【问题标题】:How to retrieve shared preferences into a non-activity class from an activity class in Android?如何从Android中的活动类中将共享首选项检索到非活动类中?
【发布时间】:2016-06-02 16:50:28
【问题描述】:

我在活动类中有一个值。我想在非活动类中使用该值。通常,为了在活动类之间共享数据,我使用 like,

FirstActivityClass.java

SharedPreferences notification_id = getSharedPreferences("NOTIFICATION_ID", MODE_PRIVATE);
SharedPreferences.Editor notificationIDEditor = notification_id.edit();
notificationIDEditor.putString("notification_id", notificationId)                
notificationIDEditor.apply();

并在另一个类中检索 notification_id 的值,

SecondActivityClass.java

SharedPreferences notificationIDSharedRetrieve = getSharedPreferences("NOTIFICATION_ID", MODE_PRIVATE);
notificationID = notificationIDSharedRetrieve .getString("notification_id", null);

但是假设第二个类是非活动类,我如何检索非活动类中的数据?

【问题讨论】:

  • 如果 second class was a non-activity class 然后将 Context 传递给第二类以访问 getSharedPreferences 方法
  • 一些语法或有关此方法的知识会有所帮助。
  • 也许this 有帮助

标签: java android android-activity sharedpreferences


【解决方案1】:

您可以通过创建自定义构造函数将您的 Activity 上下文发送到您的 cals,例如:

class A
{
Context con;
public A(Context con)
    {
    this.con=con
    }
}



Activity B
{
Context con;
  @Override
  public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         this.con=getContext();
         A = new A(this.con);
    }
}

【讨论】:

    【解决方案2】:

    您可以缓存全局应用程序上下文。

    myApplicationContext.getSharedPreferences(NOTIFICATION_ID", MODE_PRIVATE)
    

    【讨论】:

      猜你喜欢
      • 2015-09-04
      • 2011-11-21
      • 1970-01-01
      • 2011-09-05
      • 2012-09-08
      • 2016-12-23
      • 1970-01-01
      • 2020-06-26
      • 2017-05-26
      相关资源
      最近更新 更多