Digin Dominic February 2016

Convert JSON Array to display in Android List View with multiple items

I am trying to display a ListView of Items in Android from JSONArray that is given below

{"myArray":[{"id":"816","name":"Shopping","uid":"20"},{"id":"817","name":"Grocery","uid":"20"},{"id":"818","name":"Entertainment","uid":"20"},{"id":"819","name":"Maid\/Driver","uid":"20"}]}

I want to display these in Listview as given below

816 Shopping 20
817 Grocery 20
818 Environment 20
819 Maid\/Driver 20

This is the java code am working on

    JSONArray the_json_array = jObj.getJSONArray("myArray");

    List<String> list = new ArrayList<String>();
    for (int i=0; i<the_json_array.length(); i++) {
        list.add( the_json_array.getString(i) );
    }
    String[] stringArray = list.toArray(new String[list.size()]);


    final ArrayAdapter adapter = new ArrayAdapter<String>(TransactionCategory.this,android.R.layout.simple_list_item_1,stringArray);
    ListView listView = (ListView) findViewById(R.id.listView2);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

     // my actions on list items
    }
  });

I am having trouble with the for loop

I just need to get values to each item in ListView.

Answers


David Rauca February 2016

Try to use Gson to parse the json like in the code below:

public class Item {

    @SerializedName("id")
    private String id;

    @SerializedName("name")
    private String name;

    @SerializedName("uid")
    private String uid;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return id + " " + name + " " + uid;
    }
}

public class ItemList {

    @SerializedName("myArray")
    private List<Item> items;

    public List<Item> getItems() {
        if (items == null) {
            items = new ArrayList<>();
        }

        return items;
    }

}

Then change your code:

...

Gson gson = new Gson();
ItemList itemList = gson.fromJson(jObj, ItemList.class);

final ArrayAdapter adapter = new ArrayAdapter<Item>(TransactionCategory.this,android.R.layout.simple_list_item_1, itemList.getItems());
ListView listView = (ListView) findViewById(R.id.listView2);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // my actions on list items
    }
}

...

Post Status

Asked in February 2016
Viewed 2,536 times
Voted 4
Answered 1 times

Search




Leave an answer