DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Advanced Auto Loader Patterns for Large-Scale JSON and Semi-Structured Data
  • From 13,000 to 20,000+ Endpoints: Architecting Forensics for the Remote Workforce
  • Architecting Scalable JSON Pipelines: The Power of a Single PySpark Schema

Trending

  • The Twelve-Factor Agents: Building Production-Ready LLM Applications
  • Vision-Language Models in 2026: From Research Breakthroughs to Cloud-Native Production Systems
  • The Window Closes: Why I Switched to Kotlin Before the Codebase Got Too Big
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. Android Tutorial: How to Parse/Read JSON Data Into a Android ListView

Android Tutorial: How to Parse/Read JSON Data Into a Android ListView

By 
Mark Mooibroek
·
Jun. 08, 11 · News
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
260.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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){//initializeInputStream is = null;String result = "";JSONObject jArray = null;//http posttry{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 stringtry{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 objecttry{        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.

 

 

JSON Data (computing) Android (robot)

Published at DZone with permission of Mark Mooibroek. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Advanced Auto Loader Patterns for Large-Scale JSON and Semi-Structured Data
  • From 13,000 to 20,000+ Endpoints: Architecting Forensics for the Remote Workforce
  • Architecting Scalable JSON Pipelines: The Power of a Single PySpark Schema

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook