android – NullPointerException FirebaseAuth signInWithEmailAndPassword

我将我的Firebase signInWithEmailAndPassword()方法从我的登录活动中移到了一个单独的网络包/类中.我使用createuserWithEmailAndPassword()方法完成了这项工作,它按预期工作.但是,signInWithEmailAndPassword()方法抛出一个

java.lang.NullPointerException: Attempt to invoke virtual method
‘com.google.android.gms.tasks.Task
com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(java.lang.String,
java.lang.String)’ on a null object reference

在我的FirebaseBacked.java网络类的第116行抛出,该类由第102行的LoginActivity.java onClick()启动.

我不知道怎么从这里继续.任何有关代码示例的帮助将不胜感激.

LoginActivity:

public class LoginActivity extends FirebaseBackend {

// UI references.
private ShowPassword inputPassword;
private AutoCompleteTextView inputEmail;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.context = this;

    // Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }

    // Inflate interfaces
    setContentView(R.layout.activity_login);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    inputEmail = (AutoCompleteTextView) findViewById(R.id.email);
    inputPassword = (ShowPassword) findViewById(R.id.password);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    Button btnSignup = (Button) findViewById(R.id.btn_signup);
    Button btnLogin = (Button) findViewById(R.id.btn_login);
    Button btnReset = (Button) findViewById(R.id.btn_reset_password);

    btnSignup.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(LoginActivity.this, Registeractivity.class));
        }
    });

    btnReset.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
        }
    });

    btnLogin.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String email = inputEmail.getText().toString();
            final String password = inputPassword.getText().toString();
            View focusView;

            if (inputEmail.getText().length() == 0 || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                inputEmail.setError(getString(R.string.error_invalid_email));
                focusView = inputEmail;
                focusView.requestFocus();
                return;
            }

            if (!PasswordValidateUtility.isValidPassword(inputPassword.getText().toString().trim())) {
                inputPassword.setError(getString(R.string.error_invalid_password));
                focusView = inputPassword;
                focusView.requestFocus();
                return;
            }

            progressBar.setVisibility(View.VISIBLE);
            signInWithMyApp();
        }
    });
}

}

FirebaseBackend

public class FirebaseBackend extends AppCompatActivity {

    protected AutoCompleteTextView inputEmail;
    protected ShowPassword inputPassword;
    protected ProgressBar progressBar;
    protected FirebaseAuth auth;
    protected Context context;

    public void createNewUser() {

        String email = inputEmail.getText().toString().trim();
        String password = inputPassword.getText().toString().trim();

        progressBar.setVisibility(View.VISIBLE);

        //create user
        auth.createuserWithEmailAndPassword(email, password)
                .addOnCompleteListener(FirebaseBackend.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        progressBar.setVisibility(View.GONE);
                        /**
                         * If creating the user in the FireBase backend fails, display a message
                         * to the user with a dialog. If sign in succeeds, the auth state listener
                         * will be notified and the logic to handle the signed in user can be
                         * handled by the listener.
                         */
                        if (!task.isSuccessful()) {
                            /**
                             * FireBase Failed creating the user on the backend. Most likely because
                             * the email address is already in use or there was a connection issue.
                             * We will show the user a `Failed Dialog` and ask them to try again.
                             */
                            // Signup Failed Dialog
                            DialogChooser.failcreateuser(context);
                        } else {
                            /**
                             * The user was successfully created on the backend, so Now ask FireBase
                             * to send an authentication email to the new user.
                             */
                            sendVerificationEmail();
                        }

                    }
                });
    }

    public void sendVerificationEmail() {

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        user.sendEmailVerification()
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (!task.isSuccessful()) {
                            /**
                             * FireBase Failed to send a verification email so we will show a
                             * `Failed Send Verification Dialog` to the user, sign out the user
                             * and override the pent.
                             */
                            overridePendingTransition(0, 0);
                            FirebaseAuth.getInstance().signOut();
                            startActivity(getIntent());
                            DialogChooser.failSendVerification(context);
                        } else {
                            /**
                             * FireBase successfully sent a verification email so Now we show a
                             * `Thank-you Dialog` to the user that allows them to check their email
                             * for the verification.
                             */
                            DialogChooser.agreementAccepted(context);
                            FirebaseAuth.getInstance().signOut();
                        }
                    }
                });
    }

    public void signInWithMyApp() {

        String email = inputEmail.getText().toString();
        final String password = inputPassword.getText().toString();

        //Get Firebase auth instance - Just added
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        /**
                         * If sign in fails, display a message to the user. If sign in succeeds
                         * the auth state listener will be notified and logic to handle the
                         * signed in user can be handled in the listener
                         */
                        progressBar.setVisibility(View.GONE);

                        if (!task.isSuccessful()) {
                            /**
                             * If the user attempts to sign in with an account that is
                             * already in use, we'll show then a `FailSignIn Dialog` letting
                             * them kNow and give them the option to try with another email
                             * ID or signup with a new email address.
                             */
                            DialogChooser.failSignIn(context);
                        } else {
                            // Check if the user has been verified.
                            checkIfEmailVerified();
                        }
                    }

                });

    }

    public void checkIfEmailVerified() {

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user.isEmailVerified()) {
            /**
             * If the user is verified, finish this activity and send them to the
             * MainActivity and show a success toast message.
             */
            Toast.makeText(this, getString(R.string.toast_login_success), Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, MainActivity.class);
            this.startActivity(intent);
            finish();
        } else {
            /**
             * If the email is not verified, prompt a message to the user using
             * the `failEmailVerified` dialog and make sure the user is still
             * signed out.
             */
            progressBar.setVisibility(View.GONE);
            DialogChooser.failEmailVerified(context);
            FirebaseAuth.getInstance().signOut();
        }
    }
}

解决方法:

Frank van Puffelen的最后评论一个有效的答案.您尚未在FirebaseBackend活动中实例化auth对象.

auth = FirebaseAuth.getInstance();

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...