2012-04-23 45 views
0

我有一個PreferenceActivity類,用於處理在我的應用程序中獲取和設置偏好設置。但是我有一個「main」Activity類,它在啓動時調用Web服務,並且基於Web服務的返回值,需要更新其中一個首選項。Android - 如何從另一個活動中設置偏好

我似乎無法得到這個工作,沒有拋出一個NullPointerException錯誤。

下面是主要的活動代碼:

protected void onPostCreate(Bundle savedInstanceState) 
{ 

    if(getWebServiceResult.equals("FALSE")) 
    { 
     //do stuff 
    } 
    else 
    { 
     myPreferences prefs = new myPreferences();    
     prefs.updateMyChoice("TRUE"); 
    } 
} 

這裏是從拋出錯誤的PreferenceActivity類的代碼:

public void updateMyChoice(String newText) 
{ 
    if(subscriber_opt_in == null) //this is coming up null 
    { 
     subscriber_opt_in = (EditTextPreference) findPreference("opt_in"); //error here 
    } 
    subscriber_opt_in.setText(newText); 
    subscriber_opt_in.setSummary(newText); 
} 

我需要知道如何正確地更新這個偏好。如果在主Activity類中有辦法做到這一點,那更好,但如果我必須通過PreferenceActivity類來完成,我只需要了解如何去做。

謝謝!

+0

什麼是myPreferences? – JRaymond 2012-04-23 21:41:35

+0

瞭解如何使用SharedPreferences。您可以輕鬆地從應用程序中的任何活動讀取/寫入它們 – kmb64 2012-04-23 21:53:39

+0

myPreferences是PreferenceActivity類的名稱。 – JMax2012 2012-04-24 11:47:47

回答