JSON is one of the best method for storing data. In this tutorial we are going to show you how to parse a JSON response from a URL and display it in a TextView and it is provided with a example. JSON data has both square brackets and curly brackets. The square brackets denote JSON Array and curly bracket denotes JSON Object.

Creating Project:

Make sure you have properly setup the Android SDK, AVD for Testing the Application and a Local Webserver configured to get the JSON response.
Create a New project in Eclipse IDE with the package as “learn2crack.jsonparsing“. Create the Main Activity as “MainActivity” and the main Layout as “activity_main”.

Download Complete Project:

Creating Layout:

The Main layout for our project is “activity_main” which has three TextView to display the ID, Name and Email of the JSON Array from the URL.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    tools:context=".MainActivity" >

        android:textAppearance="?android:attr/textAppearanceLarge" />

        android:textAppearance="?android:attr/textAppearanceLarge" />

        android:textAppearance="?android:attr/textAppearanceLarge" />


Creating Activity:

Before creating the MainActivity we need to create a JSON Parser class which gets the JSON data from the URL and returns JSON Object.
In your Project create a new folder library in the src folder such that the package is “learn2crack.jsonparsing.library”. Create the JSONParser.java in the library folder.


package learn2crack.jsonparsing.library;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

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();
		} 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;


Next step is to create the MainActivity. In the MainActivity we are storing the JSON Nodes such as ID,Name,Email in the static variables.
Then we are using JSONParser to get the JSONArray from the URL. The parsed JSON item is the stored in the string. Finally the Stored JSON String is displayed in TextView. If you do not have a Local Server to test use can change the URL to “http://api.learn2crack.com/android/json/”


package learn2crack.jsonparsing;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import learn2crack.jsonparsing.library.JSONParser;

public class MainActivity extends Activity {

	//URL to get JSON Array
	private static String url = "";

	//JSON Node Names
	private static final String TAG_USER = "user";
	private static final String TAG_ID = "id";
	private static final String TAG_NAME = "name";
	private static final String TAG_EMAIL = "email";

	JSONArray user = null;

