53

I'm creating Shared Preferences as follows

preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();

String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();

editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);

and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.

I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.

Kathir
  • 1,282
  • 1
  • 15
  • 19
Vivekanand
  • 755
  • 1
  • 8
  • 29

5 Answers5

152

Try contains(String key) Accorting to the Javadocs,

Checks whether the preferences contains a preference. Returns true if the preference exists in the preferences, otherwise false.

Joshua G
  • 2,086
  • 3
  • 19
  • 22
24

Every method for fetching values from SharedPreferences has default value which is returned in case the key does not exist

preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
    // the key does not exist
} else {
    // handle the value
}
Mojo Risin
  • 8,136
  • 5
  • 45
  • 58
  • 1
    This is correct, but what if the key exists, but the value is empty/null? Example: – Kevin Mar 08 '13 at 16:20
  • 58
    Even though this is the accepted answer, I'm pretty sure what the author *actually* was looking for was `preferences.contains( "unknown_key");` ... For example, if you have a boolean preference obviously it can either be true or false; if you give a default value, it will return that if it doesn't exist even though that might be an actual possible value so it wouldn't actually tell you if the preference exists or not. – fatfreddyscat Mar 22 '13 at 22:10
  • 3
    Misleading answer - actually `prefsEditor.putString("now the key exists", null).commit();` is perfectly legal, the key exists and the value is null - -1 – Mr_and_Mrs_D May 02 '13 at 18:53
12

Try out

 SharedPreferences shf = getSharedPreferences("NAME_SharedPref", MODE_WORLD_READABLE);
    String strPref = shf.getString("SERVERIP", null);

    if(strPref != null) {
    // do some thing

    }
CoolMonster
  • 2,258
  • 25
  • 50
Richa
  • 3,165
  • 1
  • 22
  • 26
0

I know this is a late answer but for those who want to know if a shared preference is either empty or zero size, you can check it two ways.

            preferences = getSharedPreferences("text", 0);
            Map<String, ?> entries = preferences.getAll();//get all entries from shared preference
            Set<String> keys = entries.keySet();//set all key entries into an array of string type

            //first option
            if(keys.isEmpty()){
                //do your staff here

            }

            //second option
            if(keys.size()==0){
                //this shows that it is empty as well
                //do your staff here

            }

           //Below is extra
           //If you want to get the names of each keys also, you can use
           //For each loop as well
           //Go through the set of keys
           for (String key : keys) {

               String keyName = key;//get each key name
           }
Yosidroid
  • 2,053
  • 16
  • 15
-1
    LoadRuns();
if (loadedruns == 1) {
Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_SHORT).show(); 
}
else {
Toast.makeText(MainActivity.this, "No. runs: " + loadedruns,
Toast.LENGTH_SHORT).show();
}
loadedruns++;
SaveRuns("runs", loadedruns);


    public void SaveRuns(String key, int value){
sharedPreferences =  PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadRuns(){
sharedPreferences =  PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedruns = sharedPreferences.getInt("runs", 1);
}
mirazimi
  • 814
  • 10
  • 11
  • Please add some context as to why this code works. Makes the answer better and more useful. Thanks! :) – AT82 Feb 11 '17 at 12:39