Android

8
Android Database for Login User Authentication Using SQLite After struggling in creating and accessing an Sqlite database which authenticates users login details based on the database details, I needed to document this for future purposes and also to share it with other Android developers. For a large scale login authentication, chances are you shall use a web server to store user details, but SQLite is a good start for testing small prototypes and running demonstrations. It is assumed that you have your IDE (I use Eclipse) and all your Android setups up and running and you can write Java and Activity codes. You shall need the SQLite Browser which is open source so you can download it from http://www.sqlite.org/ 1. Creating User Database and Login Screen a. In Eclipse, create a new Project naming it appropriately. We shall create two classes under this project : DBAdapter.java and Login.java b. Right Clicking on your project name in ‘Project Explorer’, Click New then Class. Name this class as DBAdapter. c. Import the following packages import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.*; d. Declare the following: private static final String DATABASE_NAME = "Your database name"; //Declare your database here and give it an appropriate name. private static final int DATABASE_VERSION = 20; // This is not important so you can leave it as is. private static final String DATABASE_CREATE_USERS = "create table TABLE_NAME (UserID integer primary key autoincrement, " + "Username text, Password text);";

Transcript of Android

Page 1: Android

Android Database for Login User Authentication Using SQLite

After struggling in creating and accessing an Sqlite database which authenticates users login details based on the database details, I needed to document this for future purposes and also to share it with other Android developers.

For a large scale login authentication, chances are you shall use a web server to store user details, but SQLite is a good start for testing small prototypes and running demonstrations.

It is assumed that you have your IDE (I use Eclipse) and all your Android setups up and running and you can write Java and Activity codes. You shall need the SQLite Browser which is open source so you can download it from http://www.sqlite.org/

1. Creating User Database and Login Screen

a. In Eclipse, create a new Project naming it appropriately.We shall create two classes under this project : DBAdapter.java and Login.java

b. Right Clicking on your project name in ‘Project Explorer’, Click New then Class. Name this class as DBAdapter.

c. Import the following packages

import android.content.Context;import android.database.Cursor;import android.database.SQLException;import android.database.sqlite.*;

d. Declare the following: private static final String DATABASE_NAME = "Your database

name"; //Declare your database here and give it an appropriate name. private static final int DATABASE_VERSION = 20; // This is not

important so you can leave it as is. private static final String DATABASE_CREATE_USERS = "create

table TABLE_NAME (UserID integer primary key autoincrement, "

+ "Username text, Password text);";

//Give an appropriate table name.//I found that if you create the table in your code like this, after the first time //the code runs successfully, you can comment this line as the table is only //created once.

private static final String DATABASE_SELECT_USERS="users";public static final String USER_ID = "UserID";public static final String USER_NAME = "Username";public static final String USER_PASSWORD = "Password ";

// Note that my string values on the right match what I used in my table //creation so yours need to match too.//We shall use this block of code to select users from the table.

private final Context context;

Page 2: Android

private DatabaseHelper DBHelper;private SQLiteDatabase db;

//We shall need these objects

e. Create a constructor for the DBAdapter class, and parameterize it with an object ctx of type Context. Declare the following within the constructor

this.context = ctx;DBHelper = new DatabaseHelper(context);

f. Since we have declared a non-inbuilt class ‘DatabaseHelper’ above, we have to create it. This class extends SQLiteOpenHelper class as it is the one in which we shall create nd upgrade our database.

g. private static class DatabaseHelper extends SQLiteOpenHelper{

DatabaseHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}

public void onCreate(SQLiteDatabase db) {

System.out.println("Creating table");

db.execSQL(DATABASE_CREATE_USERS);

//I commented this line after my initial run since //I wanted to add users using SQLite Browser and the //table need only be created once.

}

public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

// This is an empty method for my case since I//am addind users directly using SQLite.//But it must be declared here since we are InheritingSQLiteOpenHelper and must override all its methods.

}}

h. Open the database

public DBAdapter open() throws SQLException {

db = DBHelper.getWritableDatabase();return this;

}

i. Close the database

public void close() {

DBHelper.close();}

Page 3: Android

j. Method for getting user from the database. We shall use this method in the Login class.

