Android Java Web Service Login

In this post, I am going to discuss about how to authenticate Users in Android application using Java Web service.The application which I am gonna create will have two screens – Login screen and Home screen.

User has to type his/her credentials and click ‘Login’ button. Once ‘Login’ button is clicked, application fires call to Java web service along with Username and Password typed by User. Our Activity waits for response from the web service, once it receives response, it decides whether to take User to next screen(Home) or show ‘Login Failed’ message based on the response.

Here is the graphical representation of whatever we discussed:

If you are new to using Web service in Android, please take a look at below Web service tutorials which will help you for greater extent in understanding them.

Android Webservice example

How to call Java web service in android

Java Web Service:

Create a simple web service using JEE technology to return boolean value to client by taking two strings (Username and Password) as parameters and deploy it in Apache Tomcat or Glass Fish server installed in your local machine.

If you are lazy, don’t want to create Java webservice from scratch and just want to setup the webservice with zero coding, download it and deploy it in server:

Download Java Login Webservice

Points to note:

  1. Connect your mobile and your local machine (where Apache or Glass Fish server 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 or servers

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

[pgsubscribe]

As this application requires Internet connectivity to hit Web Service hosted in remote server, we need to check if Internet connectivity is available or not.

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

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

Quick Links

Project Structure

Create layout XML

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

Code Listings

Open main.xml, now you can view the layout as either XML or in graphical view and just replace the XML with 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/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#069c88"
        android:gravity="center"
        android:text="Login"
        android:textColor="#fff"
        android:textSize="30dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="Username"
        android:paddingTop="20dp"
        android:singleLine="true" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="Password"
        android:singleLine="true" />

    <Button
        android:id="@+id/button1"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_gravity="center_horizontal"
        android:background="#d28f35"
        android:gravity="center"
        android:text="Login" />

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

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

</LinearLayout>

We need to create three Classes:

  1. CheckLoginActivity.java – Login Screen
  2. HomeActivity.java – Home Screen
  3. WebService,java – Has basic webservice configuration
Login Screen

I hope CheckLoginActivity.java along with main.xml have been created when Android project was created.

Use Intent to navigate from Login Screen to Home Screen when login is successful.

Open CheckLoginActivity.java and replace it with below code(Each line is added with comment) :

CheckLoginActivity.java

package com.prgguru.example;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class CheckLoginActivity extends Activity {
	//Set Error Status
	static boolean errored = false;
	Button b;
	TextView statusTV;
	EditText userNameET , passWordET;	
	ProgressBar webservicePG;
	String editTextUsername;
	boolean loginStatus;
	String editTextPassword;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Name Text control
        userNameET = (EditText) findViewById(R.id.editText1);
        passWordET = (EditText) findViewById(R.id.editText2);
        //Display Text control
        statusTV = (TextView) findViewById(R.id.tv_result);
        //Button to trigger web service invocation
        b = (Button) findViewById(R.id.button1);
        //Display progress bar until web service invocation completes
        webservicePG = (ProgressBar) findViewById(R.id.progressBar1);
        //Button Click Listener
        b.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Check if text controls are not empty
                if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") {
                	if(passWordET.getText().length() != 0 && passWordET.getText().toString() != ""){
                		editTextUsername = userNameET.getText().toString();
                		editTextPassword = passWordET.getText().toString();
                		statusTV.setText("");
                		//Create instance for AsyncCallWS
                		AsyncCallWS task = new AsyncCallWS();
                		//Call execute 
                		task.execute();
                	}
                	//If Password text control is empty
                	else{
                		statusTV.setText("Please enter Password");
                	}
                //If Username text control is empty
                } else {
                    statusTV.setText("Please enter Username");
                }
            }
        });
    }

    private class AsyncCallWS extends AsyncTask {
		@Override
		protected Void doInBackground(String... params) {
			//Call Web Method
			loginStatus = WebService.invokeLoginWS(editTextUsername,editTextPassword,"authenticateUser");
			return null;
		}

		@Override
		//Once WebService returns response
		protected void onPostExecute(Void result) {
			//Make Progress Bar invisible
			webservicePG.setVisibility(View.INVISIBLE);
			Intent intObj = new Intent(CheckLoginActivity.this,HomeActivity.class);
			//Error status is false
			if(!errored){
				//Based on Boolean value returned from WebService
				if(loginStatus){
					//Navigate to Home Screen
					startActivity(intObj);
				}else{
					//Set Error message
					statusTV.setText("Login Failed, try again");
				}
			//Error status is true	
			}else{
				statusTV.setText("Error occured in invoking webservice");
			}
			//Re-initialize Error Status to False
			errored = false;
		}

		@Override
		//Make Progress Bar visible
		protected void onPreExecute() {
			webservicePG.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}	
}
Click here to know more about AsyncTask,
Home Screen

home.xml

Here is layout XML for Home screen. Create home.xml under res/layout folder and do copy and paste below XML code:

<?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="match_parent"
    android:orientation="vertical" >
<TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Home"
        android:textSize="30dp" android:background="#069c88" android:textColor="#fff"/ >
    <TextView
        android:paddingTop="20dp"
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome admin"
        android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center"/>

</LinearLayout>

HomeActivity.java

Create HomeActivity.java under package com.prgguru.android.
Here is the code for HomeActivity.java – Home screen.

package com.prgguru.android;

import android.app.Activity;
import android.os.Bundle;

public class HomeActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
	}
}
WebService Configuration

Create WebService.java under com.prgguru.android package and copy and paste below WebService.java inside it.
Make sure you updated URL with your machine IP address in WebService.java.

WebService.java

package com.prgguru.example;

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;

public class WebService {
	//Namespace of the Webservice - can be found in WSDL
	private static String NAMESPACE = "http://service.programmerguru.com/";
	//Webservice URL - WSDL File location	
	private static String URL = "http://192.168.2.2:8080/LoginWebService/LoginWebService?WSDL";//Make sure you changed IP address
	//SOAP Action URI again Namespace + Web method name
	private static String SOAP_ACTION = "http://service.programmerguru.com/";
	
	public static boolean invokeLoginWS(String userName,String passWord, String webMethName) {
		boolean loginStatus = false;
		// Create request
		SoapObject request = new SoapObject(NAMESPACE, webMethName);
		// Property which holds input parameters
		PropertyInfo unamePI = new PropertyInfo();
		PropertyInfo passPI = new PropertyInfo();
		// Set Username
		unamePI.setName("username");
		// Set Value
		unamePI.setValue(userName);
		// Set dataType
		unamePI.setType(String.class);
		// Add the property to request object
		request.addProperty(unamePI);
		//Set Password
		passPI.setName("password");
		//Set dataType
		passPI.setValue(passWord);
		//Set dataType
		passPI.setType(String.class);
		//Add the property to request object
		request.addProperty(passPI);
		// Create envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		// Set output SOAP object
		envelope.setOutputSoapObject(request);
		// Create HTTP call object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

		try {
			// Invoke web service
			androidHttpTransport.call(SOAP_ACTION+webMethName, envelope);
			// Get the response
			SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
			// Assign it to  boolean variable variable
			loginStatus = Boolean.parseBoolean(response.toString());

		} catch (Exception e) {
			//Assign Error Status true in static variable 'errored'
			CheckLoginActivity.errored = true;
			e.printStackTrace();
		} 
		//Return booleam to calling object
		return loginStatus;
	}
}

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

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

[pglinkadssmall1]

Demo

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

 




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). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

I hope this post is most useful to you!! 🙂

Keep us posted with your valuable comments below 🙂


[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares