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,
- 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
- Attach an event handler to the button click event. Validate all the fields and make sure all of them have data.
- Before sending the data, check if the user has internet connectivity.
- If validation succeeded initiate the call to the web service, if it failed display the user an appropriate message.
- 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.
- Receive the JSON response on the phone and parse it to receive the meaningful data.
- 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.
Leave a Reply