我需要在我的ArrayAdapter of NavigationDrawer中保存和检索两个字符串。首先。我宣布:
private static SharedPreferences prefs;然后在getView()方法中
SharedPreferences.Editor editor = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE).edit();
editor.putString("username", NameStr);
editor.putString("photo", urlProfile);
editor.commit();这样我就可以保存我需要的字符串了。但我不太确定,因为我从不在Adapter中使用Sharedpreferences。我怎样才能检索数据?我该把它放哪儿?谢谢
编辑:为了实现我用getView()编写的字符串
Intent intent = ((Activity) context).getIntent();
NameStr = intent.getStringExtra("username");
urlProfile = intent.getStringExtra("photo");两个字符串来自另一个活动的地方。
EDIT2:解决方案得到了解决方案,它工作得很完美:
SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS",context. MODE_PRIVATE);
if(sharedPreferences == null) return;
NameStr = sharedPreferences.getString("username", "");
urlProfile = sharedPreferences.getString("photo", "");
SharedPreferences.Editor editor = sharedPreferences.edit();
Intent intent = ((Activity) context).getIntent();
if(NameStr == null || NameStr.equals("")) {
NameStr = intent.getStringExtra("username");
editor.putString("username", NameStr);
}
if(urlProfile == null || urlProfile.equals("")) {
urlProfile = intent.getStringExtra("photo");
editor.putString("photo", urlProfile);
}
editor.apply();所有这些都在适配器结构中!
发布于 2014-11-26 20:43:04
您可以使用以下方法检索数据:
SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
String photo = sharedPreferences.getString("photo", "");还喜欢使用editor.apply()
https://stackoverflow.com/questions/27158234
复制相似问题