Android Receiving JSON Data from REST Service

android-http-get-jsonMost Internet services will serve “send” you the data you requested “using HTTP GET/POST request” in JSON format. If your Android app is depending on sending and receiving data over the Internet e.g. interacting with social network API, you will definitely need to deal with JSON formatted data in your apps. This article shows how to send HTTP GET request to a rest service that returns data in JSON format & how to parse received JSON data.

Objectives:

  • How to send HTTP GET request to a rest service that returns data in JSON format?
  • How to parse “read” JSON data on Android app?

Environment & Tools:

About this Sample:

 

( 1 ) Create Android Application

  • File >> New >> Android Application
  • App Name: HTTP App
  • Enter Project Name: android-http-get-json
  • Pakcage: com.hmkcode.android
  • Keep other defualt selections, go Next  till you reach Finish

( 2 ) The App Layout & Views

  • res/layout/main.xml
  • The layout is very simple. A LinearLayout with one TextView to show the connection status and one EditText to display received JSON data.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

   <TextView
        android:id="@+id/tvIsConnected"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"     
        android:background="#FF0000"
        android:textColor="#FFF"
        android:textSize="18dp"
        android:layout_marginBottom="5dp"
        android:text="is connected? " />

    <EditText
        android:id="@+id/etResponse"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:inputType="textMultiLine" >\
        <requestFocus />
    </EditText>
</LinearLayout>

( 3 ) The Activity Class

  1. onCreate() will be called when the activity is created.
  2. In onCreate() connection is checked using isConnected()
  3. In onCreate() AsyncTask is executed.
  4. AsyncTask calls GET()
  5. GET() 1. opens the connection, 2. sends GET request, 3. receives data as inputstream, 4. convert inputstream to string using convertInputStreamToString() helper method & 5. returns String result.
  6. result is passed “automatically” to onPostExecute()
  7. onPostExecute() we display result on EditText & show “Received!” on a Toast
package com.hmkcode.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity {

	EditText etResponse;
	TextView tvIsConnected;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// get reference to the views
		etResponse = (EditText) findViewById(R.id.etResponse);
		tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);

		// check if you are connected or not
		if(isConnected()){
			tvIsConnected.setBackgroundColor(0xFF00CC00);
			tvIsConnected.setText("You are conncted");
        }
		else{
			tvIsConnected.setText("You are NOT conncted");
		}

		// call AsynTask to perform network operation on separate thread
		new HttpAsyncTask().execute("http://hmkcode.appspot.com/rest/controller/get.json");
	}

	public static String GET(String url){
		InputStream inputStream = null;
		String result = "";
		try {

			// create HttpClient
			HttpClient httpclient = new DefaultHttpClient();

			// make GET request to the given URL
			HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

			// receive response as inputStream
			inputStream = httpResponse.getEntity().getContent();

			// convert inputstream to string
			if(inputStream != null)
				result = convertInputStreamToString(inputStream);
			else
				result = "Did not work!";

		} catch (Exception e) {
			Log.d("InputStream", e.getLocalizedMessage());
		}

		return result;
	}

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    public boolean isConnected(){
    	ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
    	    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    	    if (networkInfo != null && networkInfo.isConnected()) 
    	    	return true;
    	    else
    	    	return false;	
    }
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            return GET(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
        	Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
        	etResponse.setText(result);
       }
    }
}

Add the permissions the Manifest XML file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

If you run the App you will get the following output

( 4 ) Working with JSON Data

  • Now you have received the JSON you can start working with it
  • Data in this sample contains array of two articles metadata.
  • Each Article has title, url, array of categories & array of tags.
{"articleList":
	[{
		"title":"Android Internet Connection Using HTTP GET (HttpClient)",
		"url":"http://hmkcode.com/android-internet-connection-using-http-get-httpclient/",
		"categories":["Android"],
		"tags":["android","httpclient","internet"]
	},
	{
		"title":" Android | Taking Photos with Android Camera ",
		"url":"http://hmkcode.com/android-camera-taking-photos-camera/",
		"categories":["Android"],
		"tags":["android","camera"]
	}]
}
  • Remember received data is passed to result argument of AsyncTask.onPostExecute().
 protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
            etResponse.setText(result);
       }
JSONObject json = new JSONObject(result);
  • To display the received JSON in a more readable style use toString(1)
JSONObject json = new JSONObject(result);
etResponse.setText(json.toString(1));

Output:

  1. [....] is an array e.g. [ "android" , "httpclient" , "internet" ]
  2. {….} is an object e.g. { tags:[...] , categories:[...] , url:”…” , title:”…” }
  3. JSONObject can contain JSONArray
  4. JSONArray can contain JSONObject
  • Get the array of articles “articleList“, its length, get first article keys “names” & first article url.
JSONObject json = new JSONObject(result); // convert String to JSONObject
JSONArray articles = json.getJSONArray("articleList"); // get articles array
articles.length(); // --> 2
articles.getJSONObject(0) // get first article in the array
articles.getJSONObject(0).names() // get first article keys [title,url,categories,tags]
articles.getJSONObject(0).getString("url") // return an article url

 Source Code @ GitHub