2016-07-26 60 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); 
    }