Android JSON Web Service Tutorial

In this post we will be discussing on how to consume JSON response (returned on invoking web service) in Android applications. I took simple example to demonstrate the JSON Web service tutorial. The example which we are gonna create will have two spinner controls (called Dropdownlist in traditional desktop applications), one to display ‘Countries’ list and other to display ‘Cities’ list.

When user selects a country from the ‘Countries’ spinner control, cities belong to the selected country will be populated in the ‘Cities’ spinner control.




We are going to create:

  1. Dot Net Webservice and install it in local IIS server
  2. Android application which will consume the response from Webservice deployed in IIS server

Points to note:

  1. Connect your mobile and your local machine (where IIS installed) to same WiFi internet connection so that application which we are developing can access WebService installed in the local server.
  2. Make sure you turned off Firewall in your local machine since FireWall will not allow the local machine to accept Http calls from other machines, mobiles or servers
Subscribe and download free ebook
Email:

As this application requires Internet connectivity to hit Web Service hosted in remote server, it would be good if Internet connectivity check is done before trying to hit Web Service..

Here are the tutorials which talk about checking Wifi/Mobile Internet:

Android Check Wi-Fi Internet Connection
Android Check Mobile Internet Connection

Webservice creation

Before we proceed with developing Android application, create a simple Dot Net Webservice which takes ‘Country’ as parameter and returns ‘City’ list as JSON. Go through the below links to know how to create and deploy Dot Net Webservice in IIS Server.

How-to-create-webservice-in-asp-net-using-csharp
How-to-deploy-asp-dot-net-webservice-in-iis

If you are bit lazy in creating Webservice and want to complete developing Android application with much ease, download code (Dot Net Webservice + Android application) right from here. After downloading the Dot Net Webservice project, import it in Visual Studio and deploy it in IIS server. Take help from the links I mentioned above to deploy Webservice in IIS server.

I used NewtonSoft JSON DLL (library) to serialize C# objects in Webservice. Click here to know more about NewtonSoft JSON DLL. You can download NewtonSoft JSON DLL from here without Nuget installation.

Android application creation

Refer below link to know how to call Dot Net Webservice in Android application before we start creating application as it would be easy for you to proceed further:

How to call asp.net web service in android

Quick Links

Project Structure

Layout creation:

  • Create new android project [File >> New >> Android Project] with project name WebserviceActivity
  • Click next and select target android device version [I chose version 3.2]
  • Click next and enter package name – ‘com.prgguru.android’
  • Click finish

Code Listings

Layout XML:

Open main.xml present under /res/layout folder and replace the XML with the below one.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text=""
        android:textSize="26dp" />

    <Spinner
        android:id="@+id/countrySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/citySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:visibility="invisible"/>

</LinearLayout>

KSOAP client library is being used in Android to make WebService calls. You can download KSOAP library from here and add it in lib folder of Android project

Add below code into the WebserviceActivity class we created. I have given comment to each and every line of the code so I hope you will understand code without any difficult.

package com.prgguru.android;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.Spinner;

import com.example.webserviceactivity.R;
import com.google.gson.Gson;
public class WebserviceActivity extends Activity {
	private final String NAMESPACE = "http://tempuri.org/";
	//Change IP to your machine IP
	private final String URL = "http://192.168.1.101/JSONService/Service.asmx";
	private final String SOAP_ACTION = "http://tempuri.org/";
	private String TAG = "PGGURU";
	private static String responseJSON;
	//Country Spinner Control
	Spinner countrySpinnerCtrl;
	//City Spinner Control
	Spinner citySpinnerCtrl;
	ProgressBar pg;
	String[] placelist;
	//GSON object
	Gson gson = new Gson();
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//City Spinner control
		citySpinnerCtrl = (Spinner) findViewById(R.id.citySpinner);
		//Country Spinner control
		countrySpinnerCtrl = (Spinner) findViewById(R.id.countrySpinner);
		//Progress bar to be displayed until app gets web service response
		pg = (ProgressBar) findViewById(R.id.progressBar1);
		//AysnTask class to handle Country WS call as separate UI Thread
		AsyncCountryWSCall task = new AsyncCountryWSCall();
		//Execute the task to set Country list in Country Spinner Control
		task.execute();

