Android:String和不匹配的共享首选项字符串

时间:2013-12-24 19:24:32

标签: android sharedpreferences

我从URL上的文本文件中抓取一个String并将其保存到sharedPreferences ...然后在下次抓取String时,它将它与存储在共享首选项中的旧文件进行比较,如果它不同则通知用户

我从url获取字符串并将其保存在sharedPreferences中,但是当我尝试将它们与if(x == y)语句进行比较时,它总是会产生不同的结果;

这是onPostExecute()

protected void onPostExecute(String result) {
    String Input;
    String oldInput;
    Input = result.toString();
    oldInput = currentSavedSettings();
    if (Input == oldInput){
        Toast.makeText(MainActivity.this, "fixed", Toast.LENGTH_LONG).show();
    } else {
        savePrefs("CURRENT_SETTINGS_FILE", Input);
        //the toasts were used to ensure that neither were returning null
        Toast.makeText(MainActivity.this, oldInput, Toast.LENGTH_LONG).show();
        Toast.makeText(MainActivity.this, Input, Toast.LENGTH_LONG).show();
        // the following is commented out until I fix this issue
        //createNotification();
    }   
}

和获得旧CURRENT_SETTINGS_FILE

的currentSavedSettings
private String currentSavedSettings() {     
    SharedPreferences sp =
        PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    String result = sp.getString("CURRENT_SETTINGS_FILE", null);
    return result;
}

这里有一个很好的衡量标准,我正在使用它来保存SharedPreference

private void savePrefs(String key, String value) {
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(MainActivity.this);
    Editor edit = sp.edit();
    edit.putString(key, value);
    edit.commit();
}

2 个答案:

答案 0 :(得分:3)

使用.equals.equalsIgnoreCase来比较字符串。

了解更多信息

How do I compare strings in Java?

答案 1 :(得分:0)

你试过吗,

passcode == pref_passcode // is not the same according to Java

String passcode;

pref_passcode.contentEquals(passcode); //try this or

pref_passcode.equals(passcode)

您应该始终使用其中一个来比较字符串。不要使用等号(==)