How to check SharedPreferences string empty or null * android

I want to check the line in SharedPreferences, which used it to store the username and password, so if the username and password are not null or empty, they will be redirected to the home page, otherwise, if the username and password are empty, it will be sent for login page

This is my code to check the SharedPreferences line, but it does not work.

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 verify this through a toast using this code, and after I tried this, I got a SharedPreferences string that 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 empty or null?

Thanks..

+7
source share
5 answers

Do it:

 SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); String username = myPrefs.getString("USERNAME",null); String password = myPrefs.getString("PASSWORD",null); 

if a username and password are present, they will matter, otherwise they will be empty.

 if (username != null && password != null ) { //username and password are present, do your stuff } 

You do not need to check your presence separately. Attempting to return their value will return null (if not) or value (if present) automatically.

+22
source
 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

+2
source

try it

  if(PreferenceConnector.getString("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); } 
+1
source

if (appSettings.contains (Constants.WEATHER_SUBN_POSTION)) {

  savedSubPostion = appSettings.getInt(Constants.WEATHER_SUBN_POSTION, 0); } 

First check its value

-one
source

just check the size using sp.getAll () method. size

-one
source

All Articles