我有一个片段,我用来从数据库中获取一些信息,并将它们显示到它们各自的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);
}
我无法在片段中使用getApplicationContext。我也有一个应用程序类,从中我可以得到一个静态的上下文,但我仍然不能得到它的工作, – Homombi
对,让我更新我的答案一秒 – Ethan
我仍然无法获得新的值,它仍然显示以前每次我重新启动我的应用程序 – Homombi