Firebase AuthStateListener抛出NullPointerException

时间:2017-02-21 01:14:40

标签: android firebase firebase-authentication

我不断得到这个奇怪的错误,我不能为我的生活找出它是什么。

  

java.lang.NullPointerException:尝试调用接口方法   “无效   com.google.firebase.auth.FirebaseAuth $ AuthStateListener.onAuthStateChanged(com.google.firebase.auth.FirebaseAuth)”   在null对象引用上                                                                                  在com.google.firebase.auth.FirebaseAuth $ 1.run(未知来源)

package com.workoutwager.headshot;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
 import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

private Button mSignUpBtn;
private EditText mEmailEdit;
private EditText mPasswordEdit;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthState;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FirebaseApp.initializeApp(this);
    setContentView(R.layout.activity_main);
    mSignUpBtn = (Button) findViewById(R.id.signUpBtn);
    mEmailEdit = (EditText) findViewById(R.id.emailEditText);
    mPasswordEdit = (EditText)findViewById(R.id.passwordEditText);
    mAuth = FirebaseAuth.getInstance();
    mAuthState = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser()!=null){
                //Not signed in
                Intent loginIntent = new Intent (MainActivity.this, LoginActivity.class);
                loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(loginIntent);
            }
            else {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        }
    };


    }
@Override
public void onStart(){
    super.onStart();
    mAuth.addAuthStateListener(mAuthState);
}
}

1 个答案:

答案 0 :(得分:0)

如果firebaseAuth.getCurrentUser()==null表示用户未登录。如果这是真的,那么它应该转到LoginActivity

因此您的代码应为:

if (firebaseAuth.getCurrentUser()==null){
   //Not signed in
   Intent loginIntent = new Intent (MainActivity.this, LoginActivity.class);
   loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   startActivity(loginIntent);
}