从firebase内部替换片段addOnCompleteListener

时间:2018-12-01 08:42:13

标签: android firebase android-studio android-fragments firebase-realtime-database

我试图替换firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener内部的片段。

但是我的应用程序崩溃了。请解决。这是代码: FragmentManager fm;

内部创建视图:     fm = getActivity()。getSupportFragmentManager();

通过登录按钮的onClickListener调用的

userLogin函数:

private void userLogin()
{
    String email = login_email.getText().toString().trim();
    String password = login_password.getText().toString().trim();

    if (TextUtils.isEmpty(email)) { //email is empty
        return;

    }
    if (TextUtils.isEmpty(password)) { //password empty
        return;
    }
    login_progress.setMessage("Signing in...");
    login_progress.show();

    firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>(){
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {

            if(task.isSuccessful())
            {
                login_progress.dismiss();

                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.root, new home());
                ft.commit();

            }
            else{
                login_progress.dismiss();
                Toast.makeText(getContext(),"User ID or Password incorrect!",Toast.LENGTH_LONG).show();

            }
        }
    });

}

简单的Toast语句在单击“登录”时起作用。身份验证没有问题。替换片段时出现问题。

1 个答案:

答案 0 :(得分:0)

signInWithEmailAndPassword “使用电子邮件和密码异步登录。”

您需要确保在UI线程上完成对UI的任何更改。

firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>(){
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {

        final Activity activity = getActivity();
        if (activity != null) activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(task.isSuccessful()) {
                    login_progress.dismiss();

                    FragmentTransaction ft = fm.beginTransaction();
                    ft.replace(R.id.root, new home());
                    ft.commit();

                } else {
                    login_progress.dismiss();
                    Toast.makeText(getContext(),"User ID or Password incorrect!",Toast.LENGTH_LONG).show();
                }
            }
        });
    }
});