INVOKE JSON WEB SERVICE IN ANDROID

WEB SERVICES:
By using web services, we can transfer data between the electronic devices. If we create web services for one platform and it can be accessible from any of the platform. There are many types of web services. 
Some of them are,
  • JSON
  • SOAP
JSON web service is best suitable for Android platform.
JSON WEB SERVICES:
JSON - JavaScript Object Notation. 
JSON is a light weight web service. We can obtain the response from JSON in the following ways,

  • JSON array,
  • JSON object.
STEPS TO CREATE JSON CALL
  • Create Android project with name as "JSONCall". Set Main Activity name as "JSONService". This is the code for JSONService.

package com.json.jsoncall;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class JSONService extends Activity {
Boolean isInternetConnected = false;
JSONObject json;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_jsoncall);
    NetWorkStatus status;
    status = new NetWorkStatus(JSONService.this);
    isInternetConnected = status.isConnecting();
    if (isInternetConnected) {
    new Invoke().execute("");
    }
    else {
    showAlertDialog(JSONService.this, "No Internet Connection", "You don't have internet connection.", false);
    }
}
public class Invoke extends AsyncTask{
    JsonParser jsonParser = new JsonParser();
    ProgressDialog dialog;
    protected void onPreExecute() {
    dialog = new ProgressDialog(JSONService.this);
    dialog.setMessage("Please wait...");
    dialog.setCancelable(false);
    dialog.show();
}
@Override
protected String doInBackground(String... arg0) {
    String URL = "http://192.168.3.136:28080/echain/services/ListHolidays";
    /*Make JSON Request*/
    final String body = String.format("{\"userName\": \"%s\", \"password\": \"%s\"}", "Administrator", "admin");
try {
    json = jsonParser.makeHttpRequest(URL, "POST", body);
    /*Parsing JSON Response*/
    JSONArray arr = json.getJSONArray("holidayBean");
    for(int i =0 ; i < arr.length(); i++){
    Log.d("JSONOutput" , arr.getJSONObject(i).getString("date"));
    Log.d("JSONOutput" , arr.getJSONObject(i).getString("sno"));
    Log.d("JSONOutput" , arr.getJSONObject(i).getString("day"));
    Log.d("JSONOutput" , arr.getJSONObject(i).getString("name"));
    }
}
catch (Exception e1) {
    Log.v("JSONCall Exception", Log.getStackTraceString(e1));
}
    return null;
}
protected void onPostExecute(String name) {
    dialog.dismiss();
    }
}
public void showAlertDialog(Context context, String title, String msg, Boolean status) {
    AlertDialog.Builder builder = new AlertDialog.Builder(JSONService.this);
    builder.setTitle(title)
   .setMessage(msg)
   .setCancelable(false)
   .setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { dialog.cancel();
    }
});
    AlertDialog alert = builder.create();
    alert.show();
    }
}

  • Create "Network Status" class. It will check the status of your network connection.

package com.json.jsoncall;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetWorkStatus {
    private Context _context;
    public NetWorkStatus(Context context){
    this._context = context;
}
public boolean isConnecting(){
    ConnectivityManager connectivity = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null){
    NetworkInfo[] info = connectivity.getAllNetworkInfo();
    if (info != null){
    for (int i = 0; i < info.length; i++){
    if (info[i].getState() == NetworkInfo.State.CONNECTED){
    return true;
         }
        }
      }
    }
    return false;
    }
}

  • Create "JSON Parser" Class. It will invoke the JSON response.
package com.json.jsoncall;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
public class JsonParser {
    static JSONObject jObj = null;
    static String json = "";
    public JsonParser(){
}
public JSONArray jArray(){
    return null;
}
public JSONObject makeHttpRequest(String url, String method,String params) throws Exception {
    final HttpClient client = new DefaultHttpClient();
    final HttpPost postMethod = new HttpPost(url);
    postMethod.setHeader("Content-Type","application/json");
    postMethod.setEntity(new StringEntity(params, "utf-8"));
try {
    final HttpResponse response = client.execute(postMethod);
    json = EntityUtils.toString(response.getEntity(), "utf-8");
}
catch(final Exception e) {
    Log.v("JSonParser Exception", Log.getStackTraceString(e));
}
try {
    jObj = new JSONObject(json);
} catch (Exception e) {
    Log.v("JSonParser Exception", Log.getStackTraceString(e));
}
    return jObj;
  }
}

  • Add following permission in manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

  • This is the output screen of the program.

Comments

Popular posts from this blog

SQLiteDatabase With Multiple Tables

Programmatically turn ON/OFF WiFi on Android device

Android Service and IntentService