Showing posts with label android json parsing. Show all posts
Wednesday, November 27, 2013
Android Asynctask with JSON Parsing Example
Manchu Bhargavi
10:15 PM
android
,
android json parsing
,
android parsing in android
,
asynctask json in android
,
json
,
json parsing
,
parsing with asynctask in json
35 comments
:
Hi,
This is an Example 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.
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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="114dp"
android:text="Registration Form" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="23dp"
android:layout_marginTop="39dp"
android:text="USERNAME" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="29dp"
android:text="PASSWORD" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView3"
android:layout_below="@+id/textView3"
android:layout_marginTop="36dp"
android:text="CONFIRM PASSWORD" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_centerVertical="true"
android:text="EMAIL ID" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView5"
android:layout_below="@+id/textView5"
android:layout_marginTop="40dp"
android:text="PHONE NO" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignTop="@+id/textView3"
android:ems="10"
android:password="true"/>
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_alignTop="@+id/textView4"
android:ems="10"
android:password="true"/>
<EditText
android:id="@+id/editText4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_alignTop="@+id/textView5"
android:ems="10" />
<EditText
android:id="@+id/editText5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView6"
android:layout_alignBottom="@+id/textView6"
android:layout_alignLeft="@+id/editText4"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText5"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:text="REGISTER"
android:onClick="register"/>
</RelativeLayout>
This is an Example 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.
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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="114dp"
android:text="Registration Form" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="23dp"
android:layout_marginTop="39dp"
android:text="USERNAME" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="29dp"
android:text="PASSWORD" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView3"
android:layout_below="@+id/textView3"
android:layout_marginTop="36dp"
android:text="CONFIRM PASSWORD" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_centerVertical="true"
android:text="EMAIL ID" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView5"
android:layout_below="@+id/textView5"
android:layout_marginTop="40dp"
android:text="PHONE NO" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignTop="@+id/textView3"
android:ems="10"
android:password="true"/>
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_alignTop="@+id/textView4"
android:ems="10"
android:password="true"/>
<EditText
android:id="@+id/editText4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_alignTop="@+id/textView5"
android:ems="10" />
<EditText
android:id="@+id/editText5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView6"
android:layout_alignBottom="@+id/textView6"
android:layout_alignLeft="@+id/editText4"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText5"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:text="REGISTER"
android:onClick="register"/>
</RelativeLayout>
1. Creating a java class called JSON Parser.java
2. Before creating the MainActivity we need to create a JSON Parser class which gets the JSON data from the URL and returns JSON Object.
JSONParser.java:
package com.example.service;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeoutException;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
JSONObject JSONresponseText, result;
int timeout1 = 1000*2;
int timeout2 = 1000*2;
// constructor
Context context;
public JSONParser() {
}
public JSONObject getJSONFromUrl(JSONObject data, String requesturl,
String pOST_METHOD) {
// Making HTTP request
String result = "";
Log.d("requesturl = ", requesturl);
Log.d("pOST_METHOD = ", pOST_METHOD);
try {
// defaultHttpClient
URL url = new URL(requesturl);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout1);
HttpConnectionParams.setSoTimeout(httpParameters, timeout2);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(20000);
connection.setRequestMethod(pOST_METHOD);
connection.setRequestProperty("content-Type", "application/json");
connection.setRequestProperty("content-Language", "en-US");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream dom = new DataOutputStream(
connection.getOutputStream());
dom.writeBytes(data.toString());
dom.flush();
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
dom.close();
reader.close();
Log.d("SERVICE RESPONSE: ", answer.toString());
result = answer.toString();
try {
JSONresponseText = new JSONObject(result);
Log.i("JSONresponseText", JSONresponseText.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
Log.d("JSON RESPONSE = ", JSONresponseText.toString());
return JSONresponseText;
}
}
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText ed1,ed2,ed3,ed4,ed5;
Button b1;
public static ConnectionDetector cd;
static Boolean isInternetPresent = false;
Context context;
public static String URL="http://10.0.2.2/web/ws_API/registration.php";
public static String POST_METHOD = "POST";
public static String TAG_HEAD = "data";
private static final String TAG_MESSAGE = "message";
JSONParser jParser = new JSONParser();
JSONObject json;
JSONArray data = null;
String username,pwd,confirm_pwd,emailid,phoneno,content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText1);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
ed4=(EditText)findViewById(R.id.editText4);
ed5=(EditText)findViewById(R.id.editText5);
}
public void register(View v)
{
username=ed1.getText().toString();
pwd=ed2.getText().toString();
confirm_pwd=ed3.getText().toString();
emailid=ed4.getText().toString();
phoneno=ed5.getText().toString();
if((username.length()>0)&&(pwd.length()>0)&&(confirm_pwd.length()>0)&&(emailid.length()>0)&&(phoneno.length()>0))
{
content = "{\"username\":\"" +username
+ "\",\"password\":\"" +pwd
+ "\",\"confirmpassword\":\"" +confirm_pwd
+ "\", \"emailid\":\"" +emailid
+"\",\"phoneno\":\""+phoneno
+ "\"}";
new ShowDialogAsyncTask().execute();
Intent intent=new Intent(MainActivity.this,second.class);
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(), "please enter all details", 4).show();
}
}
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
json = jParser.getJSONFromUrl(new JSONObject(content),URL ,POST_METHOD);
Log.d("JSON data",json.getString("message"));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("Content", content);
Toast.makeText(getApplicationContext(),json.toString(), 4).show();
// Toast.makeText(getApplicationContext(), "Register successful", 4)
//.show();
}
}
}
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)
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 com.example.service;
import org.json.JSONArray;import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText ed1,ed2,ed3,ed4,ed5;
Button b1;
public static ConnectionDetector cd;
static Boolean isInternetPresent = false;
Context context;
public static String URL="http://10.0.2.2/web/ws_API/registration.php";
public static String POST_METHOD = "POST";
public static String TAG_HEAD = "data";
private static final String TAG_MESSAGE = "message";
JSONParser jParser = new JSONParser();
JSONObject json;
JSONArray data = null;
String username,pwd,confirm_pwd,emailid,phoneno,content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText1);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
ed4=(EditText)findViewById(R.id.editText4);
ed5=(EditText)findViewById(R.id.editText5);
}
public void register(View v)
{
username=ed1.getText().toString();
pwd=ed2.getText().toString();
confirm_pwd=ed3.getText().toString();
emailid=ed4.getText().toString();
phoneno=ed5.getText().toString();
if((username.length()>0)&&(pwd.length()>0)&&(confirm_pwd.length()>0)&&(emailid.length()>0)&&(phoneno.length()>0))
{
content = "{\"username\":\"" +username
+ "\",\"password\":\"" +pwd
+ "\",\"confirmpassword\":\"" +confirm_pwd
+ "\", \"emailid\":\"" +emailid
+"\",\"phoneno\":\""+phoneno
+ "\"}";
new ShowDialogAsyncTask().execute();
Intent intent=new Intent(MainActivity.this,second.class);
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(), "please enter all details", 4).show();
}
}
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
json = jParser.getJSONFromUrl(new JSONObject(content),URL ,POST_METHOD);
Log.d("JSON data",json.getString("message"));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("Content", content);
Toast.makeText(getApplicationContext(),json.toString(), 4).show();
// Toast.makeText(getApplicationContext(), "Register successful", 4)
//.show();
}
}
}
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="com.example.service"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.service.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>
<activity android:name="com.example.service.second"></activity>
</application>
</manifest>
Here output is shown below here.
Subscribe to:
Posts
(
Atom
)

