4

I'm trying to put a json result in a ListView in my Android app.

This is my Json:

[
    {
        "Result": "8:30,21",
        "Meeting": "Antwerp Olympics",
        "Event": "3000m",
        "Date": "30/05/2013"
    },
    {
        "Result": "008,32",
        "Meeting": "Antwerp Olympics",
        "Event": "Long Jump",
        "Date": "30/05/2013"
    },
    {
        "Result": "6,35",
        "Meeting": "Antwerp Olympics",
        "Event": "High Jump",
        "Date": "30/05/2013"
    },
    {
        "Result": "5,00",
        "Meeting": "Antwerp Olympics",
        "Event": "Discus Throw",
        "Date": "30/05/2013"
    }
]

This is my Android code

Gson gson = new Gson();
Result[] res = gson.fromJson(results, Result[].class);
ListView lv1 = (ListView) getView().findViewById(R.id.sampleListView);
String[] values = new String[] { }; //values
ArrayAdapter<String> files = new ArrayAdapter<String>(getActivity(),android.R.layout.list_content, values);
lv1.setAdapter(files);

Getting a json result with GSON works, I did it with a simple json. Now I don't know how to implement this JSON result in my listview. How should I populate the String[] values?

Thanks in advance

3 Answers3

7

Create a Class Named EventEntity or your choise

import com.google.gson.annotations.SerializedName;

public class EventEntity{

    @SerializedName("Result")
    public int Result;

    @SerializedName("Meeting")
    public String Meeting;

    @SerializedName("Event")
    public String Event;

    @SerializedName("Date")
    public String Date;

    public EventEntity()
    {}
}

and change listview databind codes to this

ListView lv1 = (ListView) getView().findViewById(R.id.sampleListView);
Gson gson = new Gson();
List<EventEntity> events = (List<EventEntity>) gson.fromJson(results, new TypeToken<EventEntity>>() {}.getType());
ArrayAdapter<EventEntity> files = new ArrayAdapter<EventEntity>(..........);
lv1.setAdapter(files);

EDIT, you should create a custom adapter class and a row layout

public class MyCustomAdapter extends ArrayAdapter<EventEntity> {

  private final List<EventEntity> list;
  private final Activity context;

  public MyCustomAdapter (Activity context, List<EventEntity> list) {
    super(context, R.layout.rowlayout, list);
    this.context = context;
    this.list = list;
  }

  static class ViewHolder {
    protected TextView eventTitle;
    protected TextView eventDate;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;

      LayoutInflater inflator = context.getLayoutInflater();
      view = inflator.inflate(R.layout.rowlayout, null);
      final ViewHolder viewHolder = new ViewHolder();
      viewHolder.eventTitle = (TextView) view.findViewById(R.id.label);
      viewHolder.eventDate = (TextView) view.findViewById(R.id.date);

      view.setTag(viewHolder);

     ViewHolder holder = (ViewHolder) view.getTag();
     holder.eventTitle.setText(list.get(position).Event);
     holder.eventDate.setText(list.get(position).Date);

     return view;
} 
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Mehmet Emre Portakal
  • 1,774
  • 21
  • 37
  • I have a "EventEntity" class named "Result", I'm implementing your code. I'll let you know –  May 21 '13 at 19:06
  • Thanks for the answer. My app is now showing a populated listview. But it is nog correct yet. It shows for example : Result@321cd11.. What should I do? Add a toString? or adapt something in List values = (List) gson.fromJson(results, new TypeToken>() {}.getType()); ArrayAdapter files = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, values); –  May 21 '13 at 19:13
  • @AndrejHefner if you get stuck into something please let me know – Mehmet Emre Portakal May 21 '13 at 19:13
  • @AndrejHefner ok more advanced adapter to list items data corretly i will update my answer. you sould make your custom adapter – Mehmet Emre Portakal May 21 '13 at 19:15
  • @AndrejHefner i updated my answer with a custom adapter class example. dont forget to create a rowlayout on your layouts folder – Mehmet Emre Portakal May 21 '13 at 19:21
  • thanks @Amourreux I'm working in a fragment. Should that be a problem? –  May 21 '13 at 19:31
0

You can use your own class in ArrayAdapter. Like ArrayAdapter<Result[]>

I suggest you to use a class that extends ArrayAdapter<Result[]>

And override getView() method.

Use this method in getView() method: http://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder (You don't have to but for better performance.)

JustWork
  • 1,944
  • 3
  • 22
  • 34
0

Here is an example where I call a webservice and get back a result which is a list of objects. I then parse the JSON objects and put them in a list of hashmap items. The 2nd snippit of code is where I type the list of hashmap items to an actual listview. It uses a custom layout for the listview items.

List> values = new ArrayList>();
result = clsGlobals.PerformGetFromWeb(appcontext, client);

                if (result != "")
                {
                    try
                    {                               
                        JSONArray menuItems = new JSONArray(result);

                        for (int i = 0; i < menuItems.length(); i++)
                        {
                            HashMap<String, String> map = new HashMap<String, String>();
                            JSONObject jsonObject = menuItems.getJSONObject(i);

                            map.put("MenuItemID", jsonObject.getString("MenuItemID"));
                            map.put("MenuItemName", jsonObject.getString("MenuItemName"));
                            map.put("MenuItemDesc", jsonObject.getString("MenuItemDesc"));                      
                            map.put("Calories", jsonObject.getString("Calories"));
                            map.put("Protein", jsonObject.getString("Protein"));                    
                            map.put("Fat", jsonObject.getString("Fat"));                        
                            map.put("Carbohydrates", jsonObject.getString("Carbohydrates"));
                            map.put("Sodium", jsonObject.getString("Sodium"));
                            map.put("FranchiseID", jsonObject.getString("FranchiseID"));

                            values.add(map);
                        }

                        Log.d(clsGlobals.AppName, "Location menu items retrieved successfully!");
                    }


        if (values.size() > 0)
        {               

            //ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyAppDateActivity.this, R.layout.listitemlayout, values);

            String[] colsNames = new String[] {"MenuItemName", "MenuItemDesc"};
            int[] resItemsToAssign = new int[] {R.id.lstName, R.id.lstDesc};


            SimpleAdapter sa = new SimpleAdapter(appContext, values, R.layout.listitemlayout,   colsNames, resItemsToAssign );

            listViewMenu.setAdapter(sa);

        }