In the previous tutorial we showed you how to parse JSON data from a URL and display it in a TextView. In this tutorial we are going to show you how to use AsyncTask with JSON Parsing. AsyncTask is used to perform background operations instead of performing in main thread and update the user interface.

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.asynctask”. 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. It also has a Button to display data in TextView when it is clicked.


<RelativeLayout xmlns:android=""
    tools:context=".MainActivity" >

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

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

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

        android:text="Get Data" />


 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.asynctask.library”. Create the in the library folder.

package learn2crack.asynctask.library;


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 using AsyncTask. When the button is pressed AsyncTask is performed. AsyncTask performs JSON parsing and the parsed JSON item is displayed in TextView. If you do not have a Local Server to test use can change the URL to “”

Usage of AsyncTask:

The AsyncTask in the MainActivity is defined by the statement “private class JSONParse extends AsyncTask<String, String, JSONObject>”.When AsyncTask is performed the process is separated into 4 steps. They are

1. onPreExecute()
2. doInBackground(Params…)
3. onProgressUpdate(Progress…)
4. onPostExecute(Result)

The first step onPreExecute() class is used to setup the task, for instance by showing a progress bar in the user interface. Here we are initializing progress bar and and defining TextView.

The second step doInBackground(Params…) class is used to perform background operations such as getting data from the server etc. Here we are getting JSON array from the URL.

Here we are not using the third step. The fourth step onPostExecute(Result) class is used to update the UI after completing the background process. Here we are displaying parsed JSON data in TextView after getting the data in step two.

package learn2crack.asynctask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import learn2crack.asynctask.library.JSONParser;

public class MainActivity extends Activity {
	TextView uid;
	TextView name1;
	TextView email1;
	Button Btngetdata;

	//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) {

