Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSONArray to ListView?

I have a code which does following -

  1. Connect to a web service via HttpClient to PHP file
  2. Returns a result from an SQL query
  3. Returns format is a jArray (a JSONArray)

for(int i=0; i < jArray.length() ; i++) {
    json_data = jArray.getJSONObject(i);
    int id=json_data.getInt("id");
    String name=json_data.getString("name");
    Log.d(name,"Output");
}

When I look at the LogCat, I see all the "names" of the query, Each record is printed. I just need to plug these results into a ListView. How can I accomplish this ?

PS - I do not have a separate class for an ArrayAdapter. Could this be the reason ?

like image 607
Beetle Avatar asked Dec 22 '22 01:12

Beetle


1 Answers

If you just want to display a list of textViews you don't need to override anything, you can just add all of the items into an arrayList and use an arrayAdapter.

Put a list view in your xml that is named android:list and then create your arrayAdapter with the textView you want to use.

After that all you have to do is call setListAdapter(mArrayAdapter) and it should populate your list.

ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
    json_data = jArray.getJSONObject(i);
    int id=json_data.getInt("id");
    String name=json_data.getString("name");
    items.add(name);
    Log.d(name,"Output");
}

ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,  
           android.R.layout.simple_expandable_list_item_1, items));
setListAdapter(mArrayAdapter)

hope this helps!

like image 137
ByteMe Avatar answered Dec 23 '22 14:12

ByteMe