我正在借助这段代码检查共享首选项值是否为空
SharedPreferences myPrefo = this.getSharedPreferences("myPrefo", MODE_PRIVATE);
ostt = myPrefo.getString(Sharedprefse.KEY_FSHD, null);
if(ostt!= null && !ostt.equals(""))
{
Toast.makeText(context,"f"+ ostt, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, ostt+"n",
Toast.LENGTH_SHORT).show();
}
我的问题是,即使共享首选项不为空,每次它都返回 null
这是正确的流程还是我必须尝试其他方式??
如果 sharedpreference 为空,那么我从远程服务器获取一个字符串并将其存储在 shared preference 中
这是我的代码
if(ostt == null || ostt.matches("") || ostt.isEmpty()) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("Remote Address");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
finally {
if(!(str==null) || !(str.matches("")) || !(str.isEmpty())) {
session.createFS(str);
}
}
这是我的 createFS() 函数
public void createFS(String str){
editor.putString(KEY_FSHD, str);
editor.commit();
}
最佳答案
在你的代码中这样做:
保存到共享首选项:
public void createFS(String str){
SharedPreferences sharedPreferences = getSharedPreferences("myPrefo", Context.Mode_Private);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("KEY_FSHD", str);
editor.commit();
}
检索时
SharedPreferences myPrefo = this.getSharedPreferences("myPrefo", MODE_PRIVATE);
ostt = myPrefo.getString("KEY_FSHD", null);
您将获得所需的值。
关于android - 检查共享首选项是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29276786/