Android:String和共享的Preference字符串不匹配



我正在从url上的文本文件中获取一个字符串,并将其保存到sharedPreferences。。。然后,下次获取String时,它会将其与存储在共享首选项中的旧字符串进行比较,如果不同,它会通知用户。

我从url fine中获取字符串并将其保存在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_SETTING_FILE 的当前SavedSettings

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

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

更多信息

如何在Java中比较字符串?

你试过这个吗,

passcode == pref_passcode // is not the same according to Java
String passcode;
pref_passcode.contentEquals(passcode); //try this or
pref_passcode.equals(passcode)

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

最新更新