Consuming Android Web Services

In the previous tutorial, you have learned the basics of Web Services in Android. In this tutorial, you will learn how to consume Android Web Services.

Introduction

To consume The Web Services in Android applications, you must follow the given Steps.

  1. Needs permissions to access the internet
    You can give permissions for the Internet access to you Android application in Manifest file
  2. Send and Receive data over the internet
    In Android, you can use the class HttpURLConnection to send and receive data over the internet.
  3. Parse JSON Data
    You can use JSONObject & JSONArray classes to parse JSON data in Android.
  4. Update the User Interface to received information
    Use AsyncTask class allows performing background tasks and publish results on the User Interface threads without manipulating threads and handlers.

Android Web Services Project

Click here to Download the complete Android Studio project of RESTful web services

Create a new Project

Create a new project in Android Studio or Eclipse ADT. Create a new Activity to show data from the internet.

Android Activity for Web Services

Create an EditText to get the country name and a Button to get info on click. Also, add TextViews  to display the response the web service.

Android Activity for Web Services
Android Activity for Android Web Services

Implement the button Click Event in MainActivity.java

Your MainActivity.Java file will look like

You can also use Retrofit with Gson to get Countries data from Rest Countries API

AsyncTask

AsyncTask class allows performing all the background operations. It also publishes results on the User Interface thread without having to manipulate the threads or handlers or both. An asynchronous task is defined by three generic types. These types are known as Params, Progress, and Result.

There are four methods which must be overridden when you use AsyncTask. You must also implement the functionality of these methods also.

  1. onPreExecute
  2. doInBackground
  3. onProgressUpdate
  4. onPostExecute

Either you need to override onPostExecute(Result) method or doInBackground(Params…). Most often you need to override onPostExecute(Result).

MainActivity.java

Implement the button onClick event i.e. loadCountryInfo(View view) to get the data in the TextEdit

Within your MainActivity class, create a subclass named wsAsyncTask which will extend AsyncTask to run the background task. This class will help you to perform background tasks. In doInBackground(String[] strURL) method return requestWebService(strURL[0]). In the pre-execution of the of wsAsyncTasks, display a progress bar showing the loading. Dismiss the progress bar when the task is complete i.e. in onPostExecute() method.

Also, implement a method to request the web service in the wsAsyncTask class.

requestWebService()

Create Connection

Pass the URL as a string in the method. Create an instance of URL class and put the serviceURL value from the parameters in URL class constructor. Create an instance of HttpURLConnection and initialize the connection with.(HttpURLConnection) urlToRequest.openConnection() Set the connect timeout and read timeout for the connection.

Get the JSON Data

Use InputStream for URL connection Input Stream. Instantiate InputStream class and call the constructor of BufferedInputStream(urlConnection.getInputStream()). Use Scanner class to convert input stream to the string. After conversion close the Scanner.

You must handle MalformedURLException for URL exceptions, SocketTimeoutException for connection timeout, and IOexception for the read response errors.

Complete Code for requestWebService(String serviceUrl) Method

 

Get Response from Web Service and Populate Text Fields

In the overridden method onPostExecute(), first initialize all the text fields you want to populate from the web service response.

JSONArray and JSONObject

Declare and Initialize JSONArray and JSONObject

Publish Results on The User Interface Threads

Populate TextViews JSONObject instance by using the optString() method.

Complete Code of onPostExecute(String result) Method

Place the code of JSONArray and JSONObject in try catch block to handle unexpected exceptions. If the service returns null or some error.

Country Information Android Web Service
Country Information in Android Web Services

Click here to Download the complete Android Studio project of web services

You can also use Retrofit with Gson to get Countries data from Rest Countries API

Complete Code for MainActivity.java

Click here to Download the complete Android Studio project of web services

Retrofit with Gson to get Countries data from Rest Countries API

Hope you like this tutorial. Stay tuned for more upcoming tutorials. Stay blessed!

Leave a Reply

Your email address will not be published. Required fields are marked *