2016-07-26 23 views
0

我有一個片段,我用來從數據庫中獲取一些信息,並將它們顯示到它們各自的textviews,但有一個問題,因爲我的片段沒有得到更新的值,它仍然顯示以前的值,直到我重新啓動應用程序。我試圖使用onchangedlistener但沒有成功,有沒有人有任何想法我怎麼可以刷新和更新共享首選項而不關閉各自的片段。如何在片段中獲取更新的共享首選項值?

這裏是一段代碼,其中的問題發生了:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    view = inflater.inflate(R.layout.fragment_showinfo, null); 

    // i send my current user's id to the database, to get his info. 
    // the problems happens here because the context is loaded from getActivity() and is not closed so i can get the new values. 

    SharedPreferences prefs = getActivity().getSharedPreferences(
      "MyPrefs", MODE_PRIVATE); 
    getid = prefs.getString("currentid", null); 

    //AsyncTask class used to connect with db. 
    //on post execute it stores the info received from the db into the shared preferences. 

    Connection_db connection = new Connection_db(
      getActivity()); 
    connection.execute(connection_request, getid); 

    // i tried to reinitialize the shared prefs in order to get the new values (i tried to use the SP from above but still won't work). 
    SharedPreferences prefs_update = getActivity().getSharedPreferences(
      "MyPrefs", MODE_PRIVATE); 

    info_one = prefs_update.getString("info_one", "something"); 
    textView.setText(info_one); 
} 

回答

0

不是最簡單的無logcat的打印輸出解決,但我認爲這個問題是從這一行要來這裏:

SharedPreferences prefs = getActivity().getSharedPreferences 

我沒有在約一個月與Android合作,但如果我沒有記錯應該是:

SharedPreferences prefs = this.getActivity().getSharedPreference 

希望這有助於!

+0

我無法在片段中使用getApplicationContext。我也有一個應用程序類,從中我可以得到一個靜態的上下文,但我仍然不能得到它的工作, – Homombi

+0

對,讓我更新我的答案一秒 – Ethan

+0

我仍然無法獲得新的值,它仍然顯示以前每次我重新啓動我的應用程序 – Homombi

0

我正在使用PreferenceManager.getDefaultSharedPreferences(上下文)來獲取和更新prefergies值。 您還可以在某些類中創建靜態方法,如 ,並通過直接傳遞上下文(服務,活動等)來訪問它。

public static void setSSIDOption(Context c , Boolean b) { 

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putBoolean(IS_SSID_EXCLUDED, b); 
     editor.commit(); 

    } 

    public static Boolean getSSIDOption(Context c) { 
     SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); 
     return settings.getBoolean(IS_EXCLUDED, false); 
    }