如果我在一个活动中设置共享偏好,为什么另一个活动有不同的偏好?背景改变了? (但我使用应用程序上下文!)
这是我的代码
MyApp appState = ((MyApp)this.activity.getApplicationContext());
appState.setDittaSelezionata( (int) itemId);
...
MyApp appState = ((MyApp)this.getApplicationContext());
int ditta_id_selezionata = appState.getIdSomething();
和
public class MyApp extends Application implements Parcelable {
private SharedPreferences getSharedPrefs()
{
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//SharedPreferences settings = this.getSharedPreferences(MyApp.PREFS_NAME, this.MODE_PRIVATE);
return settings;
}
public int getIdSomething() {
SharedPreferences settings = this.getSharedPrefs();
return settings.getInt("ditta_id_selezionata", 0);
}
public void setDittaSelezionata(final int ditta_selezionata) {
SharedPreferences settings = this.getSharedPrefs();
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ditta_id_selezionata", ditta_selezionata);
// Commit the edits!
editor.commit();
}
...
如何制作android 3.2所有活动共享的全局首选项?有什么android提供或我必须编写保存到文件/打开文件并为每个活动onStop()/ onCreate()添加它?
答案 0 :(得分:0)
共享首选项会在各个活动中保持不变。如果您看到不同的数据,那么我预计这些值不会被保存。我不认为问题是阅读数据,而是写作,所以请检查您的偏好编写代码。
答案 1 :(得分:0)
试试这个。
private static final String APP_PREF = "application_preference";
private static final String DITTA = "ditta_id_selezionata";
public class MyApp extends Application implements Parcelable {
private SharedPreferences getSharedPrefs(){
SharedPreferences settings = getApplicationConext().getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
return settings;
}
public int getIdSomething() {
SharedPreferences settings = this.getSharedPrefs();
return settings.getInt(DITTA, 0);
}
public void setDittaSelezionata(final int ditta_selezionata) {
SharedPreferences settings = this.getSharedPrefs();
SharedPreferences.Editor editor = settings.edit();
editor.putInt(DITTA, ditta_selezionata);
// Commit the edits!
editor.commit();
}
我认为你做过类似的事,但对此进行了评论。这应该使您的偏好在整个应用程序中保持不变。如您所见,您确保正在读取和写入相同的首选项文件。