Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Adapter to Use - BaseAdapter or ArrayAdapter?

I have a JSON string with the multiple instances of the following

  1. Name
  2. Message
  3. Timestamp
  4. Profile photo url

I want to create a ListView where each list will have the above. Which is the better Adapter I need to extend for this particular case, to create a Custom Adapter?

like image 386
Harsha M V Avatar asked Nov 19 '11 08:11

Harsha M V


1 Answers

My assumption is that you have parsed the JSON string into an object model prior to considering either case... let's call this class Profile.

Strategy 1

An ArrayAdapter is sufficient with an overriden getView(..) method that will concatenate your multiple fields together in the way you wish.

ArrayAdapter<Profile> profileAdapter = new ArrayAdapter<Profile>(context, resource, profiles) {
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      View v;
      // use the ViewHolder pattern here to get a reference to v, then populate 
      // its individual fields however you wish... v may be a composite view in this case
   }
}

I strongly recommend the ViewHolder pattern for potentially large lists: https://web.archive.org/web/20110819152518/http://www.screaming-penguin.com/node/7767

It makes an enormous difference.

  • Advantage 1. Allows you to apply a complex layout to each item on the ListView.
  • Advantage 2. Does not require you to manipulate toString() to match your intended display (after all, keeping model and view logic separate is never a bad design practice).

Strategy 2

Alternatively, if the toString() method on your representative class already has a format that is acceptable for display you can use ArrayAdapter without overriding getView().

This strategy is simpler, but forces you to smash everything into one string for display.

ArrayAdapter<Profile> profileAdapter = new ArrayAdapter<Profile>(context, resource, profiles)
like image 50
Jonathan Schneider Avatar answered Oct 19 '22 20:10

Jonathan Schneider