11

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?

apaderno
  • 28,547
  • 16
  • 75
  • 90
Harsha M V
  • 54,075
  • 125
  • 354
  • 529

1 Answers1

10

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)
user3261344
  • 105
  • 1
  • 8
Jonathan Schneider
  • 26,852
  • 13
  • 75
  • 99
  • 4
    Overriding BaseAdapter in this case adds additional complexity with no real advantage. You will have to implement getCount(), getItemId(), getItem(..), etc and will find that your implementations are fairly boilerplate. – Jonathan Schneider Nov 19 '11 at 08:35
  • @jkschneider - perfect answer. Exactly the reasoning i needed to use the array adapter – Abhinav Gujjar Nov 19 '12 at 17:53