Join

Calling a JSON based ASP.NET web-service from an Android phone

Our first task, in the quest of mastering the Android platform involved calling an ASP.Net based web service from an Android phone, and passing it simple contact information data – Name, Email, and Address. Once the control reaches the web service, we write that data into a CSV file.

Doing this successfully would allow us to take the core of our processing away from Java/Android into C#.

To call a web service we’ll need to access the web service across the network, for which we’ll need PERMISSIONS to access the user’s internet, WI-FI and/or Data Connection. Add the following to our AndroidManifest.xml file,

It will be a JSON based request. We could have passed data using SOAP (XML) which would have been easier, but we decided to go with a JSON based web service because of the performance advantages. These are the following steps to get this task done,

  1. Create a UI where the user could enter his Name, Email and Address and press a button to initiate the call to the web service
  2. Attach an event handler to the button click event. Validate all the fields and make sure all of them have data.
  3. Before sending the data, check if the user has internet connectivity.
  4. If validation succeeded initiate the call to the web service, if it failed display the user an appropriate message.
  5. Receive the data on the web service and write it into a CSV file, return a proper status number, indicating whether that the data was successfully saved.
  6. Receive the JSON response on the phone and parse it to receive the meaningful data.
  7. Depending on whether the data was saved or not, display a small notification to the user.

Creating a user interface and validating all the fields is a fairly simple task. Android Developer Tool (ADT) provided by Google, offers drag and drop UI support. This also generates the required XML. You are free to write your own XML too if you so desire.

Following this short tutorial was all that we need to get started with UI development. It won’t make you an expert but that is good enough for the task at hand.

Calling the web service to save the data will be a little trickier. Instead of creating an object and passing that object to the web service, we will keep it simple and pass three different strings for Name, Email and Address.

Before calling the web service though we have to make sure that the fields are validated and that the user’s mobile device has Internet connectivity. Internet connectivity can be obtained through WI-FI or the data connection.

We can write a simple Utility class that would allow us to check if network connectivity is available. To view the code click here. The function you are looking for is hasNetwork()

Because it is a network process that would probably take at least a few second to complete, create a new class that extended AsyncTask. This ensures that the data saving occurred in the background, and the main UI thread would not be locked. Show a simple progress dialog box on the UI while the data was being saved on the server.

Click here to view the code snippets.

Save the data on the server side.

Click here to view the web service code, the major data saving part has been encapsulated in a separate class but the web service signature is what is important.

Note that the names of the parameters are the same on both the web service and the java code on the Android.

Send a status ID back from the server and in the code snippet I linked to earlier, there are three lines of code that take care of parsing the JSON data received and getting the status ID.

Once status ID is checked, display the user a simple Toast message stating whether the call was a success or not.

The possibilities now are endless. This will now allow us to combine our Android knowledge with our existing expertise in areas of ASP.NET and C#.

Author: Abijeet Patro

About Author: Abijeet Patro is a solution architect and a member of R&D department at Osmosys. He has experience in website designing and in developing solutions using .Net technologies.

