我正试图使用片段登录或注册,在成功登录/注册后,应该加载HomeActivity
。问题是,当我单击登录/注册按钮时,它会返回到同一个片段,而不是转到HomeActivity.class
。该应用程序的初始化页面名为LoginRegistryActivity.class,它将在其中调用SignIn
片段。我确认登录/注册工作正常,但身份验证成功后无法导航到HomeActivity.class
。我不确定AndroidManifest.xml文件是否有问题。
我点击登录后出现了这个logcat错误:
java.lang.ClassCastException:com.fyp.selfzen.fragments.O_LoginRegistry.SignIn无法强制转换为java.util.courrent.Executor网址:com.fyp.selfzen.sfragments.O_LoginRegistration.SignIn.login(SignIn.java:124(网址:com.fyp.selfzen.sfragments.O_LoginRegistration.SignIn$1.onClick(SignIn.java:87(在android.view.view.performClick(view.java:7448(在android.view.view.performClickInternal(view.java:7425(在android.view.view.access$3600(view.java:810(在android.view.view$PerformClick.run(view.java:28305(在android.os.Handler.handleCallback(Handler.java:938(在android.os.Handler.dispatchMessage(Handler.java:99(在android.os.Looper.loop(Looper.java:223(在android.app.ActivityThread.main(ActivityThreads.java:7656(位于java.lang.reflect.Method.ioke(本机方法(网址:com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592(网址:com.android.internal.os.ZygoteInit.main(ZygoteNit.java:947(
SignIn.java片段
public class SignIn extends Fragment{
private EditText editText_email, editText_password;
private String email, password;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
LoginRegisrationActivity loginRegistration;
public SignIn(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
}
public static SignIn newInstance(LoginRegisrationActivity loginRegistration) {
SignIn fragment = new SignIn(loginRegistration);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_login, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_email = view.findViewById(R.id.editText_email_login_activity);
editText_password = view.findViewById(R.id.editText_password_login_activity);
TextView button_login = view.findViewById(R.id.button_login_activity);
TextView textView_signup_login = view.findViewById(R.id.textView_signup_login);
final SmoothCheckBox checkBox = view.findViewById(R.id.checkbox_login_activity);
checkBox.setChecked(false);
button_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
email = editText_email.getText().toString();
password = editText_password.getText().toString();
editText_email.clearFocus();
editText_password.clearFocus();
login(email, password);
}
});
textView_signup_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SignUp f2 = SignUp.newInstance(loginRegistration);
loginRegistration.loadFrag(f2, getResources().getString(R.string.regis));
}
});
return view;
}
public void login(String email, String password) {
editText_email.setError(null);
editText_password.setError(null);
if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if(password.isEmpty()){
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else {
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Successfully sign in!", Toast.LENGTH_LONG).show();
// Intent i = new Intent(loginRegistration, HomeActivity.class); //First try to go to HomeActivity
Intent i = new Intent(getContext(), HomeActivity.class); //Second try
startActivity(i);
//loginRegistration.finish();
} else {
Toast.makeText(getContext(), "Sign in failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
} //onComplete
}); // firebaseAuth
}// else
} // login end
}
SignUp.java碎片
public class SignUp extends Fragment{
private EditText editText_name, editText_email, editText_password, editText_phoneNo;
private String name, email, password, phoneNo;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
LoginRegisrationActivity loginRegistration;
public SignUp(LoginRegisrationActivity loginRegistration) {
this.loginRegistration = loginRegistration;
// Required empty public constructor
}
public static SignUp newInstance(LoginRegisrationActivity loginRegistration) {
SignUp fragment = new SignUp(loginRegistration);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_registration, container, false);
progressDialog = new ProgressDialog(getContext());
firebaseAuth = FirebaseAuth.getInstance();
editText_name = view.findViewById(R.id.editText_name_register);
editText_email = view.findViewById(R.id.editText_email_register);
editText_password = view.findViewById(R.id.editText_password_register);
editText_phoneNo = view.findViewById(R.id.editText_phoneNo_register);
TextView button_submit = view.findViewById(R.id.button_submit);
TextView textView_login = view.findViewById(R.id.textView_login_register);
// Go to login page
textView_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SignIn f1 = SignIn.newInstance(loginRegistration);
loginRegistration.loadFrag(f1, getResources().getString(R.string.login));
}
});
button_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = editText_name.getText().toString();
email = editText_email.getText().toString();
password = editText_password.getText().toString();
phoneNo = editText_phoneNo.getText().toString();
form();
}
});
return view;
}
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void form() {
editText_name.setError(null);
editText_email.setError(null);
editText_password.setError(null);
editText_phoneNo.setError(null);
if (name.equals("") || name.isEmpty()) {
editText_name.requestFocus();
editText_name.setError(getResources().getString(R.string.please_enter_name));
}
else if (!isValidMail(email) || email.isEmpty()) {
editText_email.requestFocus();
editText_email.setError(getResources().getString(R.string.please_enter_email));
}
else if (password.equals("") || password.isEmpty()) {
editText_password.requestFocus();
editText_password.setError(getResources().getString(R.string.please_enter_password));
}
else if (phoneNo.equals("") || phoneNo.isEmpty()) {
editText_phoneNo.requestFocus();
editText_phoneNo.setError(getResources().getString(R.string.please_enter_phone));
}
else {
editText_name.clearFocus();
editText_email.clearFocus();
editText_password.clearFocus();
editText_phoneNo.clearFocus();
}
progressDialog.setMessage("Please wait...");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getContext(), "Successfully registered!", Toast.LENGTH_LONG).show();
//Intent i = new Intent(loginRegistration, HomeActivity.class);
Intent i = new Intent(getActivity(), HomeActivity.class);
startActivity(i);
//loginRegistration.finish();
}
else{
Toast.makeText(getContext(), "Sign up failed", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
} // end of form
}
登录注册活动.class
public class LoginRegisrationActivity extends AppCompatActivity {
private String curent;
VideoView vide;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_regisration);
vide = findViewById(R.id.vide);
String video_url = "android.resource://" + getPackageName() + "/" + R.raw.login_video;
Uri videoUri = Uri.parse(video_url);
vide.setVideoURI(videoUri);
vide.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
vide.requestFocus();
vide.start();
}
});
SignIn f1 = SignIn.newInstance(this);
loadFrag(f1, getResources().getString(R.string.login));
}
public void loadFrag(Fragment f1, String name) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(!name.equals(curent)){
curent =name;
ft.replace(R.id.frame_layout, f1, name);
}
ft.commitAllowingStateLoss();
}
}
AndroidManifest.xml
<activity
android:name="com.fyp.selfzen.activities.LoginRegisrationActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.fyp.selfzen.activities.HomeActivity"
android:label="@string/title_activity_home"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
你解决问题了吗
在尝试将Fragments与FirebaseAuth一起使用时,我遇到了一个类似但不同的问题。我发现的所有文档都是使用Activities引用的。将.addOnCompleteListener
更改为.addOnSuccessListener
并添加.addOnFailureListener
使我的应用程序按预期工作。我的应用程序最初因为Executor而崩溃,尽管它可以成功地对用户进行身份验证;成功/失败的听众解决了我的问题。
我的原始代码(在Firebase Docs的帮助下编写(:
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener( (java.util.concurrent.Executor) this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(getContext(), "Successfully signed in", Toast.LENGTH_SHORT).show();
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
FragmentFactory.startAdminFragment((MainActivity) getActivity());
} else
Toast.makeText( getContext(), "Authentication failed.", Toast.LENGTH_SHORT ).show();
}
});
}
当前/工作代码:
private void authWithFirebase(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener( new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
FragmentFactory.startAdminFragment((MainActivity) getActivity());
}
})
.addOnFailureListener( new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// If sign in fails, display a message to the user.
Log.d(TAG, "signInWithEmail:failure");
Toast.makeText( getContext(), e.getMessage(), Toast.LENGTH_LONG ).show();
}
} );
}
注:
我只有1个活动,所以我可以登录并继续到我想要的片段,但你应该可以修改我的代码(FragmentFactory.startAdminFragment((MainActivity) getActivity());
(以继续到你的HomeActivity.class
这个视频帮助很大:https://www.youtube.com/watch?v=fPhy1PKR1Wg我希望这能有所帮助。
在SignIn.java和SignUp.java段中,您为firebaseAuth添加addOnCompleteListener((。所以,在里面传递参数,
而不是
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {}
收件人,
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(getContext(), new OnCompleteListener<AuthResult>() {}
如果getContext((不起作用,则尝试编写getActivity((