I want to check a string in SharedPreferences used it to store username and password, so if username and password is not null or empty it will be directed to home, otherwise if the username and password is empty it will be directed to login page.
This is my code to check the SharedPreferences string, but it is not working..
if(PreferenceConnector.USERNAME!=null){
Intent intent = new Intent(MainActivity.this,MainHome_Activity.class);
startActivity(intent);
} else {
Intent intent = new Intent(MainActivity.this,LoginFormPegawai_Activity.class);
startActivity(intent);
}
I tried to check it through toast with this code, and after I tried this, I get SharedPreferences string is not null or empty..
btn_logout_pegawai.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//remove the SharedPreferences string
PreferenceConnector.getEditor(this).remove(PreferenceConnector.USERNAME)
.commit();
PreferenceConnector.getEditor(this).remove(PreferenceConnector.PASSWORD)
.commit();
//checking the SharedPreferences string
if(PreferenceConnector.USERNAME!=null){
Toast.makeText(MainHome_Activity.this,"not null", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainHome_Activity.this,"null", Toast.LENGTH_SHORT).show();
}
}
});
How can I correctly check the SharedPreferences string whether its empty or null?
Thanks..
Do this:
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String username = myPrefs.getString("USERNAME",null);
String password = myPrefs.getString("PASSWORD",null);
if username and password are present, they will have a value otherwise they will be null.
if (username != null && password != null )
{
//username and password are present, do your stuff
}
You don't have to check their presence separately. Trying to retrieve their value will return null ( if not present ) or the value ( if present ) automatically.
public static final String DEFAULT_VALUE = "default";
public static final String ANY_FIELD = "any_field";
SharedPreferences prefs = context.getPreferences(Activity.MODE_PRIVATE);
String text = prefs.getString(ANY_FIELD, DEFAULT_VALUE);
if (text.equals(DEFAULT_VALUE)) {
//TODO:
} else {
//TODO:
}
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With