[英]How to retrieve shared preferences into a non-activity class from an activity class in Android?
我在一個活動課上有一個價值。 我想在非活動類中使用該值。 通常,要在活動類之間共享數據,我會這樣使用,
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);
但是,假設第二個類是非活動類,我該如何檢索非活動類中的數據?
您可以通過創建自定義構造函數將您的Activity上下文發送到Calss,例如:
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);
}
}
您可以緩存全局Application上下文。
myApplicationContext.getSharedPreferences(NOTIFICATION_ID", MODE_PRIVATE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.