SlideShare a Scribd company logo
Md.Delwar Hossain
Made for Open IT
Using Database In Android
In this post we will develop an app in which a user can perform following task
1: User Can Create Account
2: User Can log in
we will use and learn following this in this Post
Customized Dialog: Here we have used Customized Dialog for User Login.
Creating DataBase: Here we have created database for Storing UserName and Password.
Writing functions for Inserting, Deleting, Updating and querying a Datbase
we have create a Table with following Fields :
USERNAME : to store the user name.
PASSWORD: to store the password of User
Table Name is LOGIN
List of XMLs Used.
main.xml : main screen
signup.xml : to create a new account
login.xml : to login
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_vertical" >
<Button
android:id="@+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign IN"
android:onClick="signIn"/>
<Button
android:id="@+id/buttonSignUP"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign UP" />
</LinearLayout>
signup.xml
<?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"
android:gravity="center_vertical" >
<EditText
android:id="@+id/editTextUserName"
android:hint="User Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
<EditText
android:id="@+id/editTextConfirmPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Confirm Password"
android:inputType="textPassword" />
<Button
android:id="@+id/buttonCreateAccount"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Create Account"
android:layout_marginBottom="60dp" />
</LinearLayout>
login.xml
<?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" >
<EditText
android:id="@+id/editTextUserNameToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPasswordToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="@+id/buttonSignIn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign In" />
</LinearLayout>
Activities:
1: HomeActivity.java
public class HomeActivity extends Activity
{
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create the instance of Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get The Reference OfButtons
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity abd Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
//Methods to handle Click Event of Sign In Button
public void signIn(View V)
{
final Dialog dialog = new Dialog(HomeActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the Refferences of views
final EditText
editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText
editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// get The User name and Password
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(HomeActivity.this, "Login Successfull",
Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(HomeActivity.this, "User Name and Does Not Matches",
Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
2: SignUpActivity.java
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword;
Button btnCreateAccount;
LoginDataBaseAdapter loginDataBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password Does Not Matches",
Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
Toast.makeText(getApplicationContext(), "Account Successfully Created ",
Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
}
3: DataBaseHelper.java
package com.example.login;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion +
", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
4: LoginDataBaseAdapter.java
public class LoginDataBaseAdapter
{
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME
text,PASSWORD text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
// Method to openthe Database
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
// Method to close the Database
public void close()
{
db.close();
}
// method returns an Instance of the Database
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
// method to insert a record in Table
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each column.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show();
}
// method to delete a Record of UserName
public int deleteEntry(String UserName)
{
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
Toast.makeText(context, "Number fo Entry Deleted Successfully :
"+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
// method to get the password of userName
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null,
null, null);
if(cursor.getCount()<1) // UserName Not Exist
return "NOT EXIST";
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
return password;
}
// Method to Update an Existing Record
public void updateEntry(String userName,String password)
{
// create object of ContentValues
ContentValues updatedValues = new ContentValues();
// Assign values for each Column.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}

More Related Content

PDF
Better Bullshit Driven Development [SeleniumCamp 2017]
DOCX
Android sql examples
PPTX
Mule esb – connecting to ms sql db
PPTX
Geb qa fest2017
PPTX
Roman iovlev. Test UI with JDI - Selenium camp
PDF
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
PDF
Electron: From Beginner to Pro
Better Bullshit Driven Development [SeleniumCamp 2017]
Android sql examples
Mule esb – connecting to ms sql db
Geb qa fest2017
Roman iovlev. Test UI with JDI - Selenium camp
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
Electron: From Beginner to Pro

What's hot (20)

PDF
Web 6 | JavaScript DOM
PPTX
Rails, Postgres, Angular, and Bootstrap: The Power Stack
PDF
Web 5 | JavaScript Events
DOC
Open microsoft visual studio/tutorialoutlet
PPT
Intorduction of Playframework
PPTX
18.register login
PDF
Introduction to Active Record - Silicon Valley Ruby Conference 2007
PDF
Android Testing
PDF
Idoc script beginner guide
PPT
JQuery New Evolution
PDF
Coffeescript a z
PPT
Database presentation
PPTX
Parsing in ios to create an app
PDF
Dojo1.0_Tutorials
PPT
Blocks In Drupal
TXT
Database connection instructions in net beans ide 7.1.2
DOCX
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
PDF
Building iPhone Web Apps using "classic" Domino
PPTX
jQuery Presentasion
Web 6 | JavaScript DOM
Rails, Postgres, Angular, and Bootstrap: The Power Stack
Web 5 | JavaScript Events
Open microsoft visual studio/tutorialoutlet
Intorduction of Playframework
18.register login
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Android Testing
Idoc script beginner guide
JQuery New Evolution
Coffeescript a z
Database presentation
Parsing in ios to create an app
Dojo1.0_Tutorials
Blocks In Drupal
Database connection instructions in net beans ide 7.1.2
Sec.1 กล ม 1 เร__องการสร_างแบบฟอร_มและการส_งค_าต_วแปร
Building iPhone Web Apps using "classic" Domino
jQuery Presentasion
Ad

Viewers also liked (11)

PDF
Hongkong : हांगकांग हॉलिडे में देखिये क्या और विकल्प हैं आपके पास
PPTX
Watch 2015 tsonga vs muller live tennis
PPTX
ACME presentation
PPT
Konflikt mizh ditmi_i_batkami
PPT
Top Reasons To Visit South Africa
PPT
DOC
19-07-06 Scheme Description details
PPTX
Blue Led: Key to modern energy efficient lighting
PPT
Series parallel ac networks
PPTX
Library Networks
PDF
Next-generation Python Big Data Tools, powered by Apache Arrow
Hongkong : हांगकांग हॉलिडे में देखिये क्या और विकल्प हैं आपके पास
Watch 2015 tsonga vs muller live tennis
ACME presentation
Konflikt mizh ditmi_i_batkami
Top Reasons To Visit South Africa
19-07-06 Scheme Description details
Blue Led: Key to modern energy efficient lighting
Series parallel ac networks
Library Networks
Next-generation Python Big Data Tools, powered by Apache Arrow
Ad

Similar to Using database in android (20)

PDF
Struts database access
DOC
Creating a Simple PHP and MySQL-Based Login System
DOCX
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
PDF
Php login system with admin features evolt
PDF
How to connect redis and mule esb using spring data redis module
PPS
Jdbc example program with access and MySql
DOC
Tutorial asp.net
DOCX
Week 12 code
PDF
Teste de Integração com DbUnit e jIntegrity
PDF
I am looking for some assistance with SQLite database. I have tried se.pdf
PDF
Play 2.0
PDF
Local data storage for mobile apps
PDF
Doctrine For Beginners
PDF
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
PPTX
Python Code Camp for Professionals 4/4
PDF
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
PPT
Developing Information Schema Plugins
PPTX
Python Code Camp for Professionals 3/4
PDF
Download full Distributed and Cloud Computing 1st Edition Hwang Solutions Man...
PDF
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Struts database access
Creating a Simple PHP and MySQL-Based Login System
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
Php login system with admin features evolt
How to connect redis and mule esb using spring data redis module
Jdbc example program with access and MySql
Tutorial asp.net
Week 12 code
Teste de Integração com DbUnit e jIntegrity
I am looking for some assistance with SQLite database. I have tried se.pdf
Play 2.0
Local data storage for mobile apps
Doctrine For Beginners
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Python Code Camp for Professionals 4/4
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
Developing Information Schema Plugins
Python Code Camp for Professionals 3/4
Download full Distributed and Cloud Computing 1st Edition Hwang Solutions Man...
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual

More from University of Potsdam (20)

PPTX
Computer fundamentals 01
PPTX
Workshop on android apps development
PDF
Transparency and concurrency
PDF
Database System Architecture
PDF
Functional dependency and normalization
PDF
indexing and hashing
PDF
data recovery-raid
PDF
Query processing
PDF
Machine Learning for Data Mining
PPTX
Tree, function and graph
PDF
Sets in discrete mathematics
PPT
Set in discrete mathematics
PPT
Series parallel ac rlc networks
PPT
PDF
PPT
Propositional logic
PDF
Propositional logic
PDF
Prim algorithm
PPT
Predicate &amp; quantifier
Computer fundamentals 01
Workshop on android apps development
Transparency and concurrency
Database System Architecture
Functional dependency and normalization
indexing and hashing
data recovery-raid
Query processing
Machine Learning for Data Mining
Tree, function and graph
Sets in discrete mathematics
Set in discrete mathematics
Series parallel ac rlc networks
Propositional logic
Propositional logic
Prim algorithm
Predicate &amp; quantifier

Recently uploaded (20)

PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PPTX
master seminar digital applications in india
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Cell Structure & Organelles in detailed.
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
01-Introduction-to-Information-Management.pdf
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
LDMMIA Reiki Yoga Finals Review Spring Summer
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Microbial diseases, their pathogenesis and prophylaxis
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Paper A Mock Exam 9_ Attempt review.pdf.
master seminar digital applications in india
Microbial disease of the cardiovascular and lymphatic systems
Cell Structure & Organelles in detailed.
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Computing-Curriculum for Schools in Ghana
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
01-Introduction-to-Information-Management.pdf
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Complications of Minimal Access Surgery at WLH
Supply Chain Operations Speaking Notes -ICLT Program
Final Presentation General Medicine 03-08-2024.pptx
Chinmaya Tiranga quiz Grand Finale.pdf

Using database in android

  • 1. Md.Delwar Hossain Made for Open IT Using Database In Android In this post we will develop an app in which a user can perform following task 1: User Can Create Account 2: User Can log in we will use and learn following this in this Post Customized Dialog: Here we have used Customized Dialog for User Login. Creating DataBase: Here we have created database for Storing UserName and Password. Writing functions for Inserting, Deleting, Updating and querying a Datbase we have create a Table with following Fields : USERNAME : to store the user name. PASSWORD: to store the password of User Table Name is LOGIN List of XMLs Used. main.xml : main screen signup.xml : to create a new account login.xml : to login main.xml
  • 2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_vertical" > <Button android:id="@+id/buttonSignIN" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Sign IN" android:onClick="signIn"/> <Button android:id="@+id/buttonSignUP" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Sign UP" /> </LinearLayout> signup.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
  • 3. android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_vertical" > <EditText android:id="@+id/editTextUserName" android:hint="User Name" android:layout_width="match_parent" android:layout_height="wrap_content" > <requestFocus /> </EditText> <EditText android:id="@+id/editTextPassword" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword" /> <EditText android:id="@+id/editTextConfirmPassword" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Confirm Password" android:inputType="textPassword" /> <Button android:id="@+id/buttonCreateAccount" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Create Account" android:layout_marginBottom="60dp" /> </LinearLayout> login.xml
  • 4. <?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" > <EditText android:id="@+id/editTextUserNameToLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="User Name" android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/editTextPasswordToLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPassword" android:hint="Password" /> <Button
  • 5. android:id="@+id/buttonSignIn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Sign In" /> </LinearLayout> Activities: 1: HomeActivity.java public class HomeActivity extends Activity { Button btnSignIn,btnSignUp; LoginDataBaseAdapter loginDataBaseAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // create the instance of Database loginDataBaseAdapter=new LoginDataBaseAdapter(this); loginDataBaseAdapter=loginDataBaseAdapter.open(); // Get The Reference OfButtons btnSignIn=(Button)findViewById(R.id.buttonSignIN); btnSignUp=(Button)findViewById(R.id.buttonSignUP); // Set OnClick Listener on SignUp button btnSignUp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub /// Create Intent for SignUpActivity abd Start The Activity Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class); startActivity(intentSignUP); } }); }
  • 6. //Methods to handle Click Event of Sign In Button public void signIn(View V) { final Dialog dialog = new Dialog(HomeActivity.this); dialog.setContentView(R.layout.login); dialog.setTitle("Login"); // get the Refferences of views final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin); final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin); Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn); // Set On ClickListener btnSignIn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub // get The User name and Password String userName=editTextUserName.getText().toString(); String password=editTextPassword.getText().toString(); // fetch the Password form database for respective user name String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName); // check if the Stored password matches with Password entered by user if(password.equals(storedPassword)) { Toast.makeText(HomeActivity.this, "Login Successfull", Toast.LENGTH_LONG).show(); dialog.dismiss(); } else { Toast.makeText(HomeActivity.this, "User Name and Does Not Matches", Toast.LENGTH_LONG).show(); } } }); dialog.show();
  • 7. } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); // Close The Database loginDataBaseAdapter.close(); } } 2: SignUpActivity.java public class SignUPActivity extends Activity { EditText editTextUserName,editTextPassword,editTextConfirmPassword; Button btnCreateAccount; LoginDataBaseAdapter loginDataBaseAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.signup); // get Instance of Database Adapter loginDataBaseAdapter=new LoginDataBaseAdapter(this); loginDataBaseAdapter=loginDataBaseAdapter.open(); // Get Refferences of Views editTextUserName=(EditText)findViewById(R.id.editTextUserName); editTextPassword=(EditText)findViewById(R.id.editTextPassword); editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword); btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount); btnCreateAccount.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub String userName=editTextUserName.getText().toString(); String password=editTextPassword.getText().toString(); String confirmPassword=editTextConfirmPassword.getText().toString();
  • 8. // check if any of the fields are vaccant if(userName.equals("")||password.equals("")||confirmPassword.equals("")) { Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show(); return; } // check if both password matches if(!password.equals(confirmPassword)) { Toast.makeText(getApplicationContext(), "Password Does Not Matches", Toast.LENGTH_LONG).show(); return; } else { // Save the Data in Database loginDataBaseAdapter.insertEntry(userName, password); Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show(); } } }); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); loginDataBaseAdapter.close(); } } 3: DataBaseHelper.java package com.example.login; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log;
  • 9. public class DataBaseHelper extends SQLiteOpenHelper { public DataBaseHelper(Context context, String name,CursorFactory factory, int version) { super(context, name, factory, version); } // Called when no database exists in disk and the helper class needs // to create a new one. @Override public void onCreate(SQLiteDatabase _db) { _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE); } // Called when there is a database version mismatch meaning that the version // of the database on disk needs to be upgraded to the current version. @Override public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) { // Log the version upgrade. Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data"); // Upgrade the existing database to conform to the new version. Multiple // previous versions can be handled by comparing _oldVersion and _newVersion // values. // The simplest case is to drop the old table and create a new one. _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE"); // Create a new one. onCreate(_db); } } 4: LoginDataBaseAdapter.java public class LoginDataBaseAdapter { static final String DATABASE_NAME = "login.db"; static final int DATABASE_VERSION = 1; public static final int NAME_COLUMN = 1; // TODO: Create public field for each column in your table. // SQL Statement to create a new database. static final String DATABASE_CREATE = "create table "+"LOGIN"+ "( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); "; // Variable to hold the database instance public SQLiteDatabase db;
  • 10. // Context of the application using the database. private final Context context; // Database open/upgrade helper private DataBaseHelper dbHelper; public LoginDataBaseAdapter(Context _context) { context = _context; dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION); } // Method to openthe Database public LoginDataBaseAdapter open() throws SQLException { db = dbHelper.getWritableDatabase(); return this; } // Method to close the Database public void close() { db.close(); } // method returns an Instance of the Database public SQLiteDatabase getDatabaseInstance() { return db; } // method to insert a record in Table public void insertEntry(String userName,String password) { ContentValues newValues = new ContentValues(); // Assign values for each column. newValues.put("USERNAME", userName); newValues.put("PASSWORD",password); // Insert the row into your table db.insert("LOGIN", null, newValues); Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show(); } // method to delete a Record of UserName public int deleteEntry(String UserName) { String where="USERNAME=?"; int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
  • 11. Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show(); return numberOFEntriesDeleted; } // method to get the password of userName public String getSinlgeEntry(String userName) { Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null); if(cursor.getCount()<1) // UserName Not Exist return "NOT EXIST"; cursor.moveToFirst(); String password= cursor.getString(cursor.getColumnIndex("PASSWORD")); return password; } // Method to Update an Existing Record public void updateEntry(String userName,String password) { // create object of ContentValues ContentValues updatedValues = new ContentValues(); // Assign values for each Column. updatedValues.put("USERNAME", userName); updatedValues.put("PASSWORD",password); String where="USERNAME = ?"; db.update("LOGIN",updatedValues, where, new String[]{userName}); } }