Monday, July 16, 2012

Android Login activity with MySQL database connection

Here I'm going to create a simple Android log in application  which can post data to a java web service and read data from MySQL database using a java web service to authenticate the user. Tested on Android 2.2.
(In latest versions of Android you cannot access the web in same way mentioned here. if you are planning implement web access for version 3.0 or higher than that follow one of below methods
1.Async Task
 http://codeoncloud.blogspot.com/2013/07/android-web-service-access-using-async.html
2.Handlers
http://codeoncloud.blogspot.com/2013/06/android-java-soap-web-service-access.html )

Quick demo :



The complete project has three main components

1. A MySQL database which holds user name and password.
2. A java web service deployed on Tomcat server.
3.Android application to access the database through the java web service to verify the user.

1. Databse
First we have to create a database and table to store user information. To create the database I used MySQL command line client. (If you like you can use phpmyadmin it is easier)
In order to create the database, a table and to populate the database run following queries.
a. Create the database
CREATE DATABSE androidlogin;
b. Select the database
USE androidlogin;
c. Create a table
CREATE TABLE user(
username VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL);
d.Populate the database
INSERT INTO user(username,password)
VALUES('admin','123');

2. Java webservice
Create the java web service in Eclipse. Follow the steps mentioned here. Additionally you have to import JDBC connector to the web service project.  
Here is the content for java web service.
package com.userlogin.ws;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Login {
 public String authentication(String userName,String password){
  
  String retrievedUserName = "";
  String retrievedPassword = "";
  String status = "";
  try{
   
   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin","root","chathura");
   PreparedStatement statement =  con.prepareStatement("SELECT * FROM user WHERE username = '"+userName+"'");
   ResultSet result = statement.executeQuery();
   
   while(result.next()){
    retrievedUserName = result.getString("username");
    retrievedPassword = result.getString("password");
    }
   
   if(retrievedUserName.equals(userName)&&retrievedPassword.equals(password)){
    status = "Success!";
   }
   
   else{
    status = "Login fail!!!";
   }
   
  }
  catch(Exception e){
   e.printStackTrace();
  }
  return status;
 
 }

}

> For more details read my first post.
> "root" and "chathura" in line 17 are user and the password of the database. You need to change those according to your settings.

3. Android application.
a. Code for main activity
package com.androidlogin.ws;

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.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidLoginExampleActivity extends Activity {
 private final String NAMESPACE = "http://ws.userlogin.com";
    private final String URL = "http://111.223.128.10:8085/AndroidLogin/services/Login?wsdl";
    private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
    private final String METHOD_NAME = "authentication";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button login = (Button) findViewById(R.id.btn_login);
        login.setOnClickListener(new View.OnClickListener() {
   
   public void onClick(View arg0) {
    loginAction();
    
   }
  });
    }
    
    private void loginAction(){
     SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
     
        EditText userName = (EditText) findViewById(R.id.tf_userName);
        String user_Name = userName.getText().toString();
        EditText userPassword = (EditText) findViewById(R.id.tf_password);
        String user_Password = userPassword.getText().toString();
        
      //Pass value for userName variable of the web service
        PropertyInfo unameProp =new PropertyInfo();
        unameProp.setName("userName");//Define the variable name in the web service method
        unameProp.setValue(user_Name);//set value for userName variable
        unameProp.setType(String.class);//Define the type of the variable
        request.addProperty(unameProp);//Pass properties to the variable
       
      //Pass value for Password variable of the web service
        PropertyInfo passwordProp =new PropertyInfo();
        passwordProp.setName("password");
        passwordProp.setValue(user_Password);
        passwordProp.setType(String.class);
        request.addProperty(passwordProp);
          
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        
        try{
            androidHttpTransport.call(SOAP_ACTION, envelope);
               SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
                
               TextView result = (TextView) findViewById(R.id.tv_status);
               result.setText(response.toString());
          
        }
        catch(Exception e){
          
        }
       }
    
}

