Android Login with MySQL Database

Posted: 29/03/2013 in Android

 

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)

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

1
CREATE DATABSE androidlogin;

b. Select the database

1
USE androidlogin;

c. Create a table

1
2
3
CREATE TABLE user(
username VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL);

d.Populate the database

1
2
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<absolutelayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
 
    <edittext android:id="@+id/tf_userName" android:layout_height="wrap_content" android:layout_width="194dp" android:layout_x="106dp" android:layout_y="80dp">
 
        <requestfocus>
    </requestfocus></edittext>
 
    <textview android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_x="23dp" android:layout_y="93dp" android:text="User name">
 
 
 
    <edittext android:id="@+id/tf_password" android:inputtype="textPassword" android:layout_height="wrap_content" android:layout_width="189dp" android:layout_x="108dp" android:layout_y="161dp">
 
    <textview android:id="@+id/TextView01" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_x="23dp" android:layout_y="176dp" android:text="Password">
 
 
    <button android:id="@+id/btn_login" android:layout_height="wrap_content" android:layout_width="106dp" android:layout_x="175dp" android:layout_y="273dp" android:text="Login">
 
    <textview android:id="@+id/tv_status" android:layout_height="38dp" android:layout_width="151dp" android:layout_x="26dp" android:layout_y="234dp" android:textappearance="?android:attr/textAppearanceMedium">
 
 
</textview></button></textview></edittext></textview></absolutelayout>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<manifest android:versioncode="1" android:versionname="1.0" package="com.androidlogin.ws" xmlns:android="http://schemas.android.com/apk/res/android">
 
    <uses-sdk android:minsdkversion="8">
    <uses-permission android:name="android.permission.INTERNET">
 
    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:label="@string/app_name" android:name=".AndroidLoginExampleActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">
 
                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
    </application>
 
</uses-permission></uses-sdk></manifest>

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 ) 

Advertisements

Trả lời

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Đăng xuất / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất / Thay đổi )

Connecting to %s