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(Stringurl) { // 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.

Enjoy 🙂

Any questions comment here.