0

I am creating a login logout using firebase in Android.

My code is almost done but one thing I am not able to solve is that when a user registers then the activity must be transferred to login activity from register activity. And after login, when I again open the app after some time then I want that the user need not to login again. It must be already logged in.

I have written the code which will check whether the user is already logged in or not but is unable to manage the two situations:

  1. Firstly, If I apply the code inside the onCreate of login activity: When I register after successful registration then the activity directly takes me to home activity but it needs to take me on login activity with this when I restart the app there is no need to log in again.

  2. Secondly, when I remove the code: then after successful registration, the activity normally takes me at login activity to login and when I restart the app then the problem is I need to log in again.

This is the code of login activity:

    public class LoginActivity extends AppCompatActivity {
    private Button login;
    private EditText username,password;
    private ProgressDialog progressDialog;
    private FirebaseAuth checklogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        username=findViewById(R.id.adminemail);
        password=findViewById(R.id.adminpass);

        progressDialog = new ProgressDialog(this);

        checklogin=FirebaseAuth.getInstance();


//the code for what I am talking is starting from here.
 /*if(checklogin.getCurrentUser()!=null){
    finish();
    startActivity(new Intent(getApplicationContext(),AdminHome.class));
 }*/
//till here

 }

  public void login(View view) {
   String email=username.getText().toString();
   String pass=password.getText().toString();

   if(TextUtils.isEmpty(email)){

   Toast.makeText(this, "Please enter email", Toast.LENGTH_SHORT).show();
     return;
   }
   if(TextUtils.isEmpty(pass)){
 Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
    return;
  }

        progressDialog.setMessage("Logging in...");
        progressDialog.show();

   checklogin.signInWithEmailAndPassword(email,pass)
         .addOnCompleteListener(this,new 
             OnCompleteListener<AuthResult>() {
                    @Override
    public void onComplete(@NonNull Task<AuthResult> 
      progressDialog.dismiss();
      if(task.isSuccessful()){
         finish();
      startActivity(new Intent(getApplicationContext(),AdminHome.class));
        }
       } 
    });

   }
 }


 //from here my registration activity starts
 public class RegisterActivity extends AppCompatActivity{

 private Button registeradmin;
 private EditText username;
 private EditText password;

 private ProgressDialog progressDialog;

 private FirebaseAuth mAuth;

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

    progressDialog =new ProgressDialog(this);

    mAuth=FirebaseAuth.getInstance();

    if(mAuth.getCurrentUser()!=null){
        finish();
      startActivity(new Intent(getApplicationContext(),AdminHome.class));
    }

    username=findViewById(R.id.regemail);
    password=findViewById(R.id.regpass);
    registeradmin=findViewById(R.id.register);

    //registering admin method call
    registeradmin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            register();
        }
    });
  }

//registering admin
 private void register () {
    String email = username.getText().toString();
    String pass = password.getText().toString();

    if(TextUtils.isEmpty(email)){

   Toast.makeText(this, "Please enter email", Toast.LENGTH_SHORT).show();
        return;
    }
    if(TextUtils.isEmpty(pass)){

  Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
        return;
    }

    progressDialog.setMessage("Registering Admin...");
    progressDialog.show();

    mAuth.createUserWithEmailAndPassword(email,pass)
            .addOnCompleteListener(this, new 
                OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
          if(task.isSuccessful()){
          FirebaseUser user=mAuth.getCurrentUser();
          Toast.makeText(RegisterActivity.this,"Successfully Registered",Toast.LENGTH_SHORT).show();
        Intent i = new Intent(RegisterActivity.this,LoginActivity.class);
        startActivity(i);
        finish();
       }
       else{
       Toast.makeText(RegisterActivity.this,"Could not register... Please try again",Toast.LENGTH_SHORT).show();
       }
       progressDialog.dismiss();
       }
     });
    }
   }

Actually, I expect the normal flow of app i.e after successful registration the activity must redirect me at login activity and after logging in and again restarting the app I don't need to log in again.

Orbit
  • 45
  • 7

4 Answers4

1

You need to store your username in sharedpreferences there are uncountable tutorials describing sharedpreferences if you search it,

Follow this concept also This question

Jimale Abdi
  • 2,574
  • 5
  • 26
  • 33
1

In your onStart do this -

@Override
public void onStart() {
    super.onStart();
    // Check if the user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    // do your stuff
            if (currentUser != null) {
                // go to MainActivity
            } else {
                // user doesn't exist 
            }

}

This way you don't need to be concerned about your navigation from activity to activity.

Kartik Shandilya
  • 3,796
  • 5
  • 24
  • 42
0

I think it works like the :

FirebaseAuth.getInstance().getCurrentUser()

It should return null if a user is not logged in.

Maulik Togadiya
  • 594
  • 5
  • 10
0

You may want to look into using an AuthStateListener.

List Listener will be invoked during the following events;

  • Right after the listener has been registered

  • When a user is signed in

  • When the current user is signed out
  • When the current user changes

You can use this listener to keep track of if a user is logged in or not. Docs can be found here

Sam
  • 348
  • 1
  • 10