FirebaseAuth listener giving null pointer

Aakash

I am making a splash screen for my app. While loading of the splash screen I wanted to check if user is logIn or not.

If user is Login then i want to show him main activity and if not Login then i wanted to redirect him to the LoginActivitiy.

I am using firebase as my backend and i am checking the user on the Asynctask. This thing i have seen at here.

I have added the FirebaseAuth listener in onStart().

I have understood that why it is giving me error but i don't understand where to add it so that my app runs fine.

if Anyone could help me out OR give some better suggestion to do the same will be helpfull.
Thanks in adavance..

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();

        }

    }

}

Log

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) 
Rahul Chandrabhan

Simple use this, I personally refer this method:

    //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 \\
    }

You can put this code in onCreate() method, and can send user to main activity if user is logged in, else send user to login screen

For your splash screen:

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 \\

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

null subjectline giving null pointer exception

twitter getOAuthAccessToken giving null pointer exception

Google Maps giving null pointer while loading

InputStream.getResourceAsStream() giving null pointer exception

ActionBarSherlock giving null pointer exception getSupportActionBar() on internationalization

Kotlin Android Extensions giving Layout Null Pointer

Spring Query DSL Giving Null Pointer Exception

Codenameone plugin giving null pointer exception

Struts 2 File Upload giving NULL Pointer

toggle button mouse listener null pointer exception

deallocation of same pointer twice not giving error if I make the pointer NULL

My app get crashes because of Null pointer exception for firebaseAuth.getUid()

Array Adaption giving null pointer Exception while populating listView

Communicating between Dynamically Created Fragment giving Null Pointer Exception

Android BroadcastReceiver in Service giving null pointer exception when sending broadcast to it

Android JUnit test for retrofit2 giving null pointer exception

Setting edit text of fragment from Activity giving null pointer

Spark giving Null Pointer Exception while performing jdbc save

Play Sound on Button Click in Android giving Null Pointer Exception

Null Pointer Exception error on Giving Video View a Video path

list view of Navigation drawer giving null pointer error

Android Listview adapter giving null pointer exception in fragment

I have an 'if' statement for checking null pointer exception but that line itself is giving a null pointer excpetion

Null pointer with Firebase auth. How to put listener to another class

ListView item long click listener throwing a null pointer exception

Null Pointer Exception while implementing SeekBar Listener interface in Android

Getting Null Pointer exception in setting recycler item click listener

Giving onBindViewHolder listener AlertDialog

Pause and resume FirebaseAuth state changes listener in flutter