    protected void onCreate(Bundle savedInstanceState) {


		// Creating new JSON Parser
		JSONParser jParser = new JSONParser();

		// Getting JSON from URL
		JSONObject json = jParser.getJSONFromUrl(url);

		try {
			// Getting JSON Array
			user = json.getJSONArray(TAG_USER);
			JSONObject c = user.getJSONObject(0);

			// Storing  JSON item in a Variable
			String id = c.getString(TAG_ID);
			String name = c.getString(TAG_NAME);
			String email = c.getString(TAG_EMAIL);

			//Importing TextView
			final TextView uid = (TextView)findViewById(R.id.uid);
			final TextView name1 = (TextView)findViewById(R.id.name);
			final TextView email1 = (TextView)findViewById(R.id.email);

			//Set JSON Data in TextView

	} catch (JSONException e) {



Creating Manifest:

Add the permision “android.permission.INTERNET” to the Manifest file as we need to access external Address. No other special Permissions are required.


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


        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

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


Creating JSON Response:

Create a Folder named JSON in the root of your Server and create a “index.php” file with the following contents.

"user": [
"id": "001",
"name": "Raj Amal",
"email": "raj.amalw@gmail.com"

Finally run the project in the Emulator. Here is a Screenshot.

android json parsing from url

Project Running in Emulator

Enjoy 🙂
Any questions comment here.

Raj Amal W
Raj Amal is a Co-founder of Learn2Crack.com and a Android Developer. He Loves to work with Computers, Smartphones and Digital Gadgets. He also authored a book Learning Android Google Maps
Raj Amal W
  • Thanks

    Can it get more than one user ? If so how can I add another user in index.php ?

  • Zahid

    Once I get the data from the JSON file from the web. I would like to put it into an ARRAY based on “TYPE”. Any idea how do I go on about doing it?

    Here’s my question: http://stackoverflow.com/questions/19868439/how-to-put-json-information-in-an-array-to-use-it-for-displaying-in-listview

    • Here it is Follow this tutorial.

  • Muhammadibn

    Hi, Nice tutorial, I wanted to know if its possible to pull a date which is in json format and display it as a widget on the homepage?

  • Wasim Memon

    hi really nice tutorial
    but you know how i get all links from my website in json format.
    i want to create app for my site in android so i want it.

    • Use plugins to get JSON feed instead of XML feed. So you can parse it in your app.

  • haji

    Hi! i am new in android, i follow all the steps but every time when i run the emulator i got error message “Unfortunately, JSONParsing has stopped” i am sure i did the all steps correctly.. please help

    • Srini Vasan

      Logcat report ?

      • haji

        Yes! When i run emulator

  • haji

    hi Srini and all this is error message!

    • Open DDMS in eclipse and copy the Logcat and paste here.

      • Adam Alkouri

        11-27 22:55:35.485: E/AndroidRuntime(3185): FATAL EXCEPTION: main

        11-27 22:55:35.485: E/AndroidRuntime(3185): Process: com.example.testphpjson, PID: 3185

        11-27 22:55:35.485: E/AndroidRuntime(3185): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testphpjson/com.example.testphpjson.MainActivity}: android.os.NetworkOnMainThreadException

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.app.ActivityThread.access$700(ActivityThread.java:135)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.os.Handler.dispatchMessage(Handler.java:102)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.os.Looper.loop(Looper.java:137)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.app.ActivityThread.main(ActivityThread.java:4998)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at java.lang.reflect.Method.invokeNative(Native Method)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at java.lang.reflect.Method.invoke(Method.java:515)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at dalvik.system.NativeStart.main(Native Method)

        11-27 22:55:35.485: E/AndroidRuntime(3185): Caused by: android.os.NetworkOnMainThreadException

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at libcore.io.IoBridge.connect(IoBridge.java:112)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at java.net.Socket.connect(Socket.java:843)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at learn2crack.jsonparsing.library.JSONParser.getJSONFromUrl(JSONParser.java:38)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at com.example.testphpjson.MainActivity.onCreate(MainActivity.java:35)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.app.Activity.performCreate(Activity.java:5243)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

        11-27 22:55:35.485: E/AndroidRuntime(3185): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)

        11-27 22:55:35.485: E/AndroidRuntime(3185): … 11 more

        11-27 22:55:37.825: I/Process(3185): Sending signal. PID: 3185 SIG: 9

        • Just Use android:minSdkVersion=”8″
          in your Manifest. Remove Target SDK from the Manifest. It will fix the error.

          • Adam Alkouri

            Thank you for the response, I got it working. Here is my question. I have a different PHP file that I am working with that also uses your JSON encode script. The problem is, the output is different.

            Here is my PHP script:

            $con=mysql_connect(“$host”, “$username”, “$password”)or die(“cannot connect”);

            mysql_select_db(“$db_name”)or die(“cannot select DB”);

            $sql = “select * from users”;
            $result = mysql_query($sql);
            $json = array();

            echo json_encode($json);

            The output I get for this php file for only 1 row in my SQL database is:


            How can I tweak this so it can be displayed in Android?

            This is what the output looks with your PHP file, its similar so I know I can get this to work, but I cant figure it out:

            { “user”: [ { “id”: “001”, “name”: “Raj Amal”, “email”: “raj.amalw@gmail.com” } ] }

          • Vidit Soni

            i removed target but still error are there

        • ilham

          hai raj i’m download your project and check out the android:minSdkVersion is already “8” but i still have error like that

  • eron

    “user”: [
    “id”: “001”,
    “name”: “Raj Amal”,
    “email”: “raj.amalw@gmail.com”

    how can u generate your php code to generate that kind of json?
    i have problem in my php…
    because my php code is incomplete because it has no “user”..

    • kushagra





      while ($row = $stmt->fetch( PDO::FETCH_ASSOC )) {


      $row_array[‘name’]= $row[‘name’];

      $row_array[’email’]= $row[’email’];



      echo json_encode($code);


  • 0fffspring

    I have “android.os.NetworkOnMainThreadException”
    Do not understand why you don’t have it

    • Just Use android:minSdkVersion=”8″
      in your Manifest. Remove Target SDK from the Manifest. It will fix the error.

      • DocRockulus

        It IS bad practice to do any potentially long running processes on the main thread. Rather than simply hiding the issue, you should run the JSONParser in an async task or in it’s own thread.

        • I have already written a article to use Async Task with JSON parsing.

  • Ravindra

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

    • Ravindra

      Put above code in your code this work for me

      • Bishal

        we can use thread too

  • droidcoder

    12-03 18:15:08.408: E/Trace(18869): error opening trace file: No such file or directory (2)

    • Post the complete logcat report

  • tommy

    Hi Raj Amal,

    I have a little problem. When i run it, it give me some errors. Please help. I modified some code. When the button click, it take the url from the editText. and then …

    03-19 01:56:40.127: E/JSON Parser(1259): Error parsing data org.json.JSONException: End of input at character 0 of

    03-19 01:56:40.127: D/AndroidRuntime(1259): Shutting down VM

    03-19 01:56:40.137: W/dalvikvm(1259): threadid=1: thread exiting with uncaught exception (group=0x41465700)

    03-19 01:56:40.157: E/AndroidRuntime(1259): FATAL EXCEPTION: main

    03-19 01:56:40.157: E/AndroidRuntime(1259): java.lang.NullPointerException

    03-19 01:56:40.157: E/AndroidRuntime(1259): at com.frankie.arduinodetector.MainActivity.setData(MainActivity.java:106)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at com.frankie.arduinodetector.MainActivity$1.onClick(MainActivity.java:47)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at android.view.View.performClick(View.java:4240)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at android.view.View$PerformClick.run(View.java:17721)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at android.os.Handler.handleCallback(Handler.java:730)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at android.os.Handler.dispatchMessage(Handler.java:92)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at android.os.Looper.loop(Looper.java:137)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at android.app.ActivityThread.main(ActivityThread.java:5103)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at java.lang.reflect.Method.invokeNative(Native Method)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at java.lang.reflect.Method.invoke(Method.java:525)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

    03-19 01:56:40.157: E/AndroidRuntime(1259): at dalvik.system.NativeStart.main(Native Method)

    • camsson

      In the code recipe:
      while ((line = reader.readLine()) != null) {
      sb.append(line + “n”);
      try to delect:+ “n” may resolve your problem.

  • Julian K

    This is working without AsyncTaskt ?

  • Nauna IMY

    how to make json webservices in asp.net and bind it with android listview

  • ahmad

    when im trying to run the application, Im getting a black screen with nothing happening..

    • ahmad

      and after 2 minutes it says “the application has stopped unexpectedly. please try again.” :/

  • Ayu Kusumaningtyas

    Hi, Raj..
    Is it possible to make multiple jsonparser in 1 android project?

  • Giovanni Ciavarelli

    Hello! I am a NewBie in Java and programming …. Sorry. I am using “Android Studio” and I can’t understand how to: …

    “In your Project create a new folder library in the src folder such that the package is “learn2crack.jsonparsing.library”. Create the JSONParser.java in the library folder.”

    When I do NEW->FOLDER I can’t see “Folder Library” … what I should do? Thanks!

    • Android Studio Newbie

      For anyone interested, In Android Studio, in the project browser, in the “java” folder, right click on your project’s package (“learn2crack.jsonparsing” if you followed the example), select “New”/”Package”, name the package “library”, then right click on the newly created library, “New” / “Java Class”, and name it “JSONParser”. Voilà.

  • Rony

    Can i use asynctask in this program?i mean without pressing any button ?


    In this link you used a “Get Data” Button…but i want asynctask without pressing a button?

    Thank you.

  • carlos

    my app stop working, i already changed the target SDK and the minSdkVersion is 8, th logcat is:
    09-16 11:33:14.000: E/WifiHW(1508): wifi_connect_to_supplicant: ctrl_conn(0x4a6d78)
    09-16 11:33:14.156: E/libnetutils(1508): dhcp start cmd interface : [dhcpcd:-ABK eth0]
    09-16 11:33:14.515: E/ClockWidget(12484): clock_bg portrait
    09-16 11:33:14.515: E/ClockWidget(12484): drawDayText
    09-16 11:33:14.515: E/ClockWidget(12484): width= 50
    09-16 11:33:14.515: E/ClockWidget(12484): widthText= 52.0
    09-16 11:33:14.515: E/ClockWidget(12484): RIGHT
    09-16 11:33:14.546: E/StatusBarPolicy(1561): ecio: 33
    09-16 11:33:14.546: E/StatusBarPolicy(1561): iconLevel: 4
    09-16 11:33:20.742: E/StatusBarPolicy(1561): ecio: 34
    09-16 11:33:20.742: E/StatusBarPolicy(1561): iconLevel: 4
    09-16 11:33:46.265: E/Buffer Error(12657): Error converting result java.lang.NullPointerException
    09-16 11:33:46.265: E/JSON Parser(12657): Error parsing data org.json.JSONException: End of input at character 0 of
    09-16 11:33:46.273: E/liblog(1508): failed to call dumpstate
    09-16 11:33:46.273: E/AndroidRuntime(12657): FATAL EXCEPTION: main
    09-16 11:33:46.273: E/AndroidRuntime(12657): java.lang.RuntimeException: Unable to start activity ComponentInfo{learn2crack.jsonparsing/learn2crack.jsonparsing.MainActivity}: java.lang.NullPointerException
    09-16 11:33:46.273: E/AndroidRuntime(12657): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at android.os.Handler.dispatchMessage(Handler.java:99)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at android.os.Looper.loop(Looper.java:130)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at android.app.ActivityThread.main(ActivityThread.java:3687)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at java.lang.reflect.Method.invokeNative(Native Method)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at java.lang.reflect.Method.invoke(Method.java:507)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    09-16 11:33:46.273: E/AndroidRuntime(12657): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)

  • cypo

    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);

    It should be: line + “n”

  • mahendra

    above code is throwing exception as null and application stopped

  • Boon Chew

    Hi, Raj Amal.
    I want to fetch data from localhost to my android app.
    I had follow your code. However, i won’t be able to run my application.
    Is’t my run configuration got problem ?

  • Guest

    Here are the error. I m new in android. Thank !

  • aswin

    hi…… i downloaded your code n run it ……but it is not running.. it is showing unfortunately,app has stopped…. i need correct solution for this error…

  • aswin

    when i try your code it is shown this error … can u tell me what is the problem is ???

  • Kirill Varivoda

    Hi, is there is a way to post comments (or even posts) in WordPress blog using Json, for exmaple?
    It would be great!

  • _javatar

    hi, i want to add json example like this example but i got “vm exiting with result code 0 cleanup skipped” and app closes.
    any solution?

  • ams

    keeping the Folder named JSON in the root of your Server means where exactly i have to create the folder ?

  • Reign

    Remove the + “n” on – sb.append(line + “n”);

    Becomes – sb.append(line );

    That will fix the error.

  • Maha lakshmi

    How to insert an item in Json URL?

  • Sharath kumar

    How to parse a json if it does not have a array name?

    • Riad anik

      do you find your answer?i am facing the same problem….:/

    • Krishna Ch

      did you find the solutions for this?

  • Gilang Surahman

    how to parsing json like this?


    “id”: “001”,
    “name”: “Raj Amal”,
    “email”: “raj.amalw@gmail.com”

  • Dhanukonda Murali

    Hi sir this is murali i know about getting data from given url.can you explain me about json Update,Delete,Insert

  • Divya Venkataramani

    how to display one record for 10 seconds and then refresh the screen with the next record?

  • Parminder singh

    HI, I have a blog, and i want that my android app should be same as my blog, is this code good for me?, please send me any video link so that i can follow. thank you

  • MC Mad Moefat

    Any updated version of this tutorial as HTTP methods has been deprecated. Thanks in advance, great tutorial.

  • Ghani Khan

    now i want to do add a button and if i click on that button it gets me the next record how can i do that ??

  • Aravindha Bollineni

    Hi i tried using json api on my wordpress website and it’s working fine for user registration, login and retrieving recent posts, but what i want to do is adding content which will be visible depending upon user role, lets say subscriber, subscriber 2 are two users, i can do this in wordpress just adding some plugins but if do that either both users are unable to see in app or the opp, so what can i do now?

  • Fahad Shah

    I have links in json file so how can I set to open link on click in android app.