Reputation: 805
I have a value in an activity class. I want to use that value in a non activity class. Normally, to share data between activity classes, I use like,
FirstActivityClass.java
SharedPreferences notification_id = getSharedPreferences("NOTIFICATION_ID", MODE_PRIVATE);
SharedPreferences.Editor notificationIDEditor = notification_id.edit();
notificationIDEditor.putString("notification_id", notificationId)
notificationIDEditor.apply();
And to retrieve the value of notification_id in another class,
SecondActivityClass.java
SharedPreferences notificationIDSharedRetrieve = getSharedPreferences("NOTIFICATION_ID", MODE_PRIVATE);
notificationID = notificationIDSharedRetrieve .getString("notification_id", null);
But suppose the second class was a non-activity class, how can I retrieve the data in a non-activity class?
Upvotes: 0
Views: 165
Reputation: 29
You can cache the global Application context.
myApplicationContext.getSharedPreferences(NOTIFICATION_ID", MODE_PRIVATE)
Upvotes: 0
Reputation: 3439
you can send your Activity context to your calss by creating a custom constructor for example:
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);
}
}
Upvotes: 2