Android - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Android JSON Parser

Android JSON Parser

Android JavaScript Object Notation (JSON) parser is lightweight, structured, and easy to parse independent data exchange format that allows you to parse data present in the JSON format. It is the best alternative to XML when your app requires to exchange data with your server. Android provides four classes to manipulate JSON data: JSONArray, JSONObject, JSONStringer and JSONTokenizer. In this chapter, you will learn how to use Android JSON Parser to parse the JSON file and extract required information from it. JSON- Structure and Elements: AsyncTask is an abstract class which helps the Android applications to handle the Main UI thread. AsyncTask class allows you to perform long running operations(parsing) and shows the result on the UI thread without affecting the main thread. When an asynchronous task is executed from the UI main thread, it passes through four steps:
This method is invoked before doInBackground method is called on the UI thread. This method is normally used to setup the task like showing progress bar in the UI.
Code/process running for long time should be put in doInBackground method. When execute method is called in the UI main thread, this method is called with the parameters passed.
This method is invoked by calling publishProgress at anytime from doInBackground. This method can be used to display any form of progress in the user interface.
This method is invoked after doInBackground method completes processing. Outcome of the doInBackground is passed to this method.
Cancellation of an AsyncTask: The AsyncTask can be cancelled by invoking cancel(boolean) method. After invoking this method, onCancelled(Object) method is called instead of onPostExecute() after doInBackground() returns. Rules to be followed while implementing AsyncTask: 1. The AsyncTask class must be loaded on the UI thread. 2. The task instance must be created on the UI thread. 3. Method execute (Params…) must be invoked on the UI thread. 4. Should not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually. 5. The task can be executed only once (an exception will be thrown if a second execution is attempted.) The following example illustrates how to parse data using JSONParser and AsyncTask. First create employee.txt/employee.json in assets folder(if you are using static data)
{
"employee":[ {
"id":"1"
"name": "John B",
"email": "john@splessons.com",
"number": "2345678987"
} ,
{
"id":"2"
"name": "Amit",
"email": "amit@splessons.com",
"number": "2567678987"
} ]
} ;

Now Create MainActivity.java under src/<your packagename>/ MainActvity.java: [java] public class MainActivity extends Activity{ ArrayList nameL=new ArrayList(); ArrayList emailL=new ArrayList(); ArrayList numberL=new ArrayList(); ArrayList idL=new ArrayList(); Context context; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //hide action bar requestWindowFeature(Window.FEATURE_NO_TITLE); //set activity to external view setContentView(R.layout.activity_main); final Button access=(Button)findViewById(R.id.button1); final TextView text=(TextView)findViewById(R.id.textView1); context=this; //on click access access.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub final JSONParsing jp=new JSONParsing(context); jp.execute(); JSONParsing.h=new Handler() { public void handleMessage(android.os.Message msg) { JSONObject emp; try { System.out.println(jp.data); //create instance of JSONObject emp = (new JSONObject(jp.data)); //get JSONArray JSONArray jarray=emp.getJSONArray("employee"); for(int i=0;i<jarray.length();i++) { JSONObject jo=jarray.getJSONObject(i); String id=jo.getString("id"); String name=jo.getString("name"); String email=jo.getString("email"); String number=jo.getString("number"); nameL.add(name); emailL.add(email); numberL.add(number); idL.add(id); } //You can use listview to display data text.setText(idL.get(0)+"\n"+nameL.get(0)+"\n"+emailL.get(0)+"\n"+numberL.get(0)+"\n\n"+idL.get(1)+"\n"+nameL.get(1)+"\n"+emailL.get(1)+"\n"+numberL.get(1)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; } }); } } [/java] Create JSONParsing.java class JSONParsing.java: [java] public class JSONParsing extends AsyncTask{ //variable declaration ProgressDialog dialog; Context context; static Handler h; //ProgressDialog dialog; String data; //constructor JSONParsing(Context context) { this.context=context; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog=ProgressDialog.show(context, "Loading", "Please wait"); } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); dialog.dismiss(); } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub //create URL URL url; try { /*if you are accessing data from URL use this url = new URL("http://dev.splessons.com/simplexml.php?format=json"); //URL Encoding URI uri=new URI(url.getProtocol(),url.getUserInfo(),url.getHost(),url.getPort(),url.getPath(),url.getQuery(),url.getRef()); //convert URI to URL url=uri.toURL(); System.out.println(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream stream = conn.getInputStream();*/ InputStream stream = context.getAssets().open("employee.txt"); data = convertStreamToString(stream); h.sendEmptyMessage(123); } catch (Exception e) { e.printStackTrace(); h.sendEmptyMessage(1234); } return null; } static String convertStreamToString(java.io.InputStream is) { @SuppressWarnings("resource") java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } } [/java] Create activity_main.xml in res/layout folder activity_main.xml: [code lang="xml"]