【问题标题】:SharedPreferences Returns null value in another classSharedPreferences 在另一个类中返回空值
【发布时间】:2018-11-01 21:01:39
【问题描述】:

提前谢谢..!

我正在开发一个安卓应用程序。在我的应用程序中,我想在共享首选项中存储一个 id

 SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
                    SharedPreferences.Editor editor = myPrefs.edit();
                    editor.putString("MEM1", getTrackID);
                    editor.commit();

基于该 ID,我想在我的应用程序中重定向主页,这也可以正常工作..

 SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
        String username = myPrefs.getString("MEM1","");
 if(username.equalsIgnoreCase("")||username.length()==0) {
                        Intent sessionIntent = new Intent(MainActivity.this,Dashboard.class);
                        startActivity(sessionIntent);
                        finish();
                    }

现在我进入 Dashboard 类,在这个类中,共享首选项值返回为 null。 我想获得与我的应用程序的进一步处理共享偏好的 id。谁能帮帮我?

   SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
                        String username = myPrefs.getString("MEM1","");
                        Log.e(TAG, "TRackNoShared: " + username);

【问题讨论】:

  • 你确定 MEM1 之前保存过吗?
  • 什么是getTrackID
  • 是 MEM1 之前保存
  • 您是否尝试过使用 getDefaultSharedPreferences?:prefs = PreferenceManager.getDefaultSharedPreferences(this);
  • getTrackID 可能为空,请检查一次

标签: android sharedpreferences


【解决方案1】:

我通常创建一个扩展应用程序的类以进行全局配置。在课堂上,我添加以下内容

public class MyApplication extends Application {

      private static MyApplication sInstance;

     public static MyApplication getInstance() {
          return sInstance;
      }

      public static Context getAppContext() {
          return sInstance.getApplicationContext();
      }

 public static void saveToPreferences(String preferenceName, String preferenceValue) {
    SharedPreferences sharedPreferences = getAppContext().getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(preferenceName, preferenceValue);
    editor.apply();
         }

   public static String readFromPreferences(String preferenceName, int defaultValue) {
    SharedPreferences sharedPreferences = getAppContext().getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
    return sharedPreferences.getString(preferenceName, defaultValue);
     }
}

然后在您的清单中添加<application android:name=".MyApplication" 然后从任何地方我只需拨打MyApplication.saveToPreferences(KEY, VALUE) 并检索我只需拨打MyApplication.readFromPreference(KEY, Default Value)。 好消息是您可以重载方法并具有整数和布尔类型等

【讨论】:

  • 我已经添加了整个实现,省略了第一部分
  • 不要忘记将类作为应用程序名称添加到清单中
  • 默认值是什么意思
  • 您传递一个默认值,以便在它无法检索任何可能因为它未设置的情况下,它将返回默认值给您,您可以使用它来验证
  • 字符串用户名 = myPrefs.getString("MEM1","");我是这样使用的,我认为为什么它返回空值,但在我的情况下它包含数字 10 我想检索该值
猜你喜欢
  • 2016-06-18
  • 2012-09-11
  • 1970-01-01
  • 2019-12-02
  • 2013-09-13
  • 1970-01-01
  • 2013-12-06
  • 2011-11-14
  • 2019-01-12
相关资源
最近更新 更多