【问题标题】:checking whether shared preference is null or not检查共享首选项是否为空
【发布时间】:2015-03-26 11:02:47
【问题描述】:

我正在借助此代码检查共享首选项值是否为空

    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 为空,则从远程服务器获取字符串并将其存储在 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();
  }

【问题讨论】:

  • 你怎么知道它不是空的?也许您将字符串设置为首选项的方式有问题?
  • 如何将值保存到共享首选项?
  • 将保存代码发布到共享首选项
  • 更好的IF语句if (!TextUtils.isEmpty())
  • 你把值放在哪里显示代码。

标签: android sharedpreferences


【解决方案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);

您将获得所需的值。

【讨论】:

  • 它强制关闭应用程序
  • 你可能得到空指针异常,检查str的值?
  • 是的,我得到了空指针异常,但只有当应用程序第一次运行时,因为在第二次运行时它才能正常工作。如何消除该错误??
  • 你能猜到为什么会这样吗?你能告诉我你在哪一行得到错误?
猜你喜欢
  • 2020-01-31
  • 2012-02-04
  • 1970-01-01
  • 2017-10-23
  • 2018-11-29
  • 2018-10-02
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多