首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ArrayAdapter使用SharedPreferences存储和检索字符串

使用ArrayAdapter使用SharedPreferences存储和检索字符串
EN

Stack Overflow用户
提问于 2014-11-26 20:24:59
回答 1查看 630关注 0票数 1

我需要在我的ArrayAdapter of NavigationDrawer中保存和检索两个字符串。首先。我宣布:

代码语言:javascript
复制
private static SharedPreferences prefs;

然后在getView()方法中

代码语言:javascript
复制
SharedPreferences.Editor editor = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE).edit();
        editor.putString("username", NameStr);
        editor.putString("photo", urlProfile);
        editor.commit();

这样我就可以保存我需要的字符串了。但我不太确定,因为我从不在Adapter中使用Sharedpreferences。我怎样才能检索数据?我该把它放哪儿?谢谢

编辑:为了实现我用getView()编写的字符串

代码语言:javascript
复制
Intent intent = ((Activity) context).getIntent();
            NameStr = intent.getStringExtra("username");
            urlProfile = intent.getStringExtra("photo");

两个字符串来自另一个活动的地方。

EDIT2:解决方案得到了解决方案,它工作得很完美:

代码语言:javascript
复制
  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();

所有这些都在适配器结构中!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-26 20:43:04

您可以使用以下方法检索数据:

代码语言:javascript
复制
SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
String photo = sharedPreferences.getString("photo", "");

还喜欢使用editor.apply()

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27158234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档