Amix Amix - 1 year ago 103
Java Question

How can I use getcontext() in recycler adapter class?

I have adapter class that extends recyclerview.adapter and I need to use following code in this class but it has error on "this".

public void addItems(int howMany){
if (howMany > 0) {
int lastInsertedIndex = 11;
for (int i = lastInsertedIndex + 1; i <= lastInsertedIndex + howMany; i++) {
mList.add(PreferenceManager.getDefaultSharedPreferences(this).getString("Item " + i));
notifyItemInserted(mList.size() - 1);
lastInsertedIndex = lastInsertedIndex + howMany;

how to fix this error ?

Answer Source

Pass the context in the constructor of the adapter like:

Context context;
public YourAdapter( Context c) {
    this.context = c;

Now use this context in place of this.

To pass the context :

mAdapter = new YourAdapter(getContext());

If you are using your adapter from an Activity then use ActivityName.this in place of getContext().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download