-1

I want to re-use the following code:

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

if (user != null) {
    // User is signed in
    // Redirect to signed-in flow
} else {
    // No user is signed in
    // Redirect to login activity
}

But as a beginner with Java and Android, I am not sure in what way to use this code. Should i use it in a separate class and use it in a static way? If so am I correct in the following:

Create separate class called IsUserLoggedIn.java:

public class IsUserLoggedIn {    

    public static void isUserLogged() {
        if (user != null) {
        // User is signed in
        // Redirect to signed-in flow
        } else {
        // No user is signed in
        // Redirect to login activity
        }

    }        
}

and in any activity I want to check it, I put the following in onResume:

IsUserLoggedIn isUserLoggedIn = new IsUserLoggedIn();
isUserLoggedIn.isUserLogged();

Is it correct?

Fábio Nascimento
  • 2,644
  • 1
  • 21
  • 27
pileup
  • 1
  • 2
  • 18
  • 45
  • If you want to reuse it. then it should be in separate class. – Ali Ahmed Nov 29 '18 at 09:04
  • You can also check **[this](https://stackoverflow.com/questions/50885891/one-time-login-in-app-firebaseauth)** out. – Alex Mamo Nov 29 '18 at 12:32
  • Hey @Stackpile do mark the answer as correct by clicking the tick mark like V shaped button next to the answer, it should turn green. This helps future readers of the question and I'd appreciate that too. Cheers! :) – PradyumanDixit Dec 30 '18 at 04:02

1 Answers1

0

If you're using Firebase Database, then you can also save the current state of user in your database and get the answer from there only.

What I mean to say is, you can have a node named, loginStatus for every user node in your database, which you can set to true, when the user signs in or logs in, in your app, and set it to false, when user logs out.

So, a bit of code for the above thought, will look something like this:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getUid());

// put this code where you grant user the access to log in

ref.child("loginStatus").setValue(true);

// now you can retrieve the value whenever you want in your app directly without using any new class

// to set the status to false, put this code in the code where you give user the option to log-out from your app

ref.child("loginStatus").setValue(false);

Also if you want to just use another class anyway, you can put the code in a new Java class, and use the code like you showed, it looks correct mostly.

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20