Custom ListView Adapter in Android

+1 Sandeep Mukundan · November 20, 2015
I am Learning to create custom ListViews. 

I have created a seperate class (Java FIle) for the Adapter. The CustomAdapter extends BaseAdapter.

public class CustomAdapter extends BaseAdapter{

public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());

//LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


}
}


Here, I get the error of "Cannot resolve method getContext()". 
I have seen Bucky extending the CustomAdapter to ArrayAdapter. Then, there is no such error. But when i extent the class to BaseAdapter, this problem occurs. Can someone please explain this, and how to overcome it.

The other method to create the inflater, i have to call MainActivity. Android Studio says 'Main Activity is not enclosing Class '. This is because i want to create the adapter in a seperate file (to keep my code uncluttered), and not in the Main Activity Class. Can some one give a workaround to this?

Post a Reply

Replies

Oldest  Newest  Rating
0 Dol Lod · November 22, 2015
Is there any reason you are extending BaseAdapter and not ArrayAdapter? I got ArrayAdapter to work really well with my code although I did not learn how to do that from this site.
0 Rutaba Niazi · November 22, 2015
It gives error because your adapter class doesn't have any context... only activities have their contexts not classes we create...
So, what I do is, i make a constructor in my adapter class which takes two parameters, context and list... so when i call it from any activity, i pass these two things from its constructor and no need to call getContext()... u get it from the caller actvity
  • 1

Java / Android Development

107,278 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator