Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get context for BaseAdapter in Android

I have a class named BinderData which extends BaseAdapter. I want to get the base class context. I tried to use getContext() but that doesn't work in case of BaseAdapter.

How can I get the Context of this class?

like image 399
Sid Avatar asked May 16 '13 18:05

Sid


People also ask

How to inflate ListView in Android?

In this case what you can do is, create a empty layout in your main activity xml. Set a ID for that. While inflating the listview, inflate it to that layout. In activity_main.

Why use notifyDataSetChanged in Android?

notifyDataSetChanged. Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

What is getView method in Android?

getView(int position, View convertView, ViewGroup parent) Get a View that displays the data at the specified position in the data set. abstract int. getViewTypeCount() Returns the number of types of Views that will be created by getView(int, View, ViewGroup) .


3 Answers

One more solution-

If you have a parent, you can directly access the context like so-

 public class SampleAdapter extends BaseAdapter {

            LayoutInflater inflater;

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if(inflater == null){
                Context context = parent.getContext();
                inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                }
                ...
                ...

                return convertView;
            }

    }
like image 161
My God Avatar answered Oct 13 '22 07:10

My God


Make a constructor that takes a Context as one of its arguments and store it in a private variable.

public class SampleAdapter extends BaseAdapter {
    private Context context;

    public SampleAdapter(Context context) {
        this.context = context;
    }

    /* ... other methods ... */
}
like image 31
Karakuri Avatar answered Oct 13 '22 05:10

Karakuri


Context context = parent.getContext();
like image 5
Ajay Pandya Avatar answered Oct 13 '22 06:10

Ajay Pandya