Populate Listview from JSON
Programmer Bruce is correct, there is no default way to do this. However, there is a very clean and simple way to get this accomplished. Here is the adapter I use to handle JSONArrays.
class JSONAdapter extends BaseAdapter implements ListAdapter { private final Activity activity; private final JSONArray jsonArray; private JSONAdapter(Activity activity, JSONArray jsonArray) { assert activity != null; assert jsonArray != null; this.jsonArray = jsonArray; this.activity = activity; } @Override public int getCount() { return jsonArray.length(); } @Override public JSONObject getItem(int position) { return jsonArray.optJSONObject(position); } @Override public long getItemId(int position) { JSONObject jsonObject = getItem(position); return jsonObject.optLong("id"); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) convertView = activity.getLayoutInflater().inflate(R.layout.row, null); JSONObject jsonObject = getItem(position); return convertView; }}
Android doesn't have a ready-made adapter to populate a ListView
with a JSON array, like it does for populating a ListView
with database records.
I recommend getting comfortable with populating a Java data structure of your choice with the JSON data, and getting comfortable with working with ListViews
, populating them from different collections, with different custom rows.
Here's a simple example of populating a List
from a JSON array, and then using the List
to populate a ListView
.
import java.util.ArrayList;import java.util.List;import org.json.JSONArray;import android.app.Activity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;public class Main extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { String jsonInput = "[\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\"]"; JSONArray jsonArray = new JSONArray(jsonInput); int length = jsonArray.length(); List<String> listContents = new ArrayList<String>(length); for (int i = 0; i < length; i++) { listContents.add(jsonArray.getString(i)); } ListView myListView = (ListView) findViewById(R.id.my_list); myListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listContents)); } catch (Exception e) { // this is just an example } }}