Android Development 15

Android JSON ParserIn this tutorial, I will show you how to create an Android JSON Parser. I have received this request numerous times and I will show the easiest way to parse JSON with Android without all of the extra code that confuses people.

I will be grabbing the JSON data from the URL provided by the Yahoo YQL Console. I previously used this when I covered how to parse XML with Android. All of the code used in the tutorial is provided in a package to help you learn this stuff better.

If you like videos like this, it helps to tell Google+ with a click here [googleplusone]

Code From the Video

Here is all the code in one zipped file Android JSON Parser

main.xml

MainActivity.java

AndroidManifest.xml

58 thoughts on “Android Development 15”

  1. Can you make some tutorial video about IME (Input Method. Can you show example how to make your own android keyboard. Thanks for great tutorials…

      1. Hi Derek,

        I was wondering if you help me with this program its kinda similar to your instead im using a world bank link to parse the data. Why doesnt my information show on the textview. (code is below

        package com.newthinktank.jsonparser;

        import java.io.BufferedReader;
        import java.io.InputStream;
        import java.io.InputStreamReader;

        import org.apache.http.HttpEntity;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.params.BasicHttpParams;

        import org.json.JSONException;
        import org.json.JSONObject;

        import android.app.Activity;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.util.Log;
        import android.widget.TextView;

        public class MainActivity extends Activity {

        // The JSON REST Service I will pull from
        static String url = “http://api.worldbank.org/countries/GB/indicators/SP.POP.TOTL?date=1960:2009&format=json”;
        // Will hold the values I pull from the JSON

        static String indicatorId = “”;
        static String indicatorValue = “”;
        static String countryId = “”;
        static String countryValue = “”;
        static String value2 = “”;

        static String decimal =””;
        static String date =””;

        @Override
        public void onCreate(Bundle savedInstanceState) {
        // Get any saved data
        super.onCreate(savedInstanceState);

        // Point to the name for the layout xml file used
        setContentView(R.layout.main);

        // Call for doInBackground() in MyAsyncTask to be executed
        new MyAsyncTask().execute();

        }
        // Use AsyncTask if you need to perform background tasks, but also need
        // to change components on the GUI. Put the background operations in
        // doInBackground. Put the GUI manipulation code in onPostExecute

        private class MyAsyncTask extends AsyncTask {

        protected String doInBackground(String… arg0) {

        // HTTP Client that supports streaming uploads and downloads
        DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

        // Define that I want to use the POST method to grab data from
        // the provided URL
        HttpPost httppost = new HttpPost(url);

        // Web service used is defined
        httppost.setHeader(“Content-type”, “application/json”);

        // Used to read data from the URL
        InputStream inputStream = null;

        // Will hold the whole all the data gathered from the URL
        String result = null;

        try {

        // Get a response if any from the web service
        HttpResponse response = httpclient.execute(httppost);

        // The content from the requested URL along with headers, etc.
        HttpEntity entity = response.getEntity();

        // Get the main content from the URL
        inputStream = entity.getContent();

        // JSON is UTF-8 by default
        // BufferedReader reads data from the InputStream until the Buffer is full
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, “UTF-8”), 8);

        // Will store the data
        StringBuilder theStringBuilder = new StringBuilder();

        String line = null;

        // Read in the data from the Buffer untilnothing is left
        while ((line = reader.readLine()) != null)
        {

        // Add data from the buffer to the StringBuilder
        theStringBuilder.append(line + “\n”);
        }

        // Store the complete data in result
        result = theStringBuilder.toString();

        } catch (Exception e) {
        e.printStackTrace();
        }
        finally {

        // Close the InputStream when you’re done with it
        try{if(inputStream != null)inputStream.close();}
        catch(Exception e){}
        }

        // Holds Key Value pairs from a JSON source
        JSONObject jsonObject;
        try {

        // Print out all the data read in
        // Log.v(“JSONParser RESULT “, result);

        // Get the root JSONObject
        jsonObject = new JSONObject(result);

        // Get the JSON object named query
        JSONObject indicatorJSONObject = jsonObject.getJSONObject(“indicator”);

        // Get the JSON object named results inside of the query object
        JSONObject countryJSONObject = jsonObject.getJSONObject(“country”);

        // Get the JSON Strings in the quote object
        indicatorId = indicatorJSONObject.getString(“id”);
        indicatorValue = indicatorJSONObject.getString(“value”);

        countryId = countryJSONObject.getString(“id”);
        countryValue = countryJSONObject.getString(“value”);

        value2 = jsonObject.getString(“value”);
        decimal = jsonObject.getString(“decimal”);
        date = jsonObject.getString(“date”);

        // EXTRA STUFF THAT HAS NOTHING TO DO WITH THE PROGRAM

        Log.v(“Indicator ID “, indicatorId);
        Log.v(“Indicator Value “, indicatorValue);
        Log.v(“Country ID “, countryId);
        Log.v(“country Value” , countryValue);
        Log.v(“country Value” , value2);
        Log.v(“country Value” , decimal);
        Log.v(“country Value” , date);

        } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }

        return result;

        }

        protected void onPostExecute(String result){

        // Gain access so I can change the TextViews
        TextView line1 = (TextView)findViewById(R.id.line1);

        // Change the values for all the TextViews
        line1.setText(indicatorId + indicatorValue + countryId + countryValue + value2 + decimal + date + “\n” );

        }

        }

        }

  2. Hi Derek,

    Thanks for your great tutorials, makes learning easy.

    Following your tutorial I am not able to parse the Jason object that returns an array for example below is the JSON object and I am trying to get the rowID, which I am failing. Can you point to some good reading material to learn more about the such APIs?

    {
    “entries” : [ {
    “address” : “10.x.x.x”,
    “callType” : “H323”,
    “callerId” : “YanHDX8K”,
    “duration” : 9,
    “endTime” : 1347460350000,
    “name” : “YanHDX8K”,
    “rate” : 6144,
    “rowId” : 51,
    “startTime” : 1347460341000,
    “type” : “PLACED”,
    “outgoingCall” : true
    } ],
    “next” : {
    “href” : “/rest/calllog/queries/4067-8121?start=2”,
    “rel” : “next”
    }
    }

    // Get the root JSONObject
    jsonObject = new JSONObject(result);

    // Get the JSON object named entriesJSONObject
    JSONObject entriesJSONObject = jsonObject.getJSONObject(“entries”);

    // Get the JSON Strings in the entriesJSONObject object
    rowId = entriesJSONObject.getString(“rowId”);

      1. Great! I’m glad you figured it out. I haven’t really found a good book on JSON. I learned it by reading a ton of web page articles on the rules. The same is true with Android. There are many great Android game books, but very few on basic apps.

  3. This is really a great tutorial, I was stuck up with to get the data from my sql database to my android mobile, i surfed lots of sites, but didnt get the result,,, But this tutorial helps me to get the output,,,
    Thank you…

  4. Hi Derek , thank you for your great effort in making this tutorials .. i want to ask you what steps i must take to become a professional in android development , do i need to learn the java or the xml first , and how much ? is something else is needed ? thank you again 🙂 . peace

  5. // Delete cbfunc( and ); from the
    resultsresult = result.substring(7);
    result = result.substring(0,result.length()-2);

    Hello Sir Derek .. Can you plz explain it what the purpose of the two lines of code that you used in Json parser Code…Thanks You put great Taturials…

  6. Hi Derek, what if I have a php file that connects to a mysql database and receives (and encodes the data to json) and then returns the json to data to android? What should I write in the httpPost to allow the device to connect to my PC and access the php file ? Is there any specific address for android to connect the PC or should I use my I.P address followed by the directory to the php file ?
    Awesome tutorial btw, thanks a lot! Sorry my bad English, cheers from Portugal !

  7. Hi Derek. Great tutorial.
    Do you have any examples of a form input field which will query based on the YQL query and parse the JSON?
    For instance, doing a search for stock code-microsoft (instead of hardcoding it in your example) and listing out the stock high/lows as what you showed earlier.

    If you have other tutorials to suggest, I would be keen to learn from it.
    Thanks.

    1. Thank you 🙂 I didn’t do that, but you can do that pretty easily if you spend a bit of time playing with the possible queries. You could definitely query the whole yahoo service with a bit of messing around. It sounds fun!

  8. Hello Mr. Banas,

    I’m trying to read multiple entries (for example: yahoo.finance.quote where symbol in (“YHOO”,”MSFT”)) with the code you provided but whenever I run the program the fields are blank.

    How do you read more than one item using JSON?

  9. Hi Derek,

    Great tutorial. I tried following your example and am using YQL to read json from another api.

    Up to the point of this, I am fine.
    // Get the root JSONObject
    jsonObject = new JSONObject(result);

    // Get the JSON object named query
    JSONObject queryJSONObject = jsonObject.getJSONObject(“query”);

    // Get the JSON object named results inside of the query object
    JSONObject resultsJSONObject = queryJSONObject.getJSONObject(“results”);

    // Get the JSON object named quote inside of the results object
    JSONObject quoteJSONObject = resultsJSONObject.getJSONObject(“quote”);

    Based on YQL formatted view, I noted that it goes by query->results->quote and followed by the JSONstring e.g symbol,DaysLow etc.

    However, for my api, it goes by query->results->productDetails->product and followed by a running number e.g 0,1,2 -> JSON string

    Any suggestions on how should I be editing the code to read the running number and move onto the JSON string?

      1. Derek, let me rephrase my question as I have looked at the logcat.

        Can you explain what does this code do?
        try {

        // Delete cbfunc( and ); from the results
        result = result.substring(7);
        result = result.substring(0, result.length()-2);

        I am getting org.json.JSONException: Value Z’ of type java.lang.string cannot be converted.

  10. Hi Derek, most of all, thanks for your great tutorials, it kind a help me so much! 🙂

    I’d like to know, I’ve a jsonObject to parse, but it’s rendered like an array, so i do not know how to parse it.

    The feed i retrieve is like that :

    [{“title”:”my first title”,”content”:”the first content”},{“title”:”my second title”,”content”:”the second content”}]

    I can have many items in that array, so i’d like to parse it in an arrayList, and store it in an SQLite database.

    Any idea on how to do it? Still searching on my part!

    Bye

  11. hi.. I have a project on android which is to control raspberry based robot using android WiFi. can u help me with the codes for creating an android application for this project.
    Thanks for the wonderful tutorial series…..

  12. great tutorial again!

    I couldn’t get it to work until I downloaded your source code and saw you added a line to the manifest:

    After adding that to mine it works perfectly 🙂

    (Sorry if I missed that somewhere)

  13. Hi Derek,
    Thanks for this tutorial i run correctly using the yahoo console..

    But i have a problem when i create my own php json in localhost. I used your code step by step
    when i run the the logcat says..no value for json object.

    jsonOBJ = new JSONObject();
    JSONObject shippingsJSON = jsonOBJ.getJSONObject(“shippings”);
    name = shippingsJSON.getString(“ship_name”);
    address = shippingsJSON.getString(“ship_address”);

    Thanks

  14. I just saw your tutorial – it’s great! Thanks. I continue to get an error back from Yahoo saying connection refused. Any clues?

      1. When I used YQL ‘test’, it first used HTTPS – I tried that received the refused error. Then I removed the ‘s’ and got the same thing. I substituted ‘google.com’ for the URL and that worked fine other than it didn’t like the ‘post’ method. Very weird.
        In any case your teaching style is excellent and your tutorials are very informative.

        1. Thank you for notifying me of that. I’ll look into it. I also plan on making a new Android tutorial that will cover everything i missed plus update everything that has recently changed.

          1. Hi Derek – just a quick update – this think worked from my house – not from my office – for some reason from my office yahoo reports blocked however when at home it works. Very weird. Thanks for all of your help and support.

  15. Hi Derek, nice tutorial bro, but I have some doubts as I am not familiar with Java, I want to make some changes in your app, as like I want to auto update the data in 30 mins, and use viberation alert for some results how can I include that,

    Can you also make tutorials on using viberation, calender and world time for app development please

    Cheers!!!!!

    1. Thank you 🙂 I’ll be making regular Java Android tutorials again hopefully starting this month so that I can cover what i missed and cover all the recent changes.

  16. Unfortunately I can’t see the values next to the text views..

    I get something like this on the emulator.

    Stock: :
    Days Low:
    Days High:

    Good tutorial by the way.

    1. It seems that Yahoo changed the tags for its web service. I’m going to make a new web services tutorial next so that I don’t have to worry about it changing. I’ll get it up as soon as possible.

  17. Hi Jason, many thanks for a wonderful tutorial! Can I use this JSON parser for a login system (presumably I can query my webserver with the JSON parser and get a JSON response telling me whether the login was good?) Could you potentially do a tutorial on the best way to do a web-based login? Also, how does one best achieve session behaviour (as in PHP) when navigating about the application as a signed-in user?

Leave a Reply

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