> You need to import ksoap2 library for the Android project.
> You cannot access the URL in above code because the web service is deployed in Tomcat server installed in my computer not in a cloud server therefore you have to replace that with an URL for your own web service. 
>  For more details check these posts.
 1. Post 1
 2. Post 2

b. Content of main.xml


    

        
    

    



    

    


    

c. You need to add internet permission to the project
Manifest.xml


    
    

    
        
            
                

                
            
        
    



You can download Android project here
(After downloading the project first remove imported ksoap2 library from the project and re import ksoap2 from your hard disk )

Please post your ideas :)

58 comments:

  1. Pretty nice post. I simply stumbled upon your weblog and wished to mention that I have
    really loved surfing around your blog posts. In any case I will be subscribing on your
    feed and I hope you write again very soon!
    Have a look at my webpage ... Yoga Angebote

    ReplyDelete
  2. Hi there, great example using a Java web service but is this functionality available with my PHP/PostGreSQL server space as well?

    ReplyDelete
    Replies
    1. Hi,
      I'm sorry I have no idea about that.

      Delete
    2. Hi Chathura sir, How to implement this same code(http://codeoncloud.blogspot.in/2012/07/android-login-activity-with-mysql.html) by using PhoneGap android.. Please help me about this.. Thanks in andvance

      Delete
  3. Eхcellеnt blοg you hаve herе.

    . ӏt's difficult to find quality writing like yours nowadays. I really appreciate individuals like you! Take care!!
    Also visit my weblog ... agencja reklamowa

    ReplyDelete
  4. Yes! Finally someone writes about free.[url=http://fish4payday.co.uk]payday loans[/url]

    payday loans
    my web site - payday loans

    ReplyDelete
  5. You maԁe some dесеnt points thегe.
    I checked on the internet to learn morе about the isѕue anԁ fοunԁ most people
    ωill go along with youг viеws
    оn this site.
    Feel free to visit my blog post agencja reklamowa

    ReplyDelete
  6. It's an example of how it is done in Android versions 3.0 or 4.0 as this method superior to android ics jb displays an error and must be worked asyncrono

    ReplyDelete
  7. It's an example of how it is done in Android versions 3.0 or 4.0 as this method superior to android ics jb displays an error and must be worked asyncrono

    ReplyDelete
  8. Everyone loves it whenever people get together and share ideas.
    Great site, keep it up!
    My web page : Francisco

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. I have to developed android login with mysql database connection using soap webservices.

    its successfully worked my (localhost/phpmyadmin)

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin","root","");

    But it is ot worked on my dev site: (dev.mmmm.com/phpmyadmin)

    Connection con = DriverManager.getConnection("jdbc:mysql://dev.mmmm.com:3306/login","mm2","mm5");


    i have used above code means am getting following error.please give me how can i resolve this error.

    http://pastie.org/5118624

    Please give me solution for this.

    ReplyDelete
    Replies
    1. Please show a little bit of effort at least. Can you forward the code?

      Delete
  11. I have to developed android login with mysql database connection using soap webservices.

    its successfully worked my (localhost/phpmyadmin)

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin","root","");

    But it is ot worked on my dev site: (dev.mmmm.com/phpmyadmin)

    Connection con = DriverManager.getConnection("jdbc:mysql://dev.mmmm.com:3306/login","mm2","mm5");


    i have used above code means am getting following error.please give me how can i resolve this error.

    http://pastie.org/5118624

    Please give me solution for this.

    ReplyDelete
  12. Adserve.ro este un sistem de reclama online pay per click.


    Publicati reclamele dvs unei comunitati mari folosind Adserve.
    ro Cont de advertiser.
    Faceti publicitate cu anunţuri text şi banner orientate
    spre publicul de nişă, cu un control complet cu privire la
    rata de click şi buget.
    Prezentarea unui sistem eficient de cost de publicitate în care trebuie să plătiţi doar pentru clicuri legitime pe anunţurile dvs.
    .

    Adserve.ro Cont publisher pentru webmasteri/detinatori siteuri.

    Castigati imediat bani cu siteul sau blogul dvs prin Adserve.

    ro Cont Publisher.
    Crearea de unităţi elegante şi moderne de afişare anunţuri/bannere care se potrivesc desigului
    site-ului sau blog-ului dvs.
    Afisati pe siteul dvs reclame legate de continutul siteului pentru a castiga din clickurile trimise de pe siteul dvs.
    Here is my website : advertiser

    ReplyDelete
  13. bookmarked!!, I love your blog!
    Also visit my webpage ... semenax review men's health

    ReplyDelete
  14. I'm not sure exactly why but this website is loading extremely slow for me. Is anyone else having this issue or is it a problem on my end? I'll check back later on and see if the problem still
    exists.
    My web site ; Topratedgreencoffee.com

    ReplyDelete
  15. I m getting the massage unexpectedly closed in my emulator....using apache 6.0, api version 8(froyo 2.2).

    ReplyDelete
  16. I m getting the massage unexpectedly closed in my emulator when i m running it as android application....The previous step where i have to create web service gone smoothly....using apache 6.0, api version 8(froyo 2.2). I did exactly as you told. I even kept the same package & project names as described above code. And yeah i changed my URL as instructed..Plz help....I need it badly...

    ReplyDelete
  17. Hi,
    I don't see the app in my emulator, there's no icon for it. Running it I get the message there is no launch activity. How can I solve this problem? Is there a correlation in getting this error and the missing icon in the emulator? In the "manage apps" section of the emulator (Samsung S2 Android 4.0) there is an entry com.androidlogin.ws listed with 88kb of size.

    Please help :-)

    Greetings from Germany

    ReplyDelete
  18. I'm getting the message

    D/SntpClient( 59): request time failed: java.net.SocketException: Address fami
    ly not supported by protocol

    What can I do? What did I do wrong?

    ReplyDelete
  19. How can I do it with RESTFUL?

    ReplyDelete
  20. I am getting this error 12-17 15:16:34.968: W/System.err(356): java.net.ConnectException: localhost/127.0.0.1:8282 - Connection refused

    ReplyDelete
    Replies
    1. Did you have the web service running in the same PC?

      Delete
    2. Did you have the web service and the andriod application running in different PCs?

      Delete
  21. unfortunately, Android Login Example has stopped message only coming for me when ever I click the login button..
    please help thanks in advance...

    ReplyDelete
    Replies
    1. The solution is in this post. Please let us know if it works for you.

      http://codeoncloud.blogspot.com/2013/06/could-not-find-class.html

      Delete
  22. unfortunately Android Login Example has been stopped message only coming when ever I click the login button.....please help me...

    ReplyDelete
  23. where do i import jdbc connector

    ReplyDelete
  24. what are the steps for running web service and android program.

    ReplyDelete
  25. my android application is throwing ClassDefNotFoundException ,and not being able to connect to the webservice

    ReplyDelete
  26. hi .. i try to this program but database is displayed in Access denied. pls help me.. my concept is connect to the android with mysql using php in wamp server..

    ReplyDelete
  27. I am also having the same issue as iyappan jaya has.If i click on the Login button i dont see any message on the screen.I am using android 4.2 api 17.

    ReplyDelete
  28. I am also having the same issue as iyappan jaya has.If i click on the Login button i dont see any message on the screen.I am using android 4.2 api 17.

    ReplyDelete
  29. how to connect PHP with mysql in android?

    ReplyDelete
  30. Thanks for the tutorial..........

    How can I send or Add data to MySql database from my Android application?Please help me out in that aspect too

    ReplyDelete
  31. Thanks for the tutorial...

    How can I add data to MySql database from my android application?
    Can you please help me out in that aspect

    Thanks in advance

    ReplyDelete
  32. SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
    is returning null value,So that NullPointerException is occuribg in My Program Pls help me.

    ReplyDelete
  33. Hi Im new to android and right now working with listview, i need a sample code for onitemclick in listview must go to a webpage thanks

    ReplyDelete
  34. Hi Chathura sir, How to implement this same code(http://codeoncloud.blogspot.in/2012/07/android-login-activity-with-mysql.html) by using PhoneGap android.. Please help me about this.. Thanks in andvance

    ReplyDelete
  35. it does not work for me.....

    debug did not go to try method

    ReplyDelete
  36. it does not works for me... error in try method

    ReplyDelete
  37. if possible to access the mysql database without using any scripting language and web services in android..???

    ReplyDelete
  38. hello sir..
    this is nice one ..and how to fetch the data from the database and how it get the fetching value in android client application

    ReplyDelete
  39. how can i get list object from web service response any tutorial.

    ReplyDelete
  40. how can i get list or arraylist object from web service response

    ReplyDelete
  41. This is realy very good website i found my serach here for android

    ReplyDelete
  42. Hello Friend I am a new developer for android gaming field, how should i start my training by myself to learn in better flow get trained

    ReplyDelete
  43. Hey,your tutorial is amazing. i have created it sucessfully but only problem is that how to fetch the data and show it in listview ...just tell me that logic.i have tried lot with soapobject & soapprimitive...but fail.
    this will be your great help to me.

    ReplyDelete
  44. Thanks for this post...but i want some more. i want to show list-view which should be return from web-service & show into listview in android. i have try lot with SoapObject but fail every-time. have u knowledge about this.Thanks in advance.

    ReplyDelete
  45. Hi ,

    I found your tutorial very impressive . Albeit i have one query

    1 - What is the significant of NAME_SPACE and SOAP_ACTION

    Please explain me .

    ReplyDelete
  46. hey i have create the web service as per your tutorial. However, i am getting soapAction = "urn:authentication" . which create a nullPointerException in androidHttpTransport.call(SOAP_ACTION,envelope); please help me its very urgent and i need to do it anyhow. How tell me how to find the soapAction.

    ReplyDelete
  47. Please tell me how to find the soapAction.I followed your tutorial and create a wsdl file. In wsdl file i can see the soapAction="urn:authentication". However i am getting an error in androidHttpTransport.call(SOAP_ACTION,envelope); SOAP_ACTION = "urn:authentication" in my code and it is creating problem i have find it while doing debugging.Please help me to solve this issue . It's very important to me.

    ReplyDelete
  48. 09-28 00:46:05.523: E/AndroidRuntime(19920): FATAL EXCEPTION: main
    09-28 00:46:05.523: E/AndroidRuntime(19920): java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
    09-28 00:46:05.523: E/AndroidRuntime(19920): at com.androidlogin.ws.AndroidLoginExampleActivity.loginAction(AndroidLoginExampleActivity.java:37)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at com.androidlogin.ws.AndroidLoginExampleActivity.access$0(AndroidLoginExampleActivity.java:36)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at com.androidlogin.ws.AndroidLoginExampleActivity$1.onClick(AndroidLoginExampleActivity.java:30)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at android.view.View.performClick(View.java:4401)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at android.view.View$PerformClick.run(View.java:18184)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at android.os.Handler.handleCallback(Handler.java:730)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at android.os.Handler.dispatchMessage(Handler.java:92)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at android.os.Looper.loop(Looper.java:150)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at android.app.ActivityThread.main(ActivityThread.java:5390)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at java.lang.reflect.Method.invokeNative(Native Method)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at java.lang.reflect.Method.invoke(Method.java:525)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    09-28 00:46:05.523: E/AndroidRuntime(19920): at dalvik.system.NativeStart.main(Native Method)
    09-28 00:46:07.833: I/Process(19920): Sending signal. PID: 19920 SIG: 9

    sir, I am getting this these error can you plz help me to find what is the problem

    ReplyDelete
  49. can u provide ur personal email id.

    ReplyDelete
  50. i am trying your codes and i got right results.

    My Dealersocket Login

    ReplyDelete