Home » Android » android: check if value exists in Shared Preferences

android: check if value exists in Shared Preferences

Posted by: admin February 23, 2018 Leave a comment


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.

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


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.


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


Try out

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

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


if (loadedruns == 1) {
Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_SHORT).show(); 
else {
Toast.makeText(MainActivity.this, "No. runs: " + loadedruns,
SaveRuns("runs", loadedruns);

    public void SaveRuns(String key, int value){
sharedPreferences =  PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
public void LoadRuns(){
sharedPreferences =  PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedruns = sharedPreferences.getInt("runs", 1);


Why don’t you just use try-catch block?
If you have values set and not NULL Pointer exception is thrown you will show them to the user. Otherwise you will go into the catch block where you would handle the first time load of the application.
I know it’s not “inbuilt method”, but would do the job.
Have a nice day!