Posted by: osmosee | July 20, 2013

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,

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

</uses-permission>

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >

</uses-permission>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >

</uses-permission>

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()

package osm.droid.osmcontactus;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class Utility {
static Context context;
static LocationManager locationManager;
public static void setContext(Context context)
{
Utility.context = context;
}
public static void setLocationManager(LocationManager locationManager2) {
Utility.locationManager = locationManager2;
}
/***
* Checks if a device has GPS and returns TRUE if it does and the GPS is enabled else returns FALSE.
* @return FALSE or TRUE, depending on the presence and state of the GPS.
*/
public static boolean hasGPSandIsEnabled()
{
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS))
{
// It's present, check if it's enabled.
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
return true;
}
else {
return false;
}
}
else
{
// Not present, not enabled.
return false;
}
}
/***
* Checks if a device has network connectivity - both for WIFI and MOBILE and then returns true if it does.
* @return TRUE or FALSE depending on whether network connectivity is available.
*/
public static boolean hasNetwork()
{
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
/***
* Get Location Provider, depending on what's available NETWORK or GPS. Returns null if both of them are disabled.
* @return
*/
public static String getLocationProvider()
{
if(hasGPSandIsEnabled())
{
return LocationManager.GPS_PROVIDER;
}
else if(hasNetwork())
{
return LocationManager.NETWORK_PROVIDER;
}
else {
return null;
}
<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">}
</span><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">}
</span><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">public static boolean hasSdCard()
</span>{
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
}

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.

// Making an HTTP Post call, and passing the URL
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("content-type", "application/json");
HttpClient httpClient = new DefaultHttpClient(getHttpParameterObj(4000,4000));
// Building the JSON object.
JSONObject data = new JSONObject();
data.put("name", name);
data.put("email",email);
data.put("address", address);
StringEntity entity = new StringEntity(data.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
// Making the call.
HttpResponse response = httpClient.execute(httpPost);
// Getting data from the response to see if it was a success.
BufferedReader reader =new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResultStr = reader.readLine();
data = new JSONObject(jsonResultStr);
return data.getString("d");

// GET HTTP PARAMETER OBJECT METHOD!
/***
* Build HTTP Parameters, such as timeOut.
* @param timeOutConnection
* @param timeOutSocket
* @return
*/
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;
}

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.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
#region Save User Data
public string saveUserData(string name, string email, string address)
{
Contact cntObj = new Contact(name, email, address);
// Save Contact Details takes care of all the storage part and such.
return saveContactDetails(cntObj);
}
#endregion

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.

About these ads

Responses

  1. Hi,

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

    Thank you

  2. 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. Hi,

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

    Thank you

  4. 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. 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. 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. 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. m not using any parameter in in my asp.net webservice m simply calling helloworld methos which returns string helloworld…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

Join 45 other followers

%d bloggers like this: