Mobile Zone is brought to you in partnership with:

I'm a 27 year old software developer that mainly focuses on software development. As everyone i have taken a side in the Apple vs Android game. My choice is Android because of oh so many reasons :-) By contributing to the Android developers content online ( in the form of writing Android tutorials ), I hope to convince others to make the same decision and help them make nice content for the Android platform. Mark is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Android tutorial: How to parse / read JSON data into a Android ListView

06.08.2011
| 101373 views |
  • submit to reddit

Today we get on with our series that will connect our Android applications to internet webservices!

Next up in line: from JSON to a Listview. A lot of this project is identical to the previous post in this series so try to look there first if you have any problems. On the bottom of the post ill add the Eclipse project with the source.

For this example i made use of an already existing JSON webservice located here.

This is a piece of the JSON array that gets returned:

{"earthquakes": [
{
"eqid": "c0001xgp",
"magnitude": 8.8,
"lng": 142.369,
"src": "us",
"datetime": "2011-03-11 04:46:23",
"depth": 24.4,
"lat": 38.322
},
{
"eqid": "2007hear",
"magnitude": 8.4,
"lng": 101.3815,
"src": "us",
"datetime": "2007-09-12 09:10:26",
"depth": 30,
"lat": -4.5172
}
<--more -->

]}

So how do we get this data into our application! Behold our getJSON class!

getJSON(String url)

public static JSONObject getJSONfromURL(String url){

//initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;

//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}

//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}

//try parse the string to a JSON object
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}

return jArray;
}

The code above can be divided in 3 parts.

  1. the first part makes the HTTP call
  2. the second part converts the stream into a String
  3. the third part converts the string to a JSPNObject

Now we only have to implement this into out ListView. We can use the same method as in the XML tutorial. We make a HashMap that stores our data and we put JSON values in the HashMap. After that we will bind that HashMap to a SimpleAdapter. Here is how its done:

Implementation

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

//Get the data (see above)
JSONObject json =
JSONfunctions.getJSONfromURL("http://api.geonames.org/postalCodeSearchJSON?formatted=true&postalcode=9791&maxRows=10&username=demo&style=full");

try{
//Get the element that holds the earthquakes ( JSONArray )
JSONArray earthquakes = json.getJSONArray("earthquakes");

//Loop the Array
for(int i=0;i < earthquakes.length();i++){

HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);

map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}

 After this we only need to make up the Simple Adapter

ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });

setListAdapter(adapter);

final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")

Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();

}
});

Now we have a ListView filled with JSON data!

Here is the Eclipse project: source code

Have fun playing around with it.

 

 

References
Published at DZone with permission of Mark Mooibroek, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)