Check if key exists in Shared Preferences

Vivekanand picture Vivekanand · Jan 6, 2012 · Viewed 70.2k times · Source

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.

Answer

Joshua G picture Joshua G · Jul 26, 2013

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.