1

I'm in

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewholder> 

When trying

SharedPreferences mySharedPrefData = getSharedPreferences("mySharedPrefData",MODE_PRIVATE);

I get as an error:

Non-static method 'getSharedPreferences(java.lang.String, int)' cannot be referenced from a static context

I tried as alternatives

Context.getSharedPreferences("mySharedPrefData",MODE_PRIVATE)

and

this.getSharedPreferences("mySharedPrefData",MODE_PRIVATE)

and declaring mySharedPrefData as static

static SharedPreference mySharedPrefData

but all throw errors.

Question: How can I get data from mySharedPrefData into the class MyAdapter?

Steven
  • 289
  • 2
  • 5
  • 14
  • Does this answer your question? [Static way to get 'Context' in Android?](https://stackoverflow.com/questions/2002288/static-way-to-get-context-in-android) – Ryan M Sep 16 '21 at 09:25

1 Answers1

2

to use the sharedPreferences you need to have the activity, so there's a lot of options here:

  • if you're using fragments then you need activity to get applicationContext, you can get an activity by calling requireActivity() on your fragment object.

  • then get a SharedPreferences reference to your data through this line of code.

Context context = requireActivity().getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
        "mySharedPrefData", Context.MODE_PRIVATE);
  • then you can send this sharedPref reference through the adapter constructor when you initialize it. so your adapter constructor code should look like this :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewholder> {
        SharedPreferences myShared ;
        public MyAdapter (SharedPreferences shared){
              myShared = shared ;
        }
}

which from now on you can use the myShared variable to access your shared preferences inside your adapter.

N.B : if you're not using fragments and initializing your adapter inside your main activity directly, then you can skip the requireActivity part and your shared preferences code will look like this instead

Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
        "mySharedPrefData", Context.MODE_PRIVATE);

Update

  • since there's some confusion let me clarify that you should use the getApplicationContext() call inside your activity, assuming you initialize your adapter in onCreate method inside activity, then your MainActivity code might look like this :
public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
       ...
       Context context = getApplicationContext();
       SharedPreferences sharedPref = context.getSharedPreferences(
        "mySharedPrefData", Context.MODE_PRIVATE);
       MyAdapter myAdapter = new myAdapter(sharedPref);
       ...
      }
}

N.B : three dots (...) means that I don't care about your code written here.

Update

  • if you don't have the permission to edit the adapter constructor parameters then what about making a setter to it.

MyAdapter.java

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewholder> {
            SharedPreferences myShared ;
            public MyAdapter (SomeOtherParameter){...}
            public void setMyShared(SharedPreferences shared){
                   myShared = shared ;    
            }
    }
  • then after initializing your adapter, you set the shared Preferences to it

MainActivity.java

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
       ...
       Context context = getApplicationContext();
       SharedPreferences sharedPref = context.getSharedPreferences(
        "mySharedPrefData", Context.MODE_PRIVATE);
       MyAdapter myAdapter = new myAdapter(SomeOtherParameter);
       myAdapter.setMyShared(sharedPref);
       ...
      }
}

N.B : if you used the code above then don't use the myShared object in any case in the adapter constructor to avoid NullPointerException

Omar Shawky
  • 1,242
  • 1
  • 12
  • 25
  • then just remove the requireActivity() call, and use `getApplicationContext()` directly, I edited the answer for you – Omar Shawky Sep 16 '21 at 08:53
  • Thanks, but I get "Cannot resolve method 'getApplicationContext' in 'MyAdapter' " – Steven Sep 16 '21 at 08:54
  • this method should be used inside an activity or using an activity object, since you didn't provide full code to how and where do you initialize your adapter, I can't but guess that you initialize it inside your activity. – Omar Shawky Sep 16 '21 at 08:56
  • please include more of your code to help me answer your question properly. – Omar Shawky Sep 16 '21 at 08:56
  • @Evenness, I've Updated my answer to clarify what I mean. – Omar Shawky Sep 16 '21 at 09:03
  • yes you should instantiate the sharedPreferences object where you instantiate the adapter but just before it so you can pass the object through the adapter constructor, like the code I included as an update. provided that you also updated the code of your adapter to include the constructor I wrote. – Omar Shawky Sep 16 '21 at 09:10
  • In MainActivity MyAdapter is already instantiated as "MyAdapter myAdapter = new myAdapter(arrayList). That arrayList contains the data that is to appear in the Recycler. So I cannot replace it with sharedPref. – Steven Sep 16 '21 at 09:16
  • well I don't know about that, you didn't include it in your code, but you can add the new parameter to the rest of parameters – Omar Shawky Sep 16 '21 at 09:19
  • Sorry for not including the code. Thought that would have been too much info. I'll try adding parameters as you suggest. – Steven Sep 16 '21 at 09:21
  • I've made another update to include the Shared Preferences object through a setter – Omar Shawky Sep 16 '21 at 09:27
  • 1
    I couldn't add sharedPref as an extra argument for MyAdapter() because the constructor of MyAdapter didn't allow for it. I changed the constructor to accept sharedPref (first had to add the field SharedPreference sharedPreferences to the MyAdapter class). IT WORKS. info of mySharedPref is now passed to myAdapter. Thank you so much for your extraordinary insight and time, Omar. – Steven Sep 16 '21 at 09:41
  • you are welcome and good luck in your app. – Omar Shawky Sep 16 '21 at 09:50
  • Thanks, but in the meantime, this question has got me blocked from asking questions on StackOverflow. Indefinitely :( – Steven Sep 17 '21 at 12:54