Android Dot Net Web Service Login

In this post, I am going to discuss about how to authenticate Users in Android application using Dot Net 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 Dot Net 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 ASP Dot Net web service in android

ASP Dot Net Web Service:

Create a simple web service using ASP .Net technology to return boolean value to client by taking two strings (Username and Password) as parameters and deploy it in IIS server installed in your local machine.

How to deploy asp dot net webservice in iis

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

Download Dot Net Login Webservice

Points to note:

  1. Connect your mobile and your local machine (where IIS 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 CheckDNLoginActivity
  • 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. CheckDNLoginActivity.java – Login Screen
  2. HomeActivity.java – Home Screen
  3. WebService,java – Has basic webservice configuration
Login Screen

I hope CheckDNLoginActivity.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 CheckDNLoginActivity.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 CheckDNLoginActivity 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(CheckDNLoginActivity.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://tempuri.org/";
	//Webservice URL - WSDL File location	
	private static String URL = "http://192.168.2.5/LoginCheck/Service.asmx";//Make sure you changed IP address
	//SOAP Action URI again Namespace + Web method name
	private static String SOAP_ACTION = "http://tempuri.org/";
	
	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);
		envelope.dotNet = true;
		// 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'
			CheckDNLoginActivity.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
  • saqib

    you have recently posted this article, and you are using android device version 2.2, its pretty much older now. Is there would be any issue if i
    run this code in android device version 4.2 or 4.4?

  • Gaurav

    loginStatus = WebService.invokeLoginWS(editTextUsername,editTextPassword,”AuthenticateUser”);
    here “AuthenticateUser” is webmethod…… but where is define it?? and ur web service response is JSON or other???

  • Sandy

    this is code is not working for my soap based login webservice please help?

  • Response is SOAP response sent by Dot net web service.

  • Have you created dot net web service and deployed it in IIS server? If not please do the same.

  • raju

    I trying with urCODE that u put here.. .. but the progress bar rotating only…i coUdnt get any out put….i also tried with ma ofiice server..Then the same thing has happend….so please help mee…….
    my work completely depends up on this

  • Please make sure you enabled internet in your Android phone and also both phone and machine (where Apache server is running) are connected to same WiFi internet connection.

    In addition to that try to print statusCode of onFailure method in MainActivity Java Class and see what http response code your are getting. If the response code is 403/407 or some other code, please fix the issue accordingly.

    Let me know once you resolve the issue.

    • md ishtiyaque

      I am also face same problem and i don’t Know how i Can solve it .. plzzzz give me Solution

  • Thair Jaber

    Hello
    Thanks for amazing tutorials , but when i click login it always “login Faild ,Try again” , what should this error be Is it an error in the web service ??

  • Have you setup Dot Net webservice in your local machine and done all prerequisite settings to connect your App to Dot Net webservice as mentioned in the tutorial?

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