Home > Software design >  Android Sharedpreference Check if the user already logged in or not
Android Sharedpreference Check if the user already logged in or not

Time:08-18

I want to check if the user is logged in or not by checking if Their ID is null or not. if the ID is null then start loginActivity, if not then carry on.

I make a separate class for my sharedpreference and have imported it, declared it. however the program returned Nullpointer Error when I run it. My intention was exactly to check whether the string id is null or not.

FYI : at the moment, there is no user logged in, so the App should run the LoginActivity becauase getMyID() should return null and therefore run the condition

Please tell me where did I make mistake and how should I do it instead

my setter and getter for ID in sharedpreference :

public void setMyID(String myID) {
    editor.putString(MYUSERID, myID);
    editor.commit();
}

public String getMyID() {
    return pref_global.getString(MYUSERID, null);
}

This is my mainactivity file

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Selamat Datang");

myContext = this;
mAuth = FirebaseAuth.getInstance();
mFirebaseAnalytics = FirebaseAnalytics.getInstance(myContext);

checkLoginState();

}

public void checkLoginState(){
    if(prefManager.getMyID() == null ){
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
}

CodePudding user response:

I think default value parameter of getString(MYUSERID, "default value") is non null type, you just need to set it to another non null string. Hope it help.

CodePudding user response:

When pulling data from sharedPreferences, you can try entering "" instead of entering the default value as null. I am sharing the sample code below;

public String getMyID() {
   return pref_global.getString(MYUSERID, "");
}


public void checkLoginState(){
if(prefManager.getMyID() == ""){
    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    finish();
}

}

  • Related