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
  • kchaou

    svp, je veux class du web service aussi les methodes thx

    Translated Text: Please, I want the web service class as the methods thx

    • Sure Kchaou. I am planning to share Web Service code as well. Thanks.

      • kchaou

        thx , j’attends πŸ™‚

  • parth

    Actuallu I downloaded the whole code and put into my eclispse. After that if I run the project it won’t give me the output and it just show me that error connecting to the network. In which my network is perfectly run.

    If you have any suggestion reply me to this email.

    • Have you enabled Internet and also created and deployed Java Web Service in your local machine?. If possible post me the error log message here, will provide more insights for your problem.

      • Corent

        ya parth right,i just debug this code, and i found

        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;

        i never go to startActivity(intObj); because condition always error, why?

        just i change

        if(loginStatus){
        //Navigate to Home Screen
        statusTV.setText(“Login Failed, try again”);
        }else{
        //Set Error message
        startActivity(intObj);
        }

        it work!!

  • Long Nguyen

    Thank you Guru, it helps me a lot.

    • You are welcome. πŸ™‚

      • Long Nguyen

        Hi Guru,

        I have a problem when try to call multiple methods in 1 soap request. Below is the code in web server, I would like to call isCorrect(); and I have to pass values to setUserName(String userName) and setPassword(String password); Please tell me what should I do for this case. Thanks Guru!

        public void setPassword(String password) {
        this.password = password;
        }

        public void setUserName(String userName) {
        this.userName = userName;
        }

        public boolean isCorrect(){
        if(this.userName.equals(“abc”) && this.password.equals(“xyz”))
        return true;
        else
        return false;
        }

  • Hi Long Nguyen,

    I have modified your code, please see below:

    public void setPassword(String password) {
    this.password = password;
    }

    public void setUserName(String userName) {
    this.userName = userName;
    }

    public boolean isCorrect(String uname, String pwd){
    setUserName(uname); //set username sent from web service call to username variable
    setPassword(pwd); //set password sent from web service call to password variable
    if(this.userName.equals(“abc”) && this.password.equals(“xyz”))
    return true;
    else
    return false;
    }

    Make sure you pass two parameters to webmethod isCorrect() from your application.
    Let me know if you still need any help. πŸ™‚

    • Long Nguyen

      Thanks Guru, but I cannot modify the code on server side so I’m finding a solution on android client without changing the code in web server. Please let me know if you have any suggestion. Anw, your Android Tutorial Bog is really good. Thanks so much πŸ™‚

    • Long Nguyen

      hmm I’ve just replied but seems like my comment has disappeared. Just want to say I cannot modify the code on web server so I’m finding a solution on andoird client without changing the code on server side. Please let me know if you have any suggestion. Anw, thanks for your Android Tutorial Blog, it’s very helpful.

      • Comment was waiting for moderation that’s why it was not appearing. You can ask the developer at server side to modify isCorrect() method to accept two parameters otherwise there is no feasible solution for your problem I guess. Let me know if you find one. T
        Thanks for your comments about my blog.
        Spread a word about this blog to your friends and colleagues. πŸ™‚

        • Long Nguyen

          Sure. Thanks again πŸ™‚

  • Asif

    Hi there,I need the Web Service Coding pls

  • Asif

    Hi Guru,
    Can I have the web services Code to get a better understanding on how to authenticate user?

    Thanks

  • Asif

    Hi there,

    Can I please have the Web Service Coding?

  • Gaurav

    hey can u pls post .net web service login authentication example..

  • First thing: Make sure Java web service you created is up and running in server.

    Initially boolean variable ‘errored’ is set to false. After making web service call, boolean variable ‘loginStatus’ will be assigned with the value returned by web service.

    When login is successful, web service will assign true otherwise false.

    Note: Don’t initialize the boolean variable to true as you mentioned in the comment.

    Hope you got it.

  • Hassan

    Hi Guru,
    Can I have the web services Code to get a better understanding on how to authenticate user?

    Thanks

  • Hi Hassan,

    Download link is already there under ‘Java Web Service’ section.

  • sunil

    plz share the web service …..

  • It is already available for download.

  • Shivin Bhogal

    When I press the “Login” button a message “error occured in invoking webservice is displayed”. I am using glass fish 4.1 server to deploy the webservice. I want to know what should be “Webservice URL – WSDL File location”?

  • Yes. It must be WSDL.

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