Monday, 31 August 2015

Android Json Parsing

Hello Guys,

Today I explain about Json Parsing in Android. Before i start about json parsing all of you need to know about Json.

I mean to say What is Json and Why we use Json in Android?

Let's start with

Question: What Is Json?

Answer: JSON is nothing but Java Script Object Notation. Its a light weight method for data interchange.

JSON is a very easy form for read and write data.

Question: Why we use JSON?

Answer: As i said in first question's answer, JSON is mainly used for data interchanging. We can simply said that its used in Android for get the required data from server and sometime save the data into server.

So if you want to communicate with another database like MySQL and so on from your android application then JSON is an easy method to use for it.

Let's start its parsing.

For Json Parsing you must need Internet Permission.

Then after you need to connect your application to server for data communication using AsyncTask.

Here I display its sample code.

Sample Code:

File: activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/bg">

    <TextView
        android:id="@+id/text_pickup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pickup Point:"
        android:layout_marginTop="20dp"
        android:paddingLeft="15dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:textColor="#FFBF00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edit_pickup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="3dp"
        android:background="@drawable/box"
        android:paddingLeft="6dp">

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/text_dropoff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dropoff Point:"
        android:layout_marginTop="10dp"
        android:paddingLeft="15dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:textColor="#FFBF00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edit_dropoff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="3dp"
        android:background="@drawable/box"
        android:paddingLeft="6dp"/>
    
    <TextView
        android:id="@+id/text_dist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Total Distance:"
        android:layout_marginTop="10dp"
        android:paddingLeft="15dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:textColor="#FFBF00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edit_dist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="3dp"
        android:focusable="false"
        android:background="@drawable/box"
        android:paddingLeft="6dp"/>
    
    <TextView
        android:id="@+id/text_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Total Time:"
        android:layout_marginTop="10dp"
        android:paddingLeft="15dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:textColor="#FFBF00"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edit_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="3dp"
        android:focusable="false"
        android:background="@drawable/box"
        android:paddingLeft="6dp"/>

    <Button
        android:id="@+id/btn_click"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="Click Me...!"
        android:layout_gravity="center"
        android:layout_marginTop="40dp"
        android:typeface="serif"
        android:textStyle="bold"
        android:background="#FFBF00"/>
    
</LinearLayout>

File: MainActivity.java

package com.sneha.jsonparsingapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity
{
EditText et_pickup, et_dropoff, et_distance, et_time;

Button b_click;

ProgressDialog progDialog;

String time, distance;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

et_pickup = (EditText)findViewById(R.id.edit_pickup);
et_dropoff = (EditText)findViewById(R.id.edit_dropoff);
et_distance = (EditText)findViewById(R.id.edit_dist);
et_time = (EditText)findViewById(R.id.edit_time);

b_click = (Button)findViewById(R.id.btn_click);

b_click.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub

if(et_pickup.getText().toString().length() == 0)
{
Toast.makeText(getApplicationContext(), "Please Enter Your Pickup Point",                                        Toast.LENGTH_LONG).show();
}
else if(et_dropoff.getText().toString().length() == 0)
{
Toast.makeText(getApplicationContext(), "Please Enter Your Dropoff                                                   Point", Toast.LENGTH_LONG).show();
}
else
{
// Call url with user define values

String url = "http://maps.googleapis.com/maps/api/directions/json?origin="                                           + et_pickup.getText().toString().replace(" ", "%20") + 
        "&destination=" + et_dropoff.getText().toString().replace(" ", "%20")                                                   +"&sensor=false&units=imperial";

// Create a class for parsing url
GetJson gs = new GetJson(url);
                gs.execute();
       
                Log.i("LOG_URL", "URL Is: "+url);
       
               progDialog = new ProgressDialog(MainActivity.this);
               progDialog.setMessage("Please Wait.....");
               progDialog.setCancelable(false);
               progDialog.show();
}
}
});
}

// Implement the class with AsyncTask for Parsing
private class GetJson extends AsyncTask<Object, Object, Object>
  {
  private String url;
private InputStream is1;
private String res;

  // Constructor
public GetJson(String url)
  {
  this.url = url;
  }
 
// Code performing long running operation goes in this method.
// For Example: When onClick method is executed on click of button, it calls 
// execute method which accepts parameters and automatically calls 
//doInBackground method with the parameters passed.

@SuppressWarnings("deprecation")
@Override
protected Object doInBackground(Object... params) 
{
try
               {
              HttpClient httpclient1 = new DefaultHttpClient();
              HttpPost httppost1 = new HttpPost(url);
              HttpResponse response1 = httpclient1.execute(httppost1);
              HttpEntity entity1 = response1.getEntity();
              is1 = entity1.getContent();
              } 
              catch(Exception e) 
             {
           Log.e("log_tag", "Error in http conection"+e.toString());
             }

     try 
            {
     BufferedReader reader1 = new BufferedReader(new InputStreamReader(is1,"iso-                                8859-1"),8);
                        StringBuilder sb1 = new StringBuilder();
                        String line1 = null;
           
                        while ( (line1 = reader1.readLine() ) != null) 
                       {
                      sb1.append(line1 + "\n"); 
                       }
                       is1.close();
                       res=sb1.toString();
                       Log.i("Response from url = ", res);
           }
           catch(Exception e)
          {
        Log.e("log_tag", "Error converting result "+e.toString());
           }
return null;
     }

    // This method is called after doInBackground method completes processing. 
    // Result from doInBackground is passed to this method.

    @Override
     protected void onPostExecute(Object result1) 
     {
super.onPostExecute(result1);
returnresult(res);
      }
  }
 
// This method is display the result of parsejson method.

  private void returnresult(String res) 
  {
Log.i("Result = ", res);
parsejson(res);
}
 
  // This method is used for parsing of user required url with Json Object, Json Array and so on. 
  private void parsejson(String res)
  {
try 
{
JSONObject rootObj = new JSONObject(res);
JSONArray routes = (JSONArray) rootObj.get("routes");

JSONObject firstRoute = (JSONObject) routes.get(0);
JSONArray legs = (JSONArray) firstRoute.getJSONArray("legs");

JSONObject firstLeg = legs.getJSONObject(0);

JSONObject distanceObject = (JSONObject) firstLeg.get("distance");
JSONObject durationObject = (JSONObject) firstLeg.get("duration");

distance =  distanceObject.getString("text");
time = durationObject.getString("text");

Log.i(" Distance = ", distance);
Log.i(" Duration = ", time);

et_distance.setText(distance);
et_time.setText(time);

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

Permission: You must have to add Internet permission into your menifest file.

<uses-permission android:name="android.permission.INTERNET"/>

Output:


























Just enter Pickup and Drop-off Point and Click on button. You will get following screens.


















































Happy Coding...!!!

No comments:

Post a Comment