        Btngetdata = (Button)findViewById(;
        Btngetdata.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
		         new JSONParse().execute();



    private class JSONParse extends AsyncTask<String, String, JSONObject> {
    	 private ProgressDialog pDialog;
        protected void onPreExecute() {
             uid = (TextView)findViewById(;
			 name1 = (TextView)findViewById(;
			 email1 = (TextView)findViewById(;
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");


        protected JSONObject doInBackground(String... args) {
    		JSONParser jParser = new JSONParser();

    		// Getting JSON from URL
    		JSONObject json = jParser.getJSONFromUrl(url);
    		return json;
         protected void onPostExecute(JSONObject json) {
    		 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);

    				//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=""
    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": ""

Finally run the project in the Emulator.

asynctask with json

Screen when the App is Opened

Screen when the button is pressed

Enjoy 🙂
Any questions comment here.

Raj Amal

Raj Amal

Developer at Learn2Crack
Raj Amal is a Co-founder of 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
  • Alex

    Thank you very much. You helped me allot.

    • Thank you, Keep visiting 🙂

  • ikki

    when you mean that we need a json folder in the root server, are you refering where is the android-sdks??? adb command?
    Thanks for your replay

    • Yes you need. Or change the URL to “” to test.

  • shouba

    What if my JSON Array does not have a name “user”, How to do that ?

    • Rename “user” to the name you used in your array.

  • Zahid
  • Khairul

    What if the content has more layers of array in it. How do i extract them out.

    “directions”: [
    “features”: [
    “attributes” : {

    Tried doing this way, but there’s no output in my textview.

    directions = json.getJSONArray(TAG_DIRECTIONS);
    JSONObject c = directions.getJSONObject(0);

    JSONObject features = c.getJSONObject(TAG_FEATURES);
    String attributes = features.getString(TAG_ATTRIBUTES);

  • Benny Margalit

    thanks a lot.
    in the example i can aslo define JSONParse as just return JSONObject and 2 other parameters can be made Void

  • Arijit Chakraborty

    Really helped me a lot man :-D…u rock m/

  • tj

    can you give some examples for http post,like login…can register the username and password..

  • Muhammad Umair

    Sir its giving me error tat string cannot be converted to JSONARRAY

    • Post your JSON format.

      • Sunil

        Raj Sir.. It is giving me error Null pointer exception. I have tried alot. Please tell me what to do ? Thanks in Advance.

        Code is same as u have given. Please help me.

        • daddeldu

          I’ve got the same error :/ any solution?

        • darr

          i get the same error!!!!

      • Aeronn Guillermo

        me too im having a hard time on that error please HELP me . thanks

      • Aeronn Guillermo


  • Allah

    Just a little mistake there

    sb.append(line + “n”);

    It should be a “n”

    • Ya. Fixed

      • David

        is still: sb.append(line + “n”)
        i have changed in: sb.append(line + “/n”)
        and works.
        thanks to both of you!

        • Amol


  • Gopala Palanee

    i want to pass those data to the JSONParser

    ArrayList nameValuePairs = new ArrayList();
    nameValuePairs.add(new BasicNameValuePair(“usernamejoiner”, username));
    nameValuePairs.add(new BasicNameValuePair(“departuretime”, departure_t));
    nameValuePairs.add(new BasicNameValuePair(“endtime”, end_t));
    nameValuePairs.add(new BasicNameValuePair(“departureaddress”, deparure_a));
    nameValuePairs.add(new BasicNameValuePair(“destinationaddress”, destination_a));
    nameValuePairs.add(new BasicNameValuePair(“date”, date_t));

    the data shall be obtain from sharedpreferences

    base on the data send the url , the php file will send a valid form of json data
    how to do that ? a little help please …

    • Add this to your JSON Parser and add parameter to the function.
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

  • Anas Sam

    I used your project and test it and i have an issue in :

    user = json.getJSONArray(TAG_USER);

    Can you help me with this?

    • What issue ?

      • shs

        my app crashed

        in the logcat this line has problem

        please help me

  • Is this possible to do it for a widget? so its can read data from a php file and shows them to a textview in widget? thanks

  • folo ouzouma

    Good morning can anybody please help to know how to store the json object recieve into an android sqlite database

  • Tolgay


    I want to ask a question about this.Can you send me an email ? My email is

  • prachi


    I want to know that I am using php api and want that same code use for post data on server and same code use for get data from server is this possible

    • Rose Caz

      me too !!

  • Archana Sarang

    Thank you Raj Sir, Now I can understand JSON Parsing in android….

  • gonza28

    I do not want listview. May want TextView

  • f5

    this error when I click GetData

  • Dar

    Hello I tried the same code and I get a fatal run time exception .”NetworkOnMainThreadException”. How can I fix this?

    • Arno Turelinckx

      Make sure you dont forget to add this line to your manifest file.

  • bilal

    i am using the same code but i need to get data from database after certain time say after every 5 mins and reload list view

  • Batal Sunat

    Hello, I am trying to change the coding , but I found the error when the application is run.

    The following error appears

    Error Parsing data org.json.JSONExcpection: Unterminated array at character 14 of {n”radio”:[n{n”server”:”ssjsjsjsj”,n”rj”:jhon”,n”pesan”:”message”n}n]n}n

    My json file

    “radio”: [
    “server”: “ssjsjsjsj”,
    “rj”: “jhon”,
    “pesan”: “message”

  • Rose Caz

    Hello sir , there is a plenty of contacts and i want to show only one, meaning i will show contacts by ID on textview???

  • Evan Dix

    Why do i keep getting a null pointer exception????

  • Rakesh Kumar

    Please help me ………………………. nullPointerException occur……………..

    02-07 14:57:11.218: E/AndroidRuntime(25163): FATAL EXCEPTION: main

    02-07 14:57:11.218: E/AndroidRuntime(25163): Process: learn2crack.asynctask, PID: 25163

    02-07 14:57:11.218: E/AndroidRuntime(25163): java.lang.NullPointerException

    02-07 14:57:11.218: E/AndroidRuntime(25163): at learn2crack.asynctask.MainActivity$JSONParse.onPostExecute(

    02-07 14:57:11.218: E/AndroidRuntime(25163): at learn2crack.asynctask.MainActivity$JSONParse.onPostExecute(

    02-07 14:57:11.218: E/AndroidRuntime(25163): at android.os.AsyncTask.finish(

    02-07 14:57:11.218: E/AndroidRuntime(25163): at android.os.AsyncTask.access$600(

    02-07 14:57:11.218: E/AndroidRuntime(25163): at android.os.AsyncTask$InternalHandler.handleMessage(

    02-07 14:57:11.218: E/AndroidRuntime(25163): at android.os.Handler.dispatchMessage(

    02-07 14:57:11.218: E/AndroidRuntime(25163): at android.os.Looper.loop(

    02-07 14:57:11.218: E/AndroidRuntime(25163): at

    02-07 14:57:11.218: E/AndroidRuntime(25163): at java.lang.reflect.Method.invokeNative(Native Method)

    02-07 14:57:11.218: E/AndroidRuntime(25163): at java.lang.reflect.Method.invoke(

    02-07 14:57:11.218: E/AndroidRuntime(25163): at$

    02-07 14:57:11.218: E/AndroidRuntime(25163): at

    02-07 14:57:11.218: E/AndroidRuntime(25163): at dalvik.system.NativeStart.main(Native Method)

    • Aaro

      same error.. please help

  • Rakesh Kumar

    nullPointerException!!!! how to solve?

  • Maha lakshmi

    How to add another data into that php file at runtime?

  • Isai


    BufferedReader lector = new BufferedReader(new InputStreamReader(inputStream,”iso-8859″),8);

    StringBuilder stringBuilder = new StringBuilder();

    String linea = null;

    while((linea = lector.readLine())!= null){




    json = stringBuilder.toString();

    }catch(IOException e){

    Log.e(“Erro de lectura(Buffer)”,”Error al convertir el resultado: “+e.getMessage());


    Buffer Error:﹕ Error al convertir el resultado: iso-8859

  • Rahul Goswami

    this website is really helpful. thanks for this example raj kamal
    can u please send me php code of this example my mail id is

  • How to get response after post?

  • adhy Ammase

    attach the file php

  • StarWardo

    Hello, I want to load a single JSON object not inside an array. Something like this”:

    “name”:”Twins Bazil Twins”,


    So no branckets used.
    How can I do this?

  • Gordo

    Any recommendation for how best to deal with the deprecated org.apache library support? I’d like to use your above example for learning, but I’m unable to find a compile dependency that resolves all the import errors.

  • Atif Patel

    What if i Have more data in JSON array…?
    This is for only one ID…
    i wanna Implement Infinite IDs

  • M.Anees ur rehman

    how get all coordinates from server and show all projects location in google map..

  • Damark

    Hello. How can I solve? Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

  • Damark

    Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

  • WaWaToR

    Hi, Thanks for your code.
    I am trying to modify it : I want to get the app to show a random string from json.
    Please help I have changed the index.php but I need help with the android code.
    Thank you please Help

  • Yog

    public class WebUtil {

    public static ArrayList getRouteDetails(){

    URL url;

    HttpURLConnection httpURLConnection;

    try {

    url = new URL(“”);

    httpURLConnection = (HttpURLConnection) url.openConnection();


    InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());

    byte[] arr = new byte[1024];

    int count;

    StringBuilder stringBuilder = new StringBuilder();

    while ((count=(!=-1){

    stringBuilder.append(new String(arr,0,count));


    JSONObject jsonObject = new JSONObject(stringBuilder.toString());

    JSONArray routes = jsonObject.getJSONArray(“routes”);

    ArrayList routesarray = new ArrayList();

    for(int i=0;i<routes.length();i++){

    JSONObject obj = routes.getJSONObject(i);

    String from = obj.getString("from");

    String to = obj.getString("to");

    String duration = obj.getString("duration");

    String time = obj.getString("time");

    String fair = obj.getString("fair");

    ArrayList stopsarray = new ArrayList();

    JSONArray stops = obj.getJSONArray(“stops”);

    for(int j=0;j<stops.length();j++){

    JSONObject stopobj = stops.getJSONObject(j);

    String name = stopobj.getString("name");



    Routes routes1 = new Routes(from,to,duration,time,fair,stopsarray);



    return routesarray;

    } catch (MalformedURLException e) {


    } catch (IOException e) {


    } catch (JSONException e) {



    return null;



  • arnab

    can i have a help on “update coordinates and sending data to mysql server in android”

  • parwi

    no error but progress bar keep on moving for long time