11 thoughts on “Calling a JSON based ASP.NET web-service from an Android phone

  1. Mfundo Delihlazo
    at 4:32 pm

    Hi,

    I want to read from a list of data web service and save it to SQLite on an android device.

    Thank you

  2. Debasis
    at 7:27 am

    Hi,
    Abijeet Patro Borther this is very nice article , but ididnot understand how to send a status ID from the Server or from my webservice build in asp.net, can you please help me by saying details of it or any code project you have , please send it to my mail id on mo.debasis@gmail.com

  3. Sagar Zala
    at 5:13 am

    Hi,

    I want to read data from .net web service using json in android.

    Thank you

  4. Debasis
    at 4:31 pm

    Hi Abhijeet brother…very nice post …but if you can send me this code snippet done in asp.net webservices on my mail id mo.debasis@gmail.com , in advance thanks and i will be grateful to you

  5. poonam
    at 2:01 pm

    I wnt to consume jsonbased asp.net webservice in android….i tried ur code bt d debuger gets suspended aftr httpresponse in android..y it is so..m i gng wrng…

  6. poonam`
    at 5:09 am

    hello my code is nt working…after httpresponse my debuger gets suspended..
    m consuming json based asp.net webservice from android..any help will b appreciated..

  7. poonam`
    at 5:16 am

    on the main page m calling webservice on button click
    below is my code…

    package com.example.hellodemo;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpRequest;
    import org.apache.http.HttpResponse;
    import org.apache.http.StatusLine;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    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 android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    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;

    public class MainActivity extends Activity implements OnClickListener {

    private Context context;
    private ProgressDialog pd;
    private Button b;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    context = this;
    b = (Button) findViewById(R.id.btnLogin);
    b.setOnClickListener(this);
    // callerwebservice();
    }

    @Override
    protected void onDestroy() {
    if (pd != null) {
    pd.dismiss();
    b.setEnabled(true);
    }
    super.onDestroy();
    }

    private HttpParams getHttpParameterObj(int timeOutConnection,
    int timeOutSocket) {
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(httpParameters,
    timeOutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeOutSocket);
    return httpParameters;
    }

    public String callerwebservice() {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(
    “http://localhost:8585/connector/wsreports.asmx/HelloWorld”);
    try {
    HttpResponse response = client.execute(httpGet);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();
    BufferedReader reader = new BufferedReader(
    new InputStreamReader(content));
    String line;
    while ((line = reader.readLine()) != null) {
    builder.append(line);
    }
    } else {
    Log.e(MainActivity.class.toString(), “Failed to call WebService”);
    }
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return builder.toString();
    }

    @Override
    public void onClick(View v) {

    new Thread(new Runnable() {
    @Override
    public void run() {
    try {
    callerwebservice();
    Thread.sleep(20000);

    } catch (Exception e) {
    e.printStackTrace();
    }

    }

    }).start();

    v.setEnabled(false);
    AsyncTask task = new AsyncTask() {

    private HttpRequest resp;

    @Override
    protected void onPreExecute() {
    pd = new ProgressDialog(context);
    pd.setTitle(“Processing…”);
    pd.setMessage(“Please wait.”);
    pd.setCancelable(false);
    pd.setIndeterminate(true);
    pd.show();
    }

    @Override
    protected Void doInBackground(Void… arg0) {

    return null;

    }

    protected void onPostExecute(Void result) {
    if (pd != null) {
    pd.dismiss();
    b.setEnabled(true);
    }
    }

    };
    task.execute((Void[]) null);
    }
    }

    M in urgent need of help..plzzzzz help me asap.

    I tried the above code but still had the problem as same as finding in my above code.

  8. poonam`
    at 5:20 am

    m not using any parameter in in my asp.net webservice m simply calling helloworld methos which returns string helloworld…

  9. munesh
    at 12:21 pm

    hi poonam you can try this code i have done this type prgrram.
    import java.net.ConnectException;
    import java.net.SocketTimeoutException;
    import java.net.UnknownHostException;
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;

    public class MainActivity extends ActionBarActivity implements OnClickListener {

    private Button HelloWorldServiceButton, ;
    private TextView logTextView;

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

    invokeServiceButton = (Button) findViewById(R.id.invokeButton);
    getRoomButton = (Button) findViewById(R.id.getRoomButton);
    logTextView = (TextView) findViewById(R.id.logTextView);
    invokeServiceButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View v)
    {
    if (v.equals(invokeServiceButton))
    {
    invokeServices().execute();
    }
    }

    public static final String NAMESPACE = “http://”;
    public static final String SERVICE_URL = “http://”;
    public static final String SOAP_ACTION_Hello_SERVICE = “http://”;
    public static final String METHOD_NAME_Hello_SERVICE = “”;

    public AsyncTask invokeServices() {
    return new AsyncTask() {
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    }

    @Override
    protected String doInBackground(String… params) {
    String resultData = “null”;
    try {
    SoapObject request = new SoapObject(NAMESPACE,

    METHOD_NAME_Hello_SERVICE);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER11);
    envelope.dotNet = true;

    System.setProperty(“http.keepAlive”, “true”);
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(
    SERVICE_URL, 10000);
    androidHttpTransport.debug = true;
    androidHttpTransport.call(SOAP_ACTION_INVOKE_SERVICE,
    envelope);
    SoapPrimitive result = (SoapPrimitive) envelope
    .getResponse();
    resultData = result.toString();
    Log.e(“DiscoverServices”, “ResultData: ” + resultData);
    } catch (Exception e) {
    e.printStackTrace();
    return e.getMessage();
    }
    return resultData;
    }

    @Override
    protected void onPostExecute(String result)
    {
    logTextView.setText(result);
    super.onPostExecute(result);
    }
    };
    }

    my mail id: munesh.parmar@outlook.com

  10. vetriselvan
    at 5:27 am

    hi friends please help me.
    i need to send android details to .net database using entity framework and web api.

  11. User
    at 3:45 pm

    A,salam
    i want Android to webservice json parsing using volley can any one refer me a link or tutorial

Leave A Reply