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

Code From the Video

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

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">
  <TextView
    android:id="@+id/line1"
    style="@android:style/TextAppearance.Medium"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
  <TextView
    android:id="@+id/line2"
    style="@android:style/TextAppearance.Medium"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
  <TextView
    android:id="@+id/line3"
    style="@android:style/TextAppearance.Medium"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java

package com.newthinktank.jsonparser;

import java.util.ArrayList;
import java.util.List;

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.JSONArray;
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 yahooStockInfo = "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20yahoo.finance.quote%20where%20symbol" + "%20in%20(%22YHOO%22)&format=json&env=store%3A%2F%2" + "Fdatatables.org%2Falltableswithkeys&callback=cbfunc";

	// Will hold the values I pull from the JSON 
	static String stockSymbol = "";
	static String stockDaysLow = "";
	static String stockDaysHigh = "";
	static String stockChange = "";

	@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<String, String, String> {

		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(yahooStockInfo);
			
			// 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 {

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

				// 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 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");
				
				// Get the JSON Strings in the quote object
				stockSymbol = quoteJSONObject.getString("symbol");
				stockDaysLow = quoteJSONObject.getString("DaysLow");
				stockDaysHigh = quoteJSONObject.getString("DaysHigh");
				stockChange = quoteJSONObject.getString("Change");
				
				// EXTRA STUFF THAT HAS NOTHING TO DO WITH THE PROGRAM
				
				Log.v("SYMBOL ", stockSymbol);
				Log.v("Days Low ", stockDaysLow);
				Log.v("Days High ", stockDaysHigh);
				Log.v("Change ", stockChange);
				
				// GET ARRAY DATA
				JSONArray queryArray = quoteJSONObject.names();
				
				List<String> list = new ArrayList<String>();
				for (int i=0; i<queryArray.length(); i++) {
				    list.add( queryArray.getString(i) );
				}
				
				for(String item : list){
					
					Log.v("JSON ARRAY ITEMS ", item);
					
				}
				// END OF GET ARRAY DATA

				// Gets the first item in the JSONObject
				JSONArray objectArray = resultsJSONObject.names();

				// Prints out that first item in the JSONObject
				Log.v("JSON NEXT NODE ", objectArray.getString(0));


			} 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); 
			TextView line2 = (TextView)findViewById(R.id.line2); 
			TextView line3 = (TextView)findViewById(R.id.line3); 

			// Change the values for all the TextViews
			line1.setText("Stock: " + stockSymbol + " : " + stockChange); 

			line2.setText("Days Low: " + stockDaysLow); 

			line3.setText("Days High: " + stockDaysHigh);

		}

	}

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.newthinktank.jsonparser"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-permission android:name="android.permission.INTERNET"/>
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.newthinktank.jsonparser.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

52 Responses to “Android Development 15”

  1. Josh says:

    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…

    • Derek Banas says:

      I will definitely do some tutorials on how to make nice interfaces after I cover the basics. Up next ill start down that path with fragments.

      • Jay92 says:

        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. Dardan says:

    You made a mistake main.xml is java code :p

  3. Simon says:

    Hey,
    could you make some tutorials on how to use accelerometers and gps?
    Btw great tutorials

  4. Gean says:

    I am learning android basic and found your tutorials to be one of the best! Keep posting Derek! Thanks!

  5. Michael says:

    I can’t see where onPostExecute(String result) is called.
    or how this method is called?

  6. Pavan says:

    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”);

    • Pavan says:

      Found the solution :) But still great tutorial.

      • Derek Banas says:

        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.

  7. Rubanraj says:

    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…

  8. Safo says:

    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

  9. waheed nazir says:

    // 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…

  10. Bruno Miguel says:

    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 !

  11. damon says:

    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.

    • Derek Banas says:

      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!

  12. Jarred says:

    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?

  13. Josh says:

    The top code doesn’t belong here I don’t think. It isn’t the main.xml.

    Great tutorial btw!

  14. jugal says:

    Superb tutorials but please we want to know parsing through gson……and how collection work in android.
    thanks

  15. damon says:

    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?

  16. Iduine says:

    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

  17. Binto Sebastian says:

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

  18. chris says:

    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)

  19. Dave says:

    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

  20. Benny says:

    Thanks for another well understood lecture.

    Derek is the best.

  21. Jay says:

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

    • Derek Banas says:

      Thank you :) I’ll have to test it again. Maybe something changed on Yahoos end?

      • Jay says:

        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.

        • Derek Banas says:

          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.

          • Jay says:

            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.

  22. L3G3ND says:

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

    • Derek Banas says:

      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.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Google+