【问题标题】:Shared Preferences not retrieving variable even after saved共享首选项即使在保存后也不会检索变量
【发布时间】:2018-02-19 21:54:12
【问题描述】:

所以,我一直在为学校项目开发应用程序。 基本上它所做的是用户使用 Instagram API 登录。 他的令牌保存在共享首选项中,因此用户无需在每次进入应用程序时都登录。 用户首次登录后,用户 Instagram 的全名也会保存在共享首选项中:

 SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                   editor.putString("full_name", Global.full_name);
                    editor.commit();

这是在 LoginActivity 中保存全名的代码。我已经调试了这部分代码和共享首选项以正确保存所有数据。 问题是当用户已经登录时(他登录,关闭应用程序并再次打开它)并转到 ProfileActivity 一个标签应该得到 SharedPreferences full_name 变量没有得到它。 检索数据的代码在哪里:

  SharedPreferences editor = PreferenceManager.getDefaultSharedPreferences(ProfileActivity.this);
    String full_name = editor.getString("full_name",null);

txtNomeUtilizador.setText(full_name);

当我从共享首选项中检索数据时有什么问题吗?因为当我调试时它说共享首选项中没有“full_name”变量

【问题讨论】:

  • 您获得的首选项与您保存的首选项不同。不要使用 ProfileActivity.this,而是使用 ProfileActivity.this.getApplicationContext() - 将此作为答案发布

标签: java android


【解决方案1】:

当我尝试使用您的代码保存到共享首选项时,它不起作用。 更改此代码:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                   editor.putString("full_name", Global.full_name);
                    editor.commit();

到:

        SharedPreferences.Editor editor = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
        editor.putString("full_name", Global.full_name);
        editor.apply();

您尝试使用此代码检索信息:

 SharedPreferences editor = PreferenceManager.getDefaultSharedPreferences(ProfileActivity.this);
    String full_name = editor.getString("full_name",null); 

请尝试将其更改为:

SharedPreferences prefs = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE);
 String full_name = prefs.getString("full_name", null);

关于共享参考的一些信息:

Android Shared preferences example

https://developer.android.com/training/data-storage/shared-preferences.html#java

【讨论】:

  • 成功了!谢谢。你能告诉我 getApplicationContext 有什么问题吗?
  • getApplicationContext没有问题。问题(在您的保存代码中)是您使用 prefs.edit() 而不是 sp.edit()。
猜你喜欢
  • 2012-09-10
  • 1970-01-01
  • 2019-08-02
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
相关资源
最近更新 更多