Working with REST and JSON in Android

  1. You can invoke back end services from your Android Application and a typical execution model involves invoking the services over HTTP and processing the data – in JSON format returned by them
  2. I registered for the weather update service and use this as the back end service in this application –
  3. To make sure the service is working, you can execute the URL in any browser and you will see the result, you can format the result using this free JSON formatter – Copy and paste the response and click on the process button and you will see the results in a more readable fashion.
  4. To process any JSON response, i have used a JSON Parser Class and included is the code for that
  5. public class JSONParser {static InputStream is = null;
    static JSONObject jObj = null;
    static String json = “”;

    // constructor
    public JSONParser() {


    public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    } catch (ClientProtocolException e) {
    } catch (IOException e) {

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “iso-8859-1”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    json = sb.toString();
    Log.i(“JSON Parser”, json.toString());
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    // try parse the string to a JSON object
    try {
    jObj = new JSONObject(json);
    } catch (JSONException e) {
    Log.e(“JSON Parser”, “Error parsing data ” + e.toString());

    // return JSON String
    return jObj;


  6. As of Honeycomb (SDK 11), Android prevents invoking Http Services etc. from the main thread, the asynchronous approach is the way to go. A NetworkOnMainThreadException gets thrown when you try to run an HTTP request from the main thread.
  7. Therefore you create a private class in your Activity that extends AsyncTask. The code below shows the Activity class with the private class
  8. import org.json.JSONObject;import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.widget.TextView;
    public class SecondActivity extends Activity {

    private String passedVarId = null;
    TextView textView = null;

    public void onCreate(Bundle savedInstanceState) {

    passedVarId = getIntent().getStringExtra(“ID”);
    textView = (TextView) findViewById(;
    WeatherParser task = new WeatherParser();

    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(, menu);
    return true;

    private class WeatherParser extends AsyncTask<String, String, String>{

    private String temp = “”;

    protected String doInBackground(String… uri) {
    try {
    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(“;);
    Log.i(“WeatherParser:”, json.toString());
    JSONObject currentWeather = (JSONObject)json.getJSONObject(“weather”).getJSONArray(“curren_weather”).get(0);
    temp = (String)currentWeather.get(“temp”);
    Log.i(“WeatherParser:”, temp);
    } catch (Exception e) {
    temp = “Error Getting Weather Update”;
    Log.e(“WeatherParser:”, “Error parsing data:” + e.toString());

    return temp;

    protected void onPostExecute(String result) {

  9. You will notice that in the private class I have used the JSON Parser to process the generic JSON response and then used message specific parsing of that JSON response to retrieve the details
  10. To update the data received from the Async call to UI fields in the Activity – code that logic in the onPostExecute method of the private class:protected void onPostExecute(String result) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: