Simple Android JSON parsing example with output into ListActivity

android-branko

One of my planned projects in the upcoming 2011 is the Magento – Android application. I already did a fair part on the Android side, plus I started the Magento Mapy extension few weeks ago. Due to my recent one month vacation I was “off the grid” when it comes to my free time work so all my stuff were in a “pause mode”.

Besides my playing around with Android and XML-RPC, here is a simple JSON parsing example that might get you started with more serious things.

In this example, I am connecting to Twitters public timeline JSON url.

package net.inchoo.demo.andy1;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
 
public class HomeActivity extends ListActivity {
 
    /** Called when the activity is first created. */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
		setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));        
    }
 
	public ArrayList<String> fetchTwitterPublicTimeline()
    {
    	ArrayList<String> listItems = new ArrayList<String>();
 
    	try {
			URL twitter = new URL(
					"http://twitter.com/statuses/public_timeline.json");
			URLConnection tc = twitter.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					tc.getInputStream()));
 
			String line;
			while ((line = in.readLine()) != null) {
				JSONArray ja = new JSONArray(line);
 
				for (int i = 0; i < ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);
					listItems.add(jo.getString("text"));
				}
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listItems;
    }
}

Please direct your attention on the listItems.add(jo.getString(“text”)); line. This is the part that I am grabbing a “text” attribute/property of single JSON object. To get a more “visual” picture of all available attributes/properties you might want to take a look at the XML version of twitters public timeline. This way you will get nice colored XML in your browser, where you can see all available attributes.

Cheers.

Interested in hiring us?

Have a chat with us. You would be surprised how small changes can make your business even more successful.


34 comments

  1. This Sample Project is showing a force close error.. whether any changes in xml file

  2. I want to check some data from android to MySQL can u provide me the whole script for this. . !

  3. [2012-06-22 19:51:26 – jason_example5] Failed to install jason_example5.apk on device ‘emulator-5554′: EOF
    [2012-06-22 19:51:26 – jason_example5] java.io.IOException: EOF
    [2012-06-22 19:51:26 – jason_example5] Launch canceled!
    ven i m launching this code its showing the above error ?i m new to android so please help me out in that.
    i have created xml which contains image view ,text view,buttons .so i wantes to reterive all images so anyone can tell me how to do that…..

  4. Thanks for the article,
    Can you please write any article that something like this:
    get name from android page send it into server in POST method and again read data from server that send by JSON fromat from server and display that data in android page.

    Thanks.

  5. 1HI, nice one but you have to remove
    setContentView(R.layout.main); if you use setListAdapter.
    and add parameter after new ArrayAdapter. no need of setcontentview()
    . This is the source code that I have changed :

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
    }

  6. Hi, I am newbie for android, please help me guys for following problem.
    ex. “profile_image_url”:”http:\/\/a0.twimg.com\/profile_images\/1882839203\/ThugMissez4_normal.jpg”

    i’m having same kind of json string and i want load and display this kind of image in my imageview
    ex.
    Bitmap bmp = BitmapFactory.decodeFile(jo.getString(“Picurl”));
    imageurl.add(bmp);
    where imageur is Arraylist
    but i get null values. please help me out for this problem. :-)

  7. basically the core of the logic is totally worng,

    String line;
    while ((line = in.readLine()) != null) {
    JSONArray ja = new JSONArray(line);

    for (int i = 0; i < ja.length(); i++) {
    JSONObject jo = (JSONObject) ja.get(i);
    listItems.add(jo.getString("text"));
    }
    }

    in this logic jsonarray cant parse a single line it needs
    the hole string of json objects..

  8. i like your tutorial.we do the json parsing using android json classes.but for parsing purpose android provides Gson API.so can u tell me wats the benifit of gsonAPI.

  9. thank you so much for the support and effort. This is what exactly i am looking for .great app :-)

  10. sorry text is not appearing just give user permission in side manifest for “android.permission.INTERNET”.

  11. @Corey,@asif:

    Just give the permission inside Android mAnifest file as

    “”

    it surely works

    and thanks Branko Ajzele for the code it is very useful one…

    requesting more like this

  12. I can’t seem to get this code to work, It just gives me a blank screen with no data. Can someone tell me what should be in my main.xml file?

  13. we have to mention url which contains result and this line should be according to the attributes in result
    listItems.add(jo.getString(“text”));
    “text” should be your attribute.

  14. I can’t seem to get this code to work, It just gives me a blank screen with no data. Can someone tell me what should be in my main.xml file?

  15. Hei Branko nice artikel! but you need to remove

    setContentView(R.layout.main); if you use setListAdapter.

    and add parameter after new ArrayAdapter. Because I am getting error from your original source code. This is the source code that I have changed :

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));  
        }

    CMIIW, Keep Posting! :D

  16. hi , i have some warnings in this code , so its not properly work. .it show warning at @SuppressWarnings({ “rawtypes”, “unchecked” }). . kindly help me . .thanx

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.