Android JSON Parsing From URL


JSON is one of the best method to provide data in android from web application. So I am discussing here how to parse a JSON response from a URL and use it, in this tutorial Android JSON Parsing From URL. JSON data has square and curly brackets which denotes JSON array and JSON object simultaneously.

Creating Project:
Create a new project in Eclipse IDE as “Read JSON from URL” with package com.tricks.readjsonfromurl. Now Create the main Activity as “MainActivity” and the main Layout as activity_main.

Manifest:
Just add a permission “android.permission.INTERNET” to the manifest file for access external url or address.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tricks.readjsonfromurl"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.tricks.readjsonfromurl.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>

Creating Layout:
The main layout for our project is “activity_main” which has three TextView as Label and other three for display the website ID, Name and URL of JSON object from the URL.

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textStyle="bold"
        android:textSize="18sp"
        android:text="@string/info"  />

    <TextView
        android:id="@+id/wid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="45dp"  />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="45dp"
        android:textStyle="bold"
        android:text="@string/wid" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wid"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="30dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wid"
        android:layout_marginTop="30dp"
        android:text="@string/name"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/url"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="30dp" />

    <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:layout_marginTop="30dp"
        android:textStyle="bold"
        android:text="@string/url" />

</RelativeLayout>

Creating String Values:
You should create string constants values in re/values/strings.xml to use in layout.

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Read Json From URL</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="info">Website Information from URL</string>
    <string name="wid">ID</string>
    <string name="name">Name</string>
    <string name="url">Website</string>

</resources>

Creating Activity:
Now to get JSON data from the URL we need to create a HttpClient and get the data from URL “http://demos.tricksofit.com/files/json.php”. If you have only JSON object you can use JSONObject json = new JSONObject(str);, If you have JSON Array then you can use JSONArray jArray = new JSONArray(str);. In MainActivity we will get the ID, Name and URL of the first object and displaying it on the layout.

MainActivity.java

package com.tricks.readjsonfromurl;

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectAll()
        .penaltyLog()
        .penaltyDialog()
        .build());

		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
        .penaltyLog()
        .build());

		TextView wid = (TextView) findViewById(R.id.wid);
		TextView name = (TextView) findViewById(R.id.name);
		TextView url = (TextView) findViewById(R.id.url);

		JSONObject json = null;
		String str = "";
		HttpResponse response;
        HttpClient myClient = new DefaultHttpClient();
        HttpPost myConnection = new HttpPost("http://demos.tricksofit.com/files/json.php");

        try {
        	response = myClient.execute(myConnection);
            str = EntityUtils.toString(response.getEntity(), "UTF-8");

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
        	JSONArray jArray = new JSONArray(str);
        	json = jArray.getJSONObject(0);

        	wid.setText(json.getString("id"));
        	name.setText(json.getString("name"));
        	url.setText(json.getString("url"));

        } catch ( JSONException e) {
        	e.printStackTrace();
        }

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

JSON Data :

[
    {
        "id": "01",
        "name": "Tricks Of IT",
        "url": "www.tricksofit.com"
    },
    {
        "id": "02",
        "name": "Demos Tricks Of IT",
        "url": "www.demos.tricksofit.com"
    }
]

DOWNLOAD CODE

Output:

Android JSON Parsing From URL
Android JSON Parsing From URL
  • Sanyog

    Thanks for the post. Nice tutorial.

  • Bush

    how to consume wcf service in android using JSON

  • vinay kumar

    how to display more than one value.

    • Hello Vinay,

      try to loop jsonArray and create a ArrayList and fill it in custom listView. Like

      ArrayList<HashMap<String, String>> arrList;
      for (int i = 0; i < jArray.length(); i++) {
      json = jArray.getJSONObject(i);
      HashMap<String, String> map1 = new HashMap<String, String>();
      map1.put("name", json.getString("name"));
      arrList.add(map1);
      }
      ListAdapter adapter = new SimpleAdapter( this, arrList, R.layout.list_item, new String[] { "name" },
      	                new int[] { R.id.name });
      listView.setAdapter(adapter);
      

      I will include it in next tutorial.

  • shayan

    hi,tanx for your nice tutorial.Iam new in android
    i do as u do in tutorial,just change the url with my localhost url,
    Its work with your url and not work with my localhost url,please help me

    • hi, if you are using emulator you should use the IP address 10.0.2.2 instead of localhost
      or
      if you are using other device then device should be in the same network with your system
      and you can use url with local lan IP address like 192.168.x.x.

      thanks

      • shayan

        tanx me a lote its work properly ,just this alert bother me
        “the app has violated its self-enforced strictmode policy”
        i must click ok 4-5 time then its work right

        • great!!

        • KrzychU

          I had the same problem, but I added other methods to ServiceMode:

          StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
          .detectDiskReads()
          .detectDiskWrites()
          .detectNetwork() // or .detectAll() for all detectable problems
          .penaltyLog()
          .build());
          StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
          .detectLeakedSqlLiteObjects()
          .penaltyLog()
          .penaltyDeath()
          .build());

          This resolve problem for me.

          • sanal

            thanks

        • Dean Go Goal

          StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
          .detectAll()
          .penaltyLog()
          .penaltyDialog()
          .build().LAX);

          StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
          .penaltyLog()
          .build().LAX);

      • Gabriel David Durruti Bautista

        Hi, great tutoria but I can’t use your code with another “URL.aspx” this “URL.aspx” does’nt have array “[]” just have 1 line its this: “{“success”:”f”, “message”:”try again”, “iduser”:”0″}” Can u help me?! please! Again Thanks

  • Amey Jahagirdar

    Hi, Thanks for nice tutorial, I am using other URL but getiing this exception
    type java.lang.String cannot be converted to JSONArray
    & on emulator it shows just wid, name & url

    URL is

    http://finance.google.com/finance/info?client=ig&q=NSE%3aRELIANCE

  • Hana

    Thank you for the useful tutorial!
    I have changed the url with my hosted url (angkotbdg.esy.es/rutetrayek_json2.php) and I’m sure its format is same as your URL example. I also changed the “getString” and didn’t have any error. But when I’m running it to my phone (I’m not using AVD), it doesn’t want to run (it said: has stopped). But it does when I’m using your URL (even though the data didn’t show up because I have changed the getString).

    Could you please tell me where I get wrong? Thank you.