我的應用程序有2個editText。SharedPreferences不適用於EditText
我想將2個文本從EditText保存到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);
}
我的代碼有什麼問題?
請更改PREFERENCES_NAME2變量的值,因爲它與PREFERENCES_NAME的值相同。 –
爲什麼你使用兩個首選對象 –