Wednesday, November 27, 2013

Android Asynctask with JSON Parsing Example

33 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>


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



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 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.


     


33 comments :


  1. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.android development course fees in chennai | android app development training in chennai

    ReplyDelete
  2. I really like your blog. You make it interesting to read and entertaining at the same time. I cant wait to read more from you.
    Click here:
    angularjs training in chennai
    Click here:
    angularjs2 training in chennai

    ReplyDelete
  3. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.
    Click here:
    Microsoft azure training in chennai
    Click here:
    Microsoft azure training in online

    ReplyDelete
  4. That was a great message in my carrier, and It's wonderful commands like mind relaxes with understand words of knowledge by information's.
    Blueprism training in Chennai

    Blueprism training in Bangalore

    Blueprism training in Pune

    Blueprism online training

    Blueprism training in tambaram

    ReplyDelete
  5. You blog post is just completely quality and informative. Many new facts and information which I have not heard about before. Keep sharing more blog posts.
    python training in chennai
    python training in Bangalore

    ReplyDelete
  6. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post I would like to read this
    python training in pune
    python online training
    python training in OMR

    ReplyDelete
  7. I am a regular reader of your blog and being students it is great to read that your responsibilities have not prevented you from continuing your study and other activities. Love

    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    ReplyDelete
  8. UiPath Training in Bangalore by myTectra is one the best UiPath Training. myTectra is the market leader in providing Robotic Process Automation on UiPath
    ui path training in bangalore

    ReplyDelete
  9. I am a regular reader of your blog and being students it is great to read that your responsibilities have not prevented you from continuing your study and other activities. Love
    Aws Training From India

    My Sql Dba Training From India

    ReplyDelete
  10. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    angularjs-Training in pune

    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    ReplyDelete
  11. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  12. This is a good post. This post give truly quality information. I’m definitely going to look into it. Really very useful tips are provided here. thank you so much. Keep up the good works.

    java training in chennai | java training in bangalore

    java interview questions and answers | core java interview questions and answers

    ReplyDelete

  13. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    Selenium Interview Questions and Answers

    Best Selenium Training in Chennai | Selenium Training Institute in Chennai | Besant Technologies

    Selenium Training in Bangalore | Best Selenium Training in Bangalore

    Free Selenium Tutorial |Selenium Webdriver Tutorial |For Beginners

    ReplyDelete
  14. Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    angularjs online training

    apache spark online training

    informatica mdm online training

    devops online training

    aws online training

    ReplyDelete
  15. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.is article.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete
  16. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.Automation Anywhere Training in Bangalore

    ReplyDelete
  17. Thank you for posting informative insights, I think we have got some more information to share with! Do check out
    oracle training in chennai and let us know your thoughts. Let’s have great learning!

    ReplyDelete
  18. Right on target with this review, I really accept that this astonishing site needs substantially more consideration. I'll presumably be getting back to peruse more, a debt of gratitude is in order for the data!
    live

    ReplyDelete
  19. Your site is very good .Here , I have read all the important topics. Do You Know about the Turkey visa application form ? ya I have a good experience about it. A new system is developed and it is very effective.And You can also read all about the new online e visa system process. just only on 1 click

    ReplyDelete
  20. Card be government involve. Media because industry represent.trending-updates

    ReplyDelete