我有一个片段用于从数据库中获取一些信息并将它们显示到各自的文本视图中,但是有一个问题,因为我的片段没有获得更新的值,它仍然显示以前的值,直到我重新启动该应用程序。我试图使用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 :(得分:0)
如果没有logcat打印输出,不是最容易排除故障,但我认为问题来自这一行:
SharedPreferences prefs = getActivity().getSharedPreferences
我在大约一个月内没有使用过android,但如果我没弄错的话应该是:
SharedPreferences prefs = this.getActivity().getSharedPreference
希望这有帮助!
答案 1 :(得分:0)
我使用PreferenceManager.getDefaultSharedPreferences(context)来获取和更新prefernce值。 你也可以在下面的某个类中创建静态方法 并通过直接传递上下文(服务,活动等)来访问它。
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);
}