我有两个使用相同活动的片段。单击按钮时,它们会在它们之间切换。我在片段中使用Google的Firebase身份验证,但它在signInWithEmailAndPassword方法中给出了一个错误它不接受我的上下文参数。
// Define the context
private Context mContext;
public LoginFragment() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mContext = context;
}
这是登录方法
// 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");
}
}
});
}
这是我得到的错误
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)
我之前看过Android Fragment onAttach() deprecated它根本没有解决我的问题。我仍然得到错误。我的应用甚至不会启动
正在对正确的活动进行mContext,但是signInWithEmailAndPassword.addOnCompleteListener不接受上下文,那就是错误的位置
答案 0 :(得分:1)
更改addOnCompleteListener
以使用此片段使用的活动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");
}
}
});
然后,您可以删除所有mContext
字段和onAttach
覆盖