检查共享首选项是否为null

时间:2015-03-26 11:02:47

标签: android sharedpreferences

我正在使用此代码

检查共享首选项值是否为null
    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为空,则从远程服务器获取字符串并将其存储在共享首选项中

这是我的代码

   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();
  }

1 个答案:

答案 0 :(得分:1)

在您的代码中执行此操作:

要保存到共享首选项:

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);

您将获得所需的价值。

相关问题