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.

34
Top

Care to rate this post?

Author

Branko Ajzele

Ex Inchooer

Worked at Inchoo as a Backend Developer/CTO from 2008 to 2013

Other posts from this author

Discussion 34 Comments

Add Comment
  1. I was looking exactly for this kinda stuff, to parse a json from a url.

    Mohneesh
    Android Developer

  2. Martin

    Excellent, also looking to parse json from url, 100%.
    Thanks

  3. Thanks a lot for the tutorial. simple and efficient. I was picking the hair off my head to find out the issue :)

  4. hardik

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

  5. Akshay

    Thanks dude, its a very nice tutorial,Simple and easy to understand

  6. sujal marotkar

    thank u so much for nice tutorial it will help us a lot

  7. Tuan

    Thanks million. I’m getting crazy with this issue

  8. harini

    this example is showing a force close error

  9. 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

  10. Corey

    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?

  11. Click

    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.

  12. asif

    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. asif

    Hi Thanks for the tutorial got the error i missed this line “” in xml file

  14. lunalvo

    Hi,

    Great article, I just extended it a little bit using an AsyncTask to load it on background:

    https://github.com/lunalvo/TweetTestApp

    Hope it helps someone.

  15. Lijo

    @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

  16. Lijo

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

  17. dinu

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

  18. santosh

    is is very helpful for the beginners like me thanq

  19. nitsy

    the application n has forced closed :(

  20. nitsy

    I’ve written the same code n still it shuts down forcibly.. pls help :(

  21. ravi

    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.

  22. nickky

    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..

  23. Stewart

    add

    and

    into your main.xml

  24. Tapan kshatriya

    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. :-)

  25. jayachandra

    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()));
    }

  26. Tapan kshatriya

    yup. thanks @jayachandra.

  27. seetaiah

    hai how to send application data to my server

  28. 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.

  29. Hi,

    I want to fetch data from MySQL can u provide me the whole script for this. .

    Please

    Thanks Alot in Advanced

  30. shashank prakash

    [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…..

  31. Gk

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

  32. Sandeep Reddy

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

  33. Ankur Tyagi

    find force close ……..

Add Your Comment

Please wrap all source codes with [code][/code] tags.
Top