Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show sharedpreference inside RecyclerView Adapter

Tags:

java

android

I have problem to pass context from Activity to Adapter.

I am calling my sharedpreference like this:

    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);

And this one need context, so i am using : getApplicationContext()

But this not work in the Adapter (RecyclerView), is there someone facing the same issue ?

Adding the adapter into the Manifest file will solve the problem ? (Just a suggestion)

like image 966
Jis Maxi Avatar asked Mar 27 '26 23:03

Jis Maxi


1 Answers

I am not sure what you are asking but here is a solution that I can think of. Pass the context of the calling activity in your adapter through constructor and then use that context.

Context ctx;

public YourAdapter(Context ctx){
    this.ctx = ctx;
}

now in your adapter you can do this

SharedPreferences pref = PreferenceManager
        .getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
like image 144
Ratul Bin Tazul Avatar answered Mar 30 '26 12:03

Ratul Bin Tazul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!