Sunteți pe pagina 1din 7

You know you can create Android Color XMLs eortlessly Click Here to know more

Home Basics Write For Us Advertise With Us Demo Videos Other Tutorials About Us Contact Us

Donate

Home Web Service Android Dot Net Web Service Login

Android Dot Net Web Service Login


Posted By Android Guru on Dec 29, 2013 | 14 comments
In this post, I am going to discuss about how to authenticate
Users in Android application using Dot Net Web service.The
Shares
application which I am gonna create will have two screens
Login screen and Home screen.
Donate us as little as
User has to type his/her credentials and click Login button. Once
Rs.10(Indian Rupees) to continue
Login button is clicked, application res call to Dot Net web
to serve you.
service along with Username and Password typed by User. Our
Activity waits for response from the web service, once it receives
Payment gateway is enabled
response, it decides whether to take User to next screen(Home)
and available only for readers
or show Login Failed message based on the response.
from India right now.
Here is the graphical representation of whatever we discussed:

Search this website

CustomSearch

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, dont 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:
Categories
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.
Categories
2. Make sure you turned o Firewall in your local machine since FireWall will not allow the local machine to
SelectCategory
accept Http calls from other machines or servers
You know you can create Android Color XMLs eortlessly Clickfrom
KSOAP client library is being used in Android to make WebService calls. You can download KSOAP library Here to know more Follow Us

here and add it in lib folder of Android project

Follows

[pgsubscribe]

As this application requires Internet connectivity to hit Web Service hosted in remote server, we need to check if Facebook Google+
Internet connectivity is available or not. 18.1k 1.2k
Followers Followers
Here are the tutorials which talk about checking Wi /Mobile Internet:

Android Check Wi-Fi Internet Connection Twitter Pinterest

Android Check Mobile Internet Connection 339 44


Followers Followers

Quick Links
RSS YouTube
Project Structure 23k 344
Followers Followers
Code Listings
Demo
Download Source Code Recent Popular Random

Shares Mobile Apps Stats and


Trends
Apr 1, 2016

Android Studio Useful


Shortcuts
Mar 27, 2016

4 Low-Code Developer
Tools You Cant Ignore
Mar 23, 2016

How to Make Irresistible


Android Game Trailers?
Project Structure Mar 23, 2016

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 nish

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:
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns: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"
You know you can create Android Color XMLs eortlessly
android:layout_gravity="center_horizontal" Click Here to know more
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 con guration

Login Screen
Shares

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
packagecom.prgguru.example

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

publicclassCheckDNLoginActivityextendsActivity{
//SetErrorStatus
staticbooleanerrored=false
Buttonb
TextViewstatusTV
EditTextuserNameET,passWordET
ProgressBarwebservicePG
StringeditTextUsername
booleanloginStatus
StringeditTextPassword
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
//NameTextcontrol
userNameET=(EditText)findViewById(R.id.editText1)
passWordET=(EditText)findViewById(R.id.editText2)
//DisplayTextcontrol
statusTV=(TextView)findViewById(R.id.tv_result)
//Buttontotriggerwebserviceinvocation
b=(Button)findViewById(R.id.button1)
//Displayprogressbaruntilwebserviceinvocationcompletes
webservicePG=(ProgressBar)findViewById(R.id.progressBar1)
//ButtonClickListener
b.setOnClickListener(newOnClickListener(){
publicvoidonClick(Viewv){
//Checkiftextcontrolsarenotempty
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("")
//CreateinstanceforAsyncCallWS
AsyncCallWStask=newAsyncCallWS()
//Callexecute
task.execute()
}
//IfPasswordtextcontrolisempty
else{
statusTV.setText("PleaseenterPassword")
}
//IfUsernametextcontrolisempty
}else{
statusTV.setText("PleaseenterUsername")
}
}
})
}

privateclassAsyncCallWSextendsAsyncTask{
@Override
protectedVoiddoInBackground(String...params){
//CallWebMethod
loginStatus=WebService.invokeLoginWS(editTextUsername,editTextPassword,"AuthenticateUser")
returnnull
}
You know you can create Android Color XMLs eortlessly
@Override Click Here to know more
//OnceWebServicereturnsresponse
protectedvoidonPostExecute(Voidresult){
//MakeProgressBarinvisible
webservicePG.setVisibility(View.INVISIBLE)
IntentintObj=newIntent(CheckDNLoginActivity.this,HomeActivity.class)
//Errorstatusisfalse
if(!errored){
//BasedonBooleanvaluereturnedfromWebService
if(loginStatus){
//NavigatetoHomeScreen
startActivity(intObj)
}else{
//SetErrormessage
statusTV.setText("LoginFailed,tryagain")
}
//Errorstatusistrue
}else{
statusTV.setText("Erroroccuredininvokingwebservice")
}
//ReinitializeErrorStatustoFalse
errored=false
}

@Override
//MakeProgressBarvisible
protectedvoidonPreExecute(){
webservicePG.setVisibility(View.VISIBLE)
}

@Override
protectedvoidonProgressUpdate(Void...values){
}
Shares }
}

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:
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns: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="Welcomeadmin"
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.


packagecom.prgguru.android
importandroid.app.Activity
importandroid.os.Bundle
publicclassHomeActivityextendsActivity{
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState)
setContentView(R.layout.login)
}
}

WebService Con guration

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
packagecom.prgguru.example

