0

I have 2 fragments that use the same activity. When a button is clicked they switch between them. I am using Google's Firebase authentication in the fragment but it gives me an error in the signInWithEmailAndPassword method It is not accepting my argument for context.

// Define the context
private Context mContext;

public LoginFragment() {

}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.mContext = context;
}

This is the login method

// logs the user in
private void loginUser() {

    // Get the text for email and password
    String email = loginEmail.getText().toString();
    String password = loginPassword.getText().toString();

    // Sign the user in
    mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(mContext, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {

            // TODO: Figure out how to give back certain messages
            // If the task fails
            if(!task.isSuccessful()){
                Log.i(TAG, "Username/Passowrd Combination dont match");
            }
        }
    });

}

This is the error I get

Error:(115, 66) error: no suitable method found for addOnCompleteListener(Context,<anonymous OnCompleteListener<AuthResult>>)
method Task.addOnCompleteListener(Executor,OnCompleteListener<AuthResult>) is not applicable
(argument mismatch; Context cannot be converted to Executor)
method Task.addOnCompleteListener(Activity,OnCompleteListener<AuthResult>) is not applicable
(argument mismatch; Context cannot be converted to Activity)

I have looked at Android Fragment onAttach() deprecated before It does not solve my problem at all. I still get the error. My app won't even launch

It is making mContext to the proper activity but signInWithEmailAndPassword.addOnCompleteListener is not accepting the context and that is where the error is

Community
  • 1
  • 1

1 Answers1

2

Change addOnCompleteListener to use the activity that this fragment is in using getActivity()

// Sign the user in
mAuth.signInWithEmailAndPassword(email, password)
   .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {

        // TODO: Figure out how to give back certain messages
        // If the task fails
        if(!task.isSuccessful()){
            Log.i(TAG, "Username/Passowrd Combination dont match");
        }
    }
});

you can then remove all the mContext fields and onAttach override

petey
  • 16,914
  • 6
  • 65
  • 97