Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check the SharedPreferences string is empty or null *android

Tags:

android

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..

like image 627
Christian Wibowo Avatar asked Dec 17 '12 07:12

Christian Wibowo


2 Answers

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.

like image 113
Anup Cowkur Avatar answered Nov 17 '22 02:11

Anup Cowkur


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!

like image 3
Ilya Demidov Avatar answered Nov 17 '22 04:11

Ilya Demidov