0

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?

harshvardhan
  • 765
  • 13
  • 32

2 Answers2

2

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);
    }
}
pouyan
  • 3,445
  • 4
  • 26
  • 44
0

You can cache the global Application context.

myApplicationContext.getSharedPreferences(NOTIFICATION_ID", MODE_PRIVATE)
jackson.ke
  • 29
  • 5