【问题标题】:android shared preference is nullandroid 共享偏好为空
【发布时间】:2016-03-22 23:33:38
【问题描述】:

我在 android 中使用 shared preference 但它返回 null, 我看到了很多代码示例,但在我的代码中看不到任何错误

 SharedPreferences sp =this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    Log.v("sharedpref",""+username+": "+password);
    editor.putString("email", username);
    editor.putString("pass",password);
    editor.apply();

我正在从共享偏好中检索数据(在另一个活动中)

SharedPreferences sp =this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        Log.v("shersend",""+sp.getString("email", "Empty")+": "+sp.getString("pass", "Empty"));

            String email = sp.getString("email", "Empty");

            String pass = sp.getString("pass", "Empty");

那么我的代码有什么问题吗? 有没有更好的写法?

【问题讨论】:

  • 两个活动中的“MYPREFERENCES”常量是否相同?
  • but it return null 什么? SharedPreferencesnullusernamepasswordnull?
  • 其中的数据为空,在我的代码中打印“空”
  • 确保Log.v("sharedpref",""+username+": "+password); 这一行打印的不是空值。
  • 使用 this.getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);请看下面我的回答

标签: android sharedpreferences


【解决方案1】:

您将首选项保存在一个活动中,比如 A,在另一个活动中访问,比如 B,两个活动的上下文不同,因此无法访问首选项值,因为模式是私有的。

试试

this.getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

【讨论】:

    【解决方案2】:

    请尝试这种方式,更改此代码块

    SharedPreferences sp =this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    

    到这个代码块

    SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    

    【讨论】:

    • 您是否尝试更改 MainActivity 和您的其他活动。因为你需要同时改变两者,我尝试过这种方式并且它对我有用。希望你能解决你的问题:)
    【解决方案3】:

    使用getApplicationContext()

    SharedPreferences sp =getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        Log.v("sharedpref",""+username+": "+password);
        editor.putString("email", username);
        editor.putString("pass",password);
        editor.commit();
    

    【讨论】:

    • 他用的是apply,其实比commit好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2019-06-20
    • 2012-10-24
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多