importorg.ksoap2.SoapEnvelope
importorg.ksoap2.serialization.PropertyInfo
importorg.ksoap2.serialization.SoapObject
importorg.ksoap2.serialization.SoapPrimitive
importorg.ksoap2.serialization.SoapSerializationEnvelope
importorg.ksoap2.transport.HttpTransportSE
You know you can create Android Color XMLs eortlessly Click Here to know more
publicclassWebService{
//NamespaceoftheWebservicecanbefoundinWSDL
privatestaticStringNAMESPACE="http://tempuri.org/"
//WebserviceURLWSDLFilelocation
privatestaticStringURL="http://192.168.2.5/LoginCheck/Service.asmx"//MakesureyouchangedIPaddress
//SOAPActionURIagainNamespace+Webmethodname
privatestaticStringSOAP_ACTION="http://tempuri.org/"

publicstaticbooleaninvokeLoginWS(StringuserName,StringpassWord,StringwebMethName){
booleanloginStatus=false
//Createrequest
SoapObjectrequest=newSoapObject(NAMESPACE,webMethName)
//Propertywhichholdsinputparameters
PropertyInfounamePI=newPropertyInfo()
PropertyInfopassPI=newPropertyInfo()
//SetUsername
unamePI.setName("username")
//SetValue
unamePI.setValue(userName)
//SetdataType
unamePI.setType(String.class)
//Addthepropertytorequestobject
request.addProperty(unamePI)
//SetPassword
passPI.setName("password")
//SetdataType
passPI.setValue(passWord)
//SetdataType
passPI.setType(String.class)
//Addthepropertytorequestobject
request.addProperty(passPI)
//Createenvelope
Shares SoapSerializationEnvelopeenvelope=newSoapSerializationEnvelope(
SoapEnvelope.VER11)
envelope.dotNet=true
//SetoutputSOAPobject
envelope.setOutputSoapObject(request)
//CreateHTTPcallobject
HttpTransportSEandroidHttpTransport=newHttpTransportSE(URL)
try{
//Invokewebservice
androidHttpTransport.call(SOAP_ACTION+webMethName,envelope)
//Gettheresponse
SoapPrimitiveresponse=(SoapPrimitive)envelope.getResponse()
//Assignittobooleanvariablevariable
loginStatus=Boolean.parseBoolean(response.toString())
}catch(Exceptione){
//AssignErrorStatustrueinstaticvariable'errored'
CheckDNLoginActivity.errored=true
e.printStackTrace()
}
//Returnbooleamtocallingobject
returnloginStatus
}
}

Internet permission

Dont forget to add internet permission in AndroidManifest.xml:


<usespermissionandroid: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:

Previous Next
Download Source CodeYou know you can create Android Color XMLs eortlessly Click Here to know more

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 dont want to hit your head
with source code, download application(apk) le and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation le 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]

Shares

Related Articles

Author: Android Guru

Share This Post On

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 de ne 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?
Android Guru
Response is SOAP response sent by Dot net web service.
Android Guru
Youdeployed
Have you created dot net web service and know youit incan
IIS create
server?Android Color
If not please doXMLs eortlessly
the same. Click Here to know more

raju
I trying with urCODE that u put here.. .. but the progress bar rotating onlyi coUdnt get any out put.i also tried with ma o ice
server..Then the same thing has happend.so please help mee.
my work completely depends up on this
Android Guru
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 x the issue accordingly.

Let me know once you resolve the issue.


md ishtiyaque
I am also face same problem and i dont 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 ??
Android Guru
Have you setup Dot Net webservice in your local machine and done all prerequisite settings to connect your App to Dot Net
webservice
Shares as mentioned in the tutorial?
Thair Jaber
yes i did , but now iv installed the source code from here and its running , but the app which iv created it still not running unless it
is the same code and there is no di erence between yours and mine , what wrong ??
Android Guru
I just uploaded webservice code, take a look at it, it may help you:

http://programmerguru.com/android-tutorial/wp-content/uploads/2013/12/LoginCheck.zip
Thair Jaber
yes i have , thanks now its running ,it was a small mistake
Android Guru
Great.

Tags Recent Posts Android Color Generator About Me

Action Bar Activity AJAX android Welcome to


Mobile Apps Stats and Trends ProgrammerGuruTutorial Blog.
apps development Android April 1, 2016
Let me introduce myself more
Basics android development
formally,
Im a normal guy, engineer by
company androidversions Android Wear
Android Studio Useful education who is passionate
Application AQuery AsyncTask about Programming and
Authentication Broadcast receivers Button Shortcuts March 27, 2016 Internet.
Call Camera Dot Net Web Service Here I am writing lot about
Eclipse Email Facebook Gallery jQuery, AJAX, Android and
GCM Image Image_Upload Intent 4 Low-Code Developer Tools JSON. Want to join with me in
Java Web Service jQuery jQuery Mobile the journey of learning
You Cant Ignore March 23, aforementioned technology?
JSON Layout Library
2016 You are in the right place then :)
Localization Media Noti cations php
Keep me posted with your
Restful webservice SD Card Seek bar valuable feedback and
SQLite Text to speech Vibrate Video web comments.
Web service Webview Happy learning

Applications AQuery Basics Facebook GCM JSON Layout Localization Media SQLite Toast Web Service

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 !!

Email

SUBSCRIBE!

You have Successfully Subscribed!

S-ar putea să vă placă și