		countrySpinnerCtrl.setOnItemSelectedListener(new OnItemSelectedListener() {
			//When an item is selected from Country Spinner Control
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				//Get the selected  item value
				String floor = countrySpinnerCtrl.getSelectedItem().toString();
				//AsynTask class to handle City WS call as separate UI Thread
				AsyncCityWSCall task = new AsyncCityWSCall();
				//Execute the task
				task.execute(floor);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		});
	}

	//AysnTask class to handle Country WS call as separate UI Thread
	private class AsyncCountryWSCall extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... params) {
			Log.i(TAG, "doInBackground");
			//Invoke web method 'PopulateCountries' with dummy value
			invokeJSONWS("dummy","PopulateCountries");
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.i(TAG, "onPostExecute");
			//Convert 'Countries' JSON response into String array using fromJSON method
			placelist = gson.fromJson(responseJSON, String[].class);
			//Assign the String array as Country Spinner Control's items
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
					android.R.layout.simple_dropdown_item_1line, placelist);
			countrySpinnerCtrl.setAdapter(adapter);
			//Make the progress bar invisible
			pg.setVisibility(View.INVISIBLE);
		}

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "onPreExecute");
			//Display progress bar
			pg.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			Log.i(TAG, "onProgressUpdate");
		}

	}

	//AsynTask class to handle City WS call as separate UI Thread
	private class AsyncCityWSCall extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... params) {
			Log.i(TAG, "doInBackground");
			//Invoke web method 'PopulateCities'
			invokeJSONWS(params[0],"PopulateCities");
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.i(TAG, "onPostExecute");
			//Convert 'Cities' JSON response into String array using fromJSON method
			placelist = gson.fromJson(responseJSON, String[].class);	
			//Assign the String array as Country Spinner Control's items
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
					android.R.layout.simple_dropdown_item_1line, placelist);
			citySpinnerCtrl.setAdapter(adapter);
			//Make the progress bar invisbile
			pg.setVisibility(View.INVISIBLE);
		}

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "onPreExecute");
			//Display the progress bar
			pg.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			Log.i(TAG, "onProgressUpdate");

		}

	}

	//Method which invoke web methods
	public void invokeJSONWS(String country, String methName) {
		// Create request
		SoapObject request = new SoapObject(NAMESPACE, methName);
		// Property which holds input parameters
		PropertyInfo paramPI = new PropertyInfo();
		// Set Name
		paramPI.setName("country");
		// Set Value
		paramPI.setValue(country);
		// Set dataType
		paramPI.setType(String.class);
		// Add the property to request object
		request.addProperty(paramPI);
		// Create envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		// Set output SOAP object
		envelope.setOutputSoapObject(request);
		// Create HTTP call object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

		try {
			// Invole web service
			androidHttpTransport.call(SOAP_ACTION+methName, envelope);
			// Get the response
			SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
			// Assign it to static variable
			responseJSON = response.toString();

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

}
I used Google JSON (GSON) JAR (library) to de-serialize JSON object returned as response of Webservice. Click here to know more about GSON Java Library. You can download GSON JAR from here.

Internet permission
Don’t forget to add internet permission in AndroidManifest.xml:

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

Demo

Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screens:



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse).

Download Source Code

If you feel the tutorial is helpful, please share your feedback below.


Author: Android Guru

Share This Post On
  • Hades Alwan

    thanks to your tutorial.

  • http://android.programmerguru.com/ Android Guru

    I don’t have idea about accessing MS Access database from within C# because I don’t have much exposure on Microsoft technologies.

    Android to Java/MySQL is already discussed here:

    http://programmerguru.com/android-tutorial/android-restful-webservice-tutorial-how-to-call-restful-webservice-in-android-part-3/

    You can find details about KSOAP methods from here:

    http://ksoap2.sourceforge.net/doc/api/

  • Hemal

    Hello ProgrammerGuru: This is the best example I could find over Internet for Android web services. Works perfect for me.

    I was trying to make some additions but couldn’t get it to work. I tried to add MS Access database to C# Services file in .net. When I check that in Visual Studio it showed results. But when I tried to Browse that through IIS 7. It would show an error. It would say. Connection is closed. And in my Android app too, it wouldn’t fetch database results. Can you please help me out with that?

    Also If you can please upload an example for Android to PHP,MySQL web service and Android to Java,Oracle. That would be a big favor or you guide me to a book or another page for the same. Nobody has explained fully as you did. Some has posted PHP files but not Android files.

    Also about

    SOAPObject, SoapSerializationEnvelope, envelope.dotNet = true, HttpTransportSE androidHttpTransport = new HttpTransportSE(URL), androidHttpTransport.call(SOAP_ACTION+methName, envelope),SoapPrimitive response

    above methods. Where I can find their info?

    Thanks,

  • Rohit Sawant

    Just like city gets filled in spinner, I want to send city and id from database from webservice and show in list in android. How this can be done.
    PS: I am new to android and JSON programming.

  • maher

    thank u

  • manikanta

    thanks for your tutorial,before seeing this program i don’t know how to connect web service to spinner.but i have learned by seeing this demo program

    • http://programmerguru.com/android-tutorial Android Guru

      Thanks for letting us know. :)
      Happy learning!

      • manikanta

        i imported the above program in eclipse but program is not running

        • http://programmerguru.com/android-tutorial Android Guru

          Please make sure that you created and deployed Dot Net Webservice in your local IIS server. It is actually used in the code to retrieve Cities as JSON value.

  • girishkumar

    in my xml i have 2 spinners ,1 for getting property details (select,igo,otr-ict..),and 2nd for getting room details like (select,1bhk,2bhk,3bhk), if i select 1st spinner it shud display dis things else if i shud select 2nd spinner it shud display 1bhk,2bhk….
    How to connect local webserver to spinner?

x
Subscribe and stay in touch!!

Enter your email and stay on top of things:

Your email address will not be published