FirebaseAuth侦听器提供空指针

时间:2018-02-22 03:41:15

标签: android android-asynctask firebase-authentication

我为我的应用制作了启动画面。在启动屏幕的加载时,我想检查用户是否登录

如果用户登录,那么我想显示他的主要活动,如果不登录,那么我想将他重定向到LoginActivitiy。

我使用firebase作为我的后端,我正在检查Asynctask上的用户。 This thing i have seen at here.

我在onStart()中添加了 FirebaseAuth侦听器。

我已经理解为什么它会给我错误但我不明白在哪里添加它以便我的应用运行正常。

如果有人可以帮助我,或者给出一些更好的建议来做同样的事情会有所帮助 谢谢你...

MainActivity.java

public class MainActivity extends AppCompatActivity {


    private FirebaseDatabase mDataBase;
    private DatabaseReference mUserDatabase;
    protected FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthStateListener;
    private String mCurrentUser;
    private static int SPLASH_TIME_OUT = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome_screen);

        mDataBase = FirebaseDatabase.getInstance();
        mUserDatabase = mDataBase.getReference("users");
        mUserDatabase.keepSynced(true);
        startProcessing();
    }

    private void startProcessing() {
     new  userCheckOperation().execute();
    }

    protected void userIsLogIn() {
        mAuth = FirebaseAuth.getInstance();
        mAuthStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() == null) {
                    Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
                    //user won't go back
                    loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(loginIntent);
                    finish();
                }
            }
        };

    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthStateListener);
    }

    private void checkUserExists() {
        if (mAuth.getCurrentUser() != null) {
            mCurrentUser = mAuth.getCurrentUser().getUid();
            mUserDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!dataSnapshot.hasChild(mCurrentUser)) {
                        Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
                        //user won't go back
                        setupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(setupIntent);
                        finish();
                    } else {
                        if (mCurrentUser.equals("nKnlkU2fWGeLlP2QDc8CLz21Fet1")) {
                            Intent admin_mainIntent = new Intent(MainActivity.this, AdminMainActivity.class);
                            //user won't go back
                            admin_mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                            startActivity(admin_mainIntent);

                            finish();
                        } else {
                            Intent user_mainIntent = new Intent(MainActivity.this, UserMainActivity.class);

                            //user won't go back
                            user_mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                            startActivity(user_mainIntent);

                            finish();
                        }

                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthStateListener != null) {
            mAuth.removeAuthStateListener(mAuthStateListener);
        }
    }

    private class userCheckOperation extends AsyncTask<Void,Void,Void>{
        @Override
        protected Void doInBackground(Void... voids) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            userIsLogIn();
            checkUserExists();

        }

    }

}

日志

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.lenovo.jdstudio, PID: 17986
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lenovo.jdstudio/com.example.lenovo.jdstudio.MainActivity}: java.lang.NullPointerException
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
                      at android.app.ActivityThread.access$800(ActivityThread.java:151)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
                      at android.os.Handler.dispatchMessage(Handler.java:110)
                      at android.os.Looper.loop(Looper.java:193)
                      at android.app.ActivityThread.main(ActivityThread.java:5333)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.NullPointerException
                      at com.example.lenovo.jdstudio.MainActivity.onStart(MainActivity.java:94)
                      at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
                      at android.app.Activity.performStart(Activity.java:5353)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2340)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429) 
                      at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342) 
                      at android.os.Handler.dispatchMessage(Handler.java:110) 
                      at android.os.Looper.loop(Looper.java:193) 
                      at android.app.ActivityThread.main(ActivityThread.java:5333) 
                      at java.lang.reflect.Method.invokeNative(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:515) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644) 
                      at dalvik.system.NativeStart.main(Native Method) 

1 个答案:

答案 0 :(得分:0)

简单使用这个,我个人推荐这个方法:

    //Get Firebase auth instance
    FirebaseAuth auth = FirebaseAuth.getInstance();
    if (auth.getCurrentUser() != null) {
        // User is logged in - send it to home screen \\
    } else {
        //User is not logged in - send it to login screen \\
    }

您可以将此代码放在onCreate()方法中,并且可以在用户登录时将用户发送到主活动,否则将用户发送到登录屏幕

对于你的启动画面:

public class SplashScreenActivity extends AppCompatActivity {

    private static final int SPLASH_TIME_OUT = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                //Get Firebase auth instance
                FirebaseAuth auth = FirebaseAuth.getInstance();
                if (auth.getCurrentUser() != null) {
                    // User is logged in - send it to home screen \\
                } else {
                    //User is not logged in - send it to login screen \\
                }
            }
        }, SPLASH_TIME_OUT);

    } // End On-Create \\

} // End Class \\