Marcos Guimaraes
Marcos Guimaraes

Reputation: 1295

Calling method from Activity in fragment

I have one Activity (1) that has two fragments. This Activity extends to another one (2) with base methods that I commonly use in my application. So I want to call a method from (2) after I click on one button that is located in one of the fragments from (1), what is the best way to do this?

I am trying to do it like this:

login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isValid()){
                    AndroidUtils.hideKeyboard(email, getActivity());
                    AuthenticationActivity.login(email.getText().toString(), password.getText().toString());
                }
            }
        });

But it says that a non-static method cannot be referenced from a static context. So I tried to do this:

login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isValid()){
                    AndroidUtils.hideKeyboard(email, getActivity());
                    AuthenticationActivity instance = new AuthenticationActivity();
                    instance.login(email.getText().toString(), password.getText().toString());
                }
            }
        });

But it is not working.

Upvotes: 0

Views: 460

Answers (1)

Mubashar Javed
Mubashar Javed

Reputation: 749

Try this one

((AuthenticationActivity)getActivity()).login(email.getText().toString(), password.getText().toString());

and make your login function non-static

Upvotes: 2

Related Questions