public Cursor fetchUser(String username, String password) {

Cursor myCursor = db.query(DATABASE_SELECT_USERS, new String[] { USER_ID, USER_NAME, USER_PASSWORD }, USER_NAME + "='" + username + "' AND " + USER_PASSWORD + "='" + password + "'", null,

null, null, null); if (myCursor != null) { myCursor.moveToFirst(); } return myCursor; }

k. Method for inserting user. I shall use this once in the Login class and then I shall comment it after my first run so that I can add the rest of the users via the SQLite browser. If you wish to insert your users using a separate Java class, you can call this method therein.

public void InsertData(String username, String password){

String sql="INSERT INTO users (Username,Password) VALUES('"+username+"','"+password+"')";

db.execSQL(sql);}

l. Create the Login Class as an Activity. Design your Login form in your main.xml file as desired and assign id variables to your ID and PWD Edit Text fields and also your ‘Login’ button. We shall use an inner class in implementing our Button Listener.

m. Below is my Login Activitiy class codes with comments to show the most important parts.

package LoginProject.chao;

import android.app.Activity;import android.content.Intent;import android.database.*;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.*;import android.widget.*;

public class Login extends Activity { public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

final EditText txt_username = (EditText) findViewById(R.id.editText1);

Page 4: Android

final EditText txt_psw = (EditText) findViewById(R.id.editText2);

Button btn_signin=(Button) findViewById(R.id.button1);

//Inner class to implement Button Listener when button is clicked.

btn_signin.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

DBAdapter db= new DBAdapter(getBaseContext()); db.open(); //Comment the line below after your first run. //Otherwise you shall have multiple users with this user

detail // I add more users via the SQLite Browser //If you wish to insert users in a separate Java file,

you call call //the InsertData method from there like this. db.InsertData("Chao", "1234"); //Use the line below if you want to see a log of the user

details //under LogCat in Eclipse. Log.v("LoginDetails", txt_username.getText().toString()

+"../.."+txt_psw.getText().toString()); //Accessing user using the fetchUser method we created in

DBAdapter Cursor cur =

db.fetchUser( txt_username.getText().toString() , txt_psw.getText().toString());

//Use this line if you want to see the number of users

with these login details System.out.println("cur.getCount() "+cur.getCount());

if(cur.getCount()!=0) { String usn=cur.getString(1); if(usn.equals("Chao")) { }else{ } System.out.println("Query succedded"); Toast.makeText(getBaseContext(), "Success! Valid

User name and password", Toast.LENGTH_LONG).show(); db.close(); } else Toast.makeText(getBaseContext(), "Please enter Valid

User name and password", Toast.LENGTH_LONG).show(); } //Closes the onClick method

}//Closes the inner class ); //Closes the onClickListener

Page 5: Android

}}

All those compiled should run successfully and the user ‘Chao’ with Password ‘1234’ Should successfully login. Try using a different password and you should get the error Toast.

If you want to add users via code then you can create a separate class in the same project to do that. Below I show how to add users using SQLite browser.

2. Accessing and Modifying Database for more Users

a. You should have downloaded SQLite.b. In Eclipse Access the database you created above using the following steps

Page 6: Android

Window menu – Show View – File Explorer (If File explorer does not display click on Other and type it.

File explorer shall be displayed on the right of your Eclipse window. Open the folders in File Explorer in this order data-data – Your project Name – databases – You should see your database here (Click on it)

At the top of the File Explorer you shall see ‘Pull a file from device’ and ‘Push file onto Device’. Click on ‘Pull a file from device’ and it shall require you to save the database file in your desired folder. Remember this location. Leave your File Explorer open.

c. Open SQLite and Open file and then locate your database where you had saved it.d. In SQLite, click on ‘Browse Data’ and then choose your table from ‘Table’. You

should be able to see ‘Chao’ entry, depending on how many times you run the code with that insert query.

e. Click on ‘new record’ and double click ‘username’ and type in the new username and click on ‘Apply Changes’. Do the same for password.

f. Click on Save Changes to Database file at the top of SQLite menu tabs.g. Go back to Eclipse to your File explorer. Click on your database as below, now at the

top of File Explorer choose, ‘Push file onto Device’ and double click on the new saved version of your database from above. This will now store your database file with the new users in your data folder.

h. Rerun your project…. And enjoy the feeling of seeing the new users successfully logged in.

*** A useful next step would be to implement opening of a new Window (Using Intents) when a user is successfully logged in.