-1

I have created one login page for two users, log in as a user and log in as admin, and save user session using share preferences, want to switch between two activity using share preference. if logined user is admin it starts admin activity and if logined user is user it starts another activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    email = findViewById(R.id.email);
    password = findViewById(R.id.password);
    checkedStatus = findViewById(R.id.checkbox);
    radioGroup2 = findViewById(R.id.workeroruser);
    userData = new ArrayList<>();
    if(SharedPreferences.getmInstance(this).isLoggedIn()){
        if(SharedPreferences.getmInstance(this).getAccountu()=="Admin"){
                finish();
                startActivity(new Intent(this,AdminViewActivity.class));
                return;
         }else if (SharedPreferences.getmInstance(this).getAccountu()=="User"){
              finish();
              startActivity(new Intent(this,UserViewActivity.class));
         }
     }
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
Mina
  • 47
  • 1
  • 9

1 Answers1

0

Strings are compared using equals method, but you are trying to compare them using == operator, this is the cause of your issue, You need to update your comparisons as following

if(SharedPreferences.getmInstance(this).getAccountu().equals("Admin")){
    startActivity(new Intent(this,AdminViewActivity.class));
    finish();
 }
 else if (SharedPreferences.getmInstance(this).getAccountu().equals("User")){
      finish();
      startActivity(new Intent(this,UserViewActivity.class));
 }

This should start your desired Activity, given that you have stored correct value in shared pref when user logged in.

mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
  • I did this, always the first condition executes, even I log in as a User it saves the session and then starts AdminViewActivity. – Mina Jul 19 '21 at 15:53
  • Then you are not correctly updating SharedPrefs when you log in. – mightyWOZ Jul 19 '21 at 15:55
  • but I can get the user name and email from Sharedprefrences correctly. when I login as User I get user account info and when log in as Admin I get Admin account info. – Mina Jul 19 '21 at 16:00
  • What does `SharedPreferences.getmInstance(this).getAccountu()` return in each case? – mightyWOZ Jul 19 '21 at 16:03
  • public String getAccountu(){ SharedPreferences sharedPreferences=mCtx.getSharedPreferences(SHARED_PREF_NAME_Worker,Context.MODE_PRIVATE); return sharedPreferences.getString(KEY_ACCOUNT,null); } it return string – Mina Jul 19 '21 at 16:06
  • I mean what value it returns, does it return "Admin" in each case? – mightyWOZ Jul 19 '21 at 16:08
  • Yes it returns Admin, or User – Mina Jul 19 '21 at 16:09
  • If it returns `User` then else if block should execute and `UserViewActivity` should start. – mightyWOZ Jul 19 '21 at 16:13