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.

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:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/uid"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/uid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_alignParentTop="true"
        android:layout_marginTop="76dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/getdata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="23dp"
        android:text="Get Data" />

</RelativeLayout>

 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 JSONParser.java in the library folder.

JSONParser.java

package learn2crack.asynctask.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) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		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");
			}
			is.close();
			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 “http://api.learn2crack.com/android/json/”

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.

MainActivity.java

package learn2crack.asynctask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
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 = "http://10.0.2.2/JSON/";

	//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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Btngetdata = (Button)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {

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

			}
		});

    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
    	 private ProgressDialog pDialog;
    	@Override
        protected void onPreExecute() {
            super.onPreExecute();
             uid = (TextView)findViewById(R.id.uid);
			 name1 = (TextView)findViewById(R.id.name);
			 email1 = (TextView)findViewById(R.id.email);
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

    	}

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

    		// Getting JSON from URL
    		JSONObject json = jParser.getJSONFromUrl(url);
    		return json;
    	}
    	 @Override
         protected void onPostExecute(JSONObject json) {
    		 pDialog.dismiss();
    		 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
    				uid.setText(id);
    				name1.setText(name);
    				email1.setText(email);

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

    	 }
    }

}

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.

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
         />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="learn2crack.asynctask.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>
            <uses-permission android:name="android.permission.INTERNET" />

</manifest>

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.

asynctask with json

Screen when the App is Opened

Screen when the button is pressed

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
  • 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 “http://api.learn2crack.com/android/json/” 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” : {
    “text”:
    }
    }
    ]
    }
    ]
    }

    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

        PLEASE HELP ME

  • 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

          Thanks..

  • 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

    Hi

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

  • prachi

    hi

    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
    Thanks!

    • 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 MainActivity.java , 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(MainActivity.java:87)

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

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

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

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

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

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

    02-07 14:57:11.218: E/AndroidRuntime(25163): at android.app.ActivityThread.main(ActivityThread.java:5292)

    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(Method.java:515)

    02-07 14:57:11.218: E/AndroidRuntime(25163): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)

    02-07 14:57:11.218: E/AndroidRuntime(25163): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)

    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

    try{

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

    StringBuilder stringBuilder = new StringBuilder();

    String linea = null;

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

    stringBuilder.append(linea+”n”);

    }

    inputStream.close();

    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
    goswami.rahul0@gmail.com

  • How to get response after post?

  • adhy Ammase

    please….
    attach the file php

  • StarWardo

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

    “data”:{
    “id”:”g8nEDt”,
    “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(“http://bitcodetech.co/ws_ios_assignment/routes.php”);

    httpURLConnection = (HttpURLConnection) url.openConnection();

    httpURLConnection.connect();

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

    byte[] arr = new byte[1024];

    int count;

    StringBuilder stringBuilder = new StringBuilder();

    while ((count=(in.read(arr)))!=-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");

    stopsarray.add(name);

    }

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

    routesarray.add(routes1);

    }

    return routesarray;

    } catch (MalformedURLException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    } catch (JSONException e) {

    e.printStackTrace();

    }

    return null;

    }

    }

  • arnab

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