检查密钥在共享首选项中是否存在 [英] Check if key exists in Shared Preferences

查看:61
本文介绍了检查密钥在共享首选项中是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在如下创建共享首选项

I'm creating Shared Preferences as follows

preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();

String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();

editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);

和onCreate我想在一组新的TextViews中显示这些值,但是第一次我没有在共享首选项中存储任何值,并且会得到NULL指针异常.

and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.

我想知道是否有任何内置方法可以检查SharedPreferences是否包含任何值,以便我可以检查该键是否存在,如果不存在,则替换该键.带有首选项值的一组新的TextViews.

I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.

推荐答案

尝试contains(String key)根据Javadocs进行

Try contains(String key) Accorting to the Javadocs,

检查首选项是否包含首选项.如果满足,则返回true 该首选项存在于首选项中,否则为false.

Checks whether the preferences contains a preference. Returns true if the preference exists in the preferences, otherwise false.

这篇关于检查密钥在共享首选项中是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