2012-03-14 63 views
0

如果我在一個活動中設置了共享首選項,爲什麼另一個有不同的首選項?上下文變了? (但我本身使用的應用程序上下文!)共享首選項不會因活動而改變?

這裏是我的代碼

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

...

我怎樣才能讓全球喜好是sh在所有活動之中android 3.2?有沒有android提供的東西,或者我必須編寫一個保存到文件/打開文件,並將其添加到每個活動onStop()/ onCreate()?

+0

如何將'ditta_id_selezionata'添加到sharedPreferences中?首先我可以想到的是,你忘記提交()後,你可以設置值 – SERPRO 2012-03-14 16:23:29

+0

看到一個代碼spinet你把東西放在sharedpreference – Blackbelt 2012-03-14 16:23:31

+0

添加代碼,我設置sharedpref – max4ever 2012-03-16 08:45:16

回答

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

我想你已經做了類似的事情,但評論它。這應該讓您的偏好在整個應用中始終保持不變。正如你在這裏看到的,你要確保正在讀取和寫入相同的首選項文件。

+0

奇怪,它工作,即使雖然我確信我之前嘗試過...謝謝! – max4ever 2012-03-16 10:33:36

0

共享首選項在活動中保持不變。如果您看到不同的數據,那麼我預計這些值不會被保存。我認爲問題不在於閱讀數據,而在於寫作,因此請檢查您的偏好編寫代碼。