检查共享首选项中是否存在密钥

时间:2012-01-06 12:07:29

标签: android sharedpreferences

我正在创建共享首选项,如下所示

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);

和onCreate我想在一组新的TextViews中显示这些值,但是我第一次没有在共享首选项中存储任何值,并且会得到一个NULL指针异常。

我想知道是否有任何内置方法可以检查SharedPreferences是否包含任何值,以便我可以检查密钥是否存在,如果不存在,则替换具有首选项值的新TextView集。

4 个答案:

答案 0 :(得分:131)

尝试contains(String key) Accorting to Javadocs,

  

检查首选项是否包含首选项。如果,则返回true   偏好存在于偏好中,否则为假。

答案 1 :(得分:21)

SharedPreferences获取值的每个方法都有默认值,如果密钥不存在,则返回

preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
    // the key does not exist
} else {
    // handle the value
}

答案 2 :(得分:9)

试试

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

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

    }

答案 3 :(得分:-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);
}