2016-06-02 6 views
0

私はアクティビティクラスに値を持っています。私は、その値を非アクティビティクラスで使用したいと思います。通常、アクティビティクラスの間でデータを共有するために、私は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); 

しかし、2番目のクラスが非アクティビティクラスのデータを取得するにはどうすればよいですか?

+3

第二のクラスは、非活動class'はその後、 '' getSharedPreferences方法 –

+0

いくつかの構文、またはそのための方法論についての知識にアクセスするための第二のクラスにコンテキストを渡した '場合は、役立つだろう。たぶん – harshvardhan

+0

[この](http://stackoverflow.com/questions/3549596/sharing-data-amongst-activities-and-services)に役立ちます – GAVD

答えて

2

あなたは、例えば、カスタムコンストラクタを作成してcalssにごActivityコンテキストを送信することができます

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); 
    } 
} 
0

あなたはグローバル・アプリケーション・コンテキストをキャッシュすることができます。

myApplicationContext.getSharedPreferences(NOTIFICATION_ID", MODE_PRIVATE) 
関連する問題