我的应用程序有2个editText。
我想将EditText中的2个文本保存到sharedpreferences然后加载它,但是当我尝试在保存后加载它时 - app会在每个editText中读取与最后一个EditText相同的文本。
private static final String PREFERENCES_NAME = "myPreferences";
private static final String PREFERENCES_NAME2 = "myPreferences";
private SharedPreferences preferences;
private SharedPreferences preferences2;
preferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
preferences2 = getSharedPreferences(PREFERENCES_NAME2, Activity.MODE_PRIVATE);
private void save() {
SharedPreferences.Editor preferencesEditor = preferences.edit();
String eTextData = eText.getText().toString();
preferencesEditor.putString(PREFERENCES_TEXT_FIELD, eTextData);
preferencesEditor.commit();
SharedPreferences.Editor preferencesEditor2 = preferences2.edit();
String eTextData2 = eText2.getText().toString();
preferencesEditor2.putString(PREFERENCES_TEXT_FIELD2, eTextData1);
preferencesEditor2.commit();
}
private void read() {
String textFromPreferences = preferences.getString(PREFERENCES_TEXT_FIELD, "");
eText.setText(textFromPreferences);
String textFromPreferences2 = preferences2.getString(PREFERENCES_TEXT_FIELD2, "");
eText2.setText(textFromPreferences2);
}
我的代码有什么问题?
答案 0 :(得分:1)
您的字符串具有相同的值:
private static final String PREFERENCES_NAME = "myPreferences";
private static final String PREFERENCES_NAME2 = "myPreferences";
所以putString会覆盖彼此。 此外,您只能为两个字符串使用1个SharedPreferences实例。
答案 1 :(得分:0)
您使用的是相同的偏好文件名"myPreferences"
。此外,没有必要使用两种不同的偏好,一种就足够了。
private static final String PREFERENCES_NAME = "myPreferences";
private SharedPreferences preferences;
preferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
private void save() {
SharedPreferences.Editor preferencesEditor = preferences.edit();
String eTextData = eText.getText().toString();
String eTextData2 = eText2.getText().toString();
//Again, PREFERENCES_TEXT_FIELD and PREFERENCES_TEXT_FIELD2 should be //different
preferencesEditor.putString(PREFERENCES_TEXT_FIELD, eTextData);
preferencesEditor.putString(PREFERENCES_TEXT_FIELD2, eTextData2);
preferencesEditor.commit();
}
private void read() {
String textFromPreferences = preferences.getString(PREFERENCES_TEXT_FIELD, "");
eText.setText(textFromPreferences);
String textFromPreferences2 = preferences.getString(PREFERENCES_TEXT_FIELD2, "");
eText2.setText(textFromPreferences2);
}
答案 2 :(得分:0)
问题可能是您的PREFERENCES_TEXT_FIELD2
和PREFERENCES_TEXT_FIELD
相等。
此外,通常您不需要SharedPreferences
的多个实例,除非您为不同的配置加载。