Professional Documents
Culture Documents
AndroidSQLiteDatabaseTutorial
Downloads
HOME
DATABASE
Tips
Write for Us
SEARCH HERE
WERE SOCIAL
AndroidHive
38,494likes
LikePage
Bethefirstofyourfriendstolikethis
Subscribe to
Newsletter
Join our 746,498
subscribers and get
access to the latest
android tutorials,
freebies, scripts and
much more!
1/20
7/12/2016
AndroidSQLiteDatabaseTutorial
Sign Up
We strictly care about
your privacy!
POPULAR ANDROID
TUTORIALS
1.
Contact.java
packagecom.androidhive.androidsqlite;
publicclassContact{
//privatevariables
int_id;
String_name;
String_phone_number;
//Emptyconstructor
publicContact(){
}
//constructor
publicContact(intid,Stringname,String_phone_number){
this._id=id;
this._name=name;
this._phone_number=_phone_number;
}
//constructor
publicContact(Stringname,String_phone_number){
this._name=name;
this._phone_number=_phone_number;
}
//gettingID
publicintgetID(){
returnthis._id;
}
//settingid
publicvoidsetID(intid){
this._id=id;
}
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
Android SQLite
How to connect
Android Push
Notications using
Google Cloud Messaging
(GCM), PHP and MySQL 1,195,980 views
5.
Android Custom
7/12/2016
AndroidSQLiteDatabaseTutorial
//gettingname
publicStringgetName(){
returnthis._name;
}
//settingname
publicvoidsetName(Stringname){
this._name=name;
}
//gettingphonenumber
publicStringgetPhoneNumber(){
returnthis._phone_number;
}
//settingphonenumber
publicvoidsetPhoneNumber(Stringphone_number){
this._phone_number=phone_number;
}
}
Android GPS,
Location Manager
Android working
publicclassDatabaseHandlerextendsSQLiteOpenHelper{
3/20
7/12/2016
AndroidSQLiteDatabaseTutorial
publicclassDatabaseHandlerextendsSQLiteOpenHelper{
//AllStaticvariables
//DatabaseVersion
privatestaticfinalintDATABASE_VERSION=1;
//DatabaseName
privatestaticfinalStringDATABASE_NAME="contactsManager"
//Contactstablename
privatestaticfinalStringTABLE_CONTACTS="contacts"
//ContactsTableColumnsnames
privatestaticfinalStringKEY_ID="id";
privatestaticfinalStringKEY_NAME="name";
privatestaticfinalStringKEY_PH_NO="phone_number"
publicDatabaseHandler(Contextcontext){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
//CreatingTables
@Override
publicvoidonCreate(SQLiteDatabasedb){
StringCREATE_CONTACTS_TABLE="CREATETABLE"+TABLE_CONTACTS+
+KEY_ID+"INTEGERPRIMARYKEY,"+KEY_NAME+
+KEY_PH_NO+"TEXT"+")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
//Upgradingdatabase
@Override
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,
//Dropoldertableifexisted
db.execSQL("DROPTABLEIFEXISTS"+TABLE_CONTACTS);
//Createtablesagain
onCreate(db);
}
//Addingnewcontact
publicvoidaddContact(Contactcontact){}
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
4/20
7/12/2016
AndroidSQLiteDatabaseTutorial
//Gettingsinglecontact
publicContactgetContact(intid){}
//GettingAllContacts
publicList<Contact>getAllContacts(){}
//GettingcontactsCount
publicintgetContactsCount(){}
//Updatingsinglecontact
publicintupdateContact(Contactcontact){}
//Deletingsinglecontact
publicvoiddeleteContact(Contactcontact){}
addContact()
//Addingnewcontact
publicvoidaddContact(Contactcontact){
SQLiteDatabasedb=this.getWritableDatabase();
ContentValuesvalues=newContentValues();
values.put(KEY_NAME,contact.getName());//ContactName
values.put(KEY_PH_NO,contact.getPhoneNumber());//ContactPhoneNumber
//InsertingRow
db.insert(TABLE_CONTACTS,null,values);
db.close();//Closingdatabaseconnection
}
Reading Row(s)
The following method getC on ta c t( ) will read single contact row. It
accepts id as parameter and will return the matched row from the
database.
getContact()
//Gettingsinglecontact
publicContactgetContact(intid){
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
5/20
7/12/2016
AndroidSQLiteDatabaseTutorial
publicContactgetContact(intid){
SQLiteDatabasedb=this.getReadableDatabase();
Cursorcursor=db.query(TABLE_CONTACTS,newString[]{KEY_ID,
KEY_NAME,KEY_PH_NO},KEY_ID+"=?",
newString[]{String.valueOf(id)},null,null
if(cursor!=null)
cursor.moveToFirst();
Contactcontact=newContact(Integer.parseInt(cursor.getString(
cursor.getString(1),cursor.getString(2));
//returncontact
returncontact;
}
get A l l C on t ac ts( ) will return all contacts from database in array list
format of Contact class type. You need to write a for loop to go through
each contact.
getAllContacts()
//GettingAllContacts
publicList<Contact>getAllContacts(){
List<Contact>contactList=newArrayList<Contact>();
//SelectAllQuery
StringselectQuery="SELECT*FROM"+TABLE_CONTACTS;
SQLiteDatabasedb=this.getWritableDatabase();
Cursorcursor=db.rawQuery(selectQuery,null);
//loopingthroughallrowsandaddingtolist
if(cursor.moveToFirst()){
do{
Contactcontact=newContact();
contact.setID(Integer.parseInt(cursor.getString(
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
//Addingcontacttolist
contactList.add(contact);
}while(cursor.moveToNext());
}
//returncontactlist
returncontactList;
}
6/20
7/12/2016
AndroidSQLiteDatabaseTutorial
database.
getContactsCount()
//GettingcontactsCount
publicintgetContactsCount(){
StringcountQuery="SELECT*FROM"+TABLE_CONTACTS;
SQLiteDatabasedb=this.getReadableDatabase();
Cursorcursor=db.rawQuery(countQuery,null);
cursor.close();
//returncount
returncursor.getCount();
}
Updating Record
up da te Co nta c t( ) will update single contact in database. This
method accepts Contact class object as parameter.
updateContact()
//Updatingsinglecontact
publicintupdateContact(Contactcontact){
SQLiteDatabasedb=this.getWritableDatabase();
ContentValuesvalues=newContentValues();
values.put(KEY_NAME,contact.getName());
values.put(KEY_PH_NO,contact.getPhoneNumber());
//updatingrow
returndb.update(TABLE_CONTACTS,values,KEY_ID+"=?"
newString[]{String.valueOf(contact.getID())});
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
7/20
7/12/2016
AndroidSQLiteDatabaseTutorial
newString[]{String.valueOf(contact.getID())});
}
Deleting Record
del et e Con t ac t( ) will delete single contact from database.
deleteContact()
//Deletingsinglecontact
publicvoiddeleteContact(Contactcontact){
SQLiteDatabasedb=this.getWritableDatabase();
db.delete(TABLE_CONTACTS,KEY_ID+"=?",
newString[]{String.valueOf(contact.getID())});
db.close();
}
packagecom.androidhive.androidsqlite;
importjava.util.ArrayList;
importjava.util.List;
importandroid.content.ContentValues;
importandroid.content.Context;
importandroid.database.Cursor;
importandroid.database.sqlite.SQLiteDatabase;
importandroid.database.sqlite.SQLiteOpenHelper;
publicclassDatabaseHandlerextendsSQLiteOpenHelper{
//AllStaticvariables
//DatabaseVersion
privatestaticfinalintDATABASE_VERSION=1;
//DatabaseName
privatestaticfinalStringDATABASE_NAME="contactsManager"
//Contactstablename
privatestaticfinalStringTABLE_CONTACTS="contacts"
//ContactsTableColumnsnames
privatestaticfinalStringKEY_ID="id";
privatestaticfinalStringKEY_NAME="name";
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
8/20
7/12/2016
AndroidSQLiteDatabaseTutorial
privatestaticfinalStringKEY_NAME="name";
privatestaticfinalStringKEY_PH_NO="phone_number"
publicDatabaseHandler(Contextcontext){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
//CreatingTables
@Override
publicvoidonCreate(SQLiteDatabasedb){
StringCREATE_CONTACTS_TABLE="CREATETABLE"+TABLE_CONTACTS+
+KEY_ID+"INTEGERPRIMARYKEY,"+KEY_NAME+
+KEY_PH_NO+"TEXT"+")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
//Upgradingdatabase
@Override
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,
//Dropoldertableifexisted
db.execSQL("DROPTABLEIFEXISTS"+TABLE_CONTACTS);
//Createtablesagain
onCreate(db);
}
/**
*AllCRUD(Create,Read,Update,Delete)Operations
*/
//Addingnewcontact
voidaddContact(Contactcontact){
SQLiteDatabasedb=this.getWritableDatabase();
ContentValuesvalues=newContentValues();
values.put(KEY_NAME,contact.getName());//ContactName
values.put(KEY_PH_NO,contact.getPhoneNumber());
//InsertingRow
db.insert(TABLE_CONTACTS,null,values);
db.close();//Closingdatabaseconnection
}
//Gettingsinglecontact
ContactgetContact(intid){
SQLiteDatabasedb=this.getReadableDatabase();
Cursorcursor=db.query(TABLE_CONTACTS,newString[]{KEY_ID,
KEY_NAME,KEY_PH_NO},KEY_ID+"=?",
newString[]{String.valueOf(id)},null
if(cursor!=null)
cursor.moveToFirst();
Contactcontact=newContact(Integer.parseInt(cursor.getString(
cursor.getString(1),cursor.getString(2));
//returncontact
returncontact;
}
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
9/20
7/12/2016
AndroidSQLiteDatabaseTutorial
//GettingAllContacts
publicList<Contact>getAllContacts(){
List<Contact>contactList=newArrayList<Contact>();
//SelectAllQuery
StringselectQuery="SELECT*FROM"+TABLE_CONTACTS;
SQLiteDatabasedb=this.getWritableDatabase();
Cursorcursor=db.rawQuery(selectQuery,null);
//loopingthroughallrowsandaddingtolist
if(cursor.moveToFirst()){
do{
Contactcontact=newContact();
contact.setID(Integer.parseInt(cursor.getString(
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2
//Addingcontacttolist
contactList.add(contact);
}while(cursor.moveToNext());
}
//returncontactlist
returncontactList;
}
//Updatingsinglecontact
publicintupdateContact(Contactcontact){
SQLiteDatabasedb=this.getWritableDatabase();
ContentValuesvalues=newContentValues();
values.put(KEY_NAME,contact.getName());
values.put(KEY_PH_NO,contact.getPhoneNumber());
//updatingrow
returndb.update(TABLE_CONTACTS,values,KEY_ID+
newString[]{String.valueOf(contact.getID())});
}
//Deletingsinglecontact
publicvoiddeleteContact(Contactcontact){
SQLiteDatabasedb=this.getWritableDatabase();
db.delete(TABLE_CONTACTS,KEY_ID+"=?",
newString[]{String.valueOf(contact.getID())});
db.close();
}
//GettingcontactsCount
publicintgetContactsCount(){
StringcountQuery="SELECT*FROM"+TABLE_CONTACTS;
SQLiteDatabasedb=this.getReadableDatabase();
Cursorcursor=db.rawQuery(countQuery,null);
cursor.close();
//returncount
returncursor.getCount();
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
10/20
7/12/2016
AndroidSQLiteDatabaseTutorial
returncursor.getCount();
}
Usage:
AndroidSQLiteTutorialActivity
packagecom.androidhive.androidsqlite;
importjava.util.List;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.widget.TextView;
publicclassAndroidSQLiteTutorialActivityextendsActivity{
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHandlerdb=newDatabaseHandler(this);
/**
*CRUDOperations
**/
//InsertingContacts
Log.d("Insert:","Inserting..");
db.addContact(newContact("Ravi","9100000000"));
db.addContact(newContact("Srinivas","9199999999"
db.addContact(newContact("Tommy","9522222222"));
db.addContact(newContact("Karthik","9533333333"
//Readingallcontacts
Log.d("Reading:","Readingallcontacts..");
List<Contact>contacts=db.getAllContacts();
for(Contactcn:contacts){
Stringlog="Id:"+cn.getID()+",Name:"+cn.getName()+
//WritingContactstolog
Log.d("Name:",log);
}
}
}
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
11/20
7/12/2016
AndroidSQLiteDatabaseTutorial
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
12/20
7/12/2016
AndroidSQLiteDatabaseTutorial
Whats Next?
If you feel comfortable with SQLite database, check out Android SQLite
Database with Multiple Tables which explains how to handle SQLite
when your app needs more than one table.
ravi8x
Ravi is hardcore Android programmer and Android
programming has been his passion since he compiled
his rst hello-world program. Solving real problems of
Android developers through tutorials has always been interesting part
for him.
RELATED POSTS
Android XML
Android
Android
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
Android
13/20
7/12/2016
AndroidSQLiteDatabaseTutorial
Parsing
Tutorial
Dashboard
Design Tutorial
by Ravi Tamada
by Ravi Tamada
Populating
Spinner data
from MySQL
Database
by Ravi Tamada
Working with
Realm Database
Replacing
SQLite & Core
Data
by Ravi Tamada
552Comments
AndroidHive
Recommend 111
Share
Login
SortbyNewest
Jointhediscussion
AjayB 21daysago
Iseeyouhaveuseddb.close()atonlyatoneplaceand
cursor.close()atanotherplace.Willthatnotleadtoissueofopendb
connections?AnywayIamlookingforcodethatusessynchronized
DBconnectiontoensurethatopencollectiondonothangthemobile
device.DOyouknowofanygoodexample?
Reply Share
rogue_shadow amonthago
Couldyoushowhowtousetheupdatefunction?Thankyou
Reply Share
GianEspinosa amonthago
Thanks!
Reply Share
amonthago
ihaveerrorinDatabaseHandler?why?
Reply Share
FaisalHyder> amonthago
Assalamoalaikum.
Error,where?whicherror?Bespecificbrother..
Reply Share
AmitJayant amonthago
Thanksalot!
Reply Share
florencecosmas 2monthsago
Thisisawesome!Thanks
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
14/20
7/12/2016
AndroidSQLiteDatabaseTutorial
Reply Share
KCRajuVysyaraju 2monthsago
it'sgreatandsimple.
Thankyou
Reply Share
MarcusSilva 3monthsago
ThankYouSoooomuch!!!
Greattutorial,wellexplained!
Reply Share
GrahamWashbrook 3monthsago
Thankyou.Anyreasonwhydb.close()isnotcalledinsomeofthe
CRUDoperations?
1
Reply Share
RaviTamada
Yeah,pleaseadditbeforereturn.AlsoIsuggestyoucreatea
singletonclasstoinitiatethesqlite.
1
Reply Share
LuthfiMNabil 3monthsago
ThanksfortheSample:)
Reply Share
RaviGodara 3monthsago
Thanksalotforthecode....
Asuperbpostforimageupload&retrieveisalsoat
http://godara4ravi.blogspot.in...
Reply Share
AhmadMuzzammil 4monthsago
howcanimakeanappthatfunctionreaddatabasenotcreate,edit
orevendeleteit?sothereisasearchbarthemifiinsertanIDthe
resultisdetailviewoftheID.Thankyou
Reply Share
Shreedhar090 4monthsago
Thanksalotman...
Reply Share
RaviTamada
Youarewelcome:)
Reply Share
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
15/20
7/12/2016
AndroidSQLiteDatabaseTutorial
NiravKalola 5monthsago
Verynicetutorial
Reply Share
DroidTalker 5monthsago
Hi,
@RaviTamadathankuforfirstofall.
ineedaquestion:
Inyouropinion,
howdoihavetochoosedatabaseforanyandroidapplication?
SQliteorPHPMysqlorelse?
Whatineedtosuggest?
Thankuveryverymuch
Regards,
Reply Share
hezo 5monthsago
thankyou!itveryuseful.
Reply Share
RaviTamada
Youarewelcome!
Reply Share
LucasOfend>RaviTamada 2monthsago
Pleasesir,ihaveanissuewiththeSQLiteDatabase
Restorebuttoninc#.
Canyouguidemepleaseonhowtorestorean
SQLitedatabaseinc#??
i'llbeverygratefull
Reply Share
KamaroLambert 6monthsago
ManIloveyourtutorialstheyareverysimpletounderstandand
codesareveryclean.
Reply Share
GoodnessAdewale>KamaroLambert 5monthsago
"thecodesareveryclean"verytrue
Reply Share
:)
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
16/20
7/12/2016
AndroidSQLiteDatabaseTutorial
Reply Share
LucasOfend>RaviTamada
2monthsago
Pleasesir,ihaveanissuewiththeSQLite
DatabaseRestorebuttoninc#.
Canyouguidemepleaseonhowtorestorean
SQLitedatabaseinc#??
i'llbeverygratefull.
Reply Share
NiravKalola 6monthsago
Verynicetutorial.thanksforsharing
Reply Share
RaviTamada
Youarewelcome:)
1
Reply Share
Elashry>RaviTamada 6monthsago
howcanmatchanewreadingdatawithsavedsqlite
database
Reply Share
Arpit 7monthsago
Thanksforthetutorialravisirbutiwannaaknowhowtoadd.sqlfile
intotheourSQLitedatabasePleasehelpmesuggestanylinktodo
thatandsorryformyenglish
Reply Share
joejava 7monthsago
//MySQLiteHelper
packagecom.egci392.qz0428
importandroid.content.Context
importandroid.database.sqlite.SQLiteDatabase
importandroid.database.sqlite.SQLiteOpenHelper
importandroid.util.Log
publicclassMySQLiteHelperextendsSQLiteOpenHelper{
publicstaticfinalStringTABLE_DATA="data"
publicstaticfinalStringCOLUMN_ID="_id"
publicstaticfinalStringCOLUMN_ROUTENAME="routeName"
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
17/20
7/12/2016
AndroidSQLiteDatabaseTutorial
publicstaticfinalStringCOLUMN_ROUTENAME="routeName"
publicstaticfinalStringCOLUMN_START_LATITUDE=
seemore
Reply Share
roopa 8monthsago
sorrystoreddatadisplayfromanotheractivity.
Reply Share
roopa 8monthsago
hi.iamnewtosqlite..andineedcodefromyousir.howtodevelopa
programforname,phno,city,countryfieldsgivefromthekeyboard
andstoredatainsqliteanddisplayinanotheractivityusinglistview.
Reply Share
SathishKumar 8monthsago
howtosavethedatasfromtheservertosqlitedatabase
Reply Share
AK 8monthsago
IammakingasmallappwhichwilljustaddanddeleteproductsbutIt
isnotabletoprintthedatabase
Iwanttoprintthedatabasebutitisnotenteringinthewhileloop
whichismadetomovethecursortoaccesstheproductname
Hereismycodeforproducts.javaclass
packagecom.firstapp.sqliteexample
publicclassProducts{
privateint_id
privateString_productname
publicProducts(Stringproductname){
this._productname=productname
}
publicvoidset_id(int_id){
this._id=_id
seemore
Reply Share
RhiedzalBrilliantMarz 8monthsago
Howshowingdatabaseinlayout??please
1
Reply Share
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
18/20
7/12/2016
AndroidSQLiteDatabaseTutorial
Homen 9monthsago
Nicetutorial
Reply Share
ShindouTakuto 9monthsago
whereiscodeforupdateanddeletecontact?andiwanttolistitin
listview..thanks
Reply Share
Tim>ShindouTakuto 6monthsago
@ShindouTakutonottoberude,butyoushouldreadupon
howandroidcomponentsworktogethertoforman
application.Thecodeforupdatinganddeletingisinthe
DatabaseHandlerclass,itsuptoyoutotrytofigureouthow
toputittogether.Theauthorshowsagoodexampleofhow
touseitintheactivity,justlookbythe"CRUDoperations"
comment.GreatJob@RaviTamada.
Reply Share
SunilSingh 10monthsago
veryniceforbeginners
Reply Share
masoudseraj 10monthsago
nicetutorial!
Reply Share
GergelyBindics 10monthsago
Hi!
Thankyouforthistutorial,itwasveryuseful.
TherewasoneproblemwithitifIamcorrect.
CallinggetContactsCount()method,myappcrashed.
Theproblemwasthatyouclosedcursorandthentriedtocallits
getCount()method.
SoIstoredcursor,getCount()intavariable,closedthecursorand
thenreturnedthevariable.
Cheers!
1
Reply Share
RaviTamada
Yeah.Yourcodeiscorrect.
Reply Share
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
19/20
7/12/2016
Reply Share
AndroidSQLiteDatabaseTutorial
8FarhanShaikh 10monthsago
ihavetrytodoaboveprogrambutistuckatmainclass.......when
initiate()theDatabaseHandlerlikethisDatabaseHandlerdb=new
DatabaseHandler(this)inmainActivityclassitsaystoimpement
arguments...butwhenisaeinyourmainActivitythereisno
argumentexpect(this)
pleasehelpmesoon
Reply Share
HenriqueRosa 10monthsago
Howcaniexcludethetable,nottherows,buttheintiretable?
Reply Share
UsmanIshrat ayearago
Wellelaborated...couldbemorehelpfulifyouexplaintheparameters
ofthequeries.
Reply Share
8FarhanShaikh>UsmanIshrat 10monthsago
ifuunderstoodprogramplzhelp..ipostedabovemyquery
plzhelpmeout
1
Reply Share
SanketPrabhu ayearago
Infuture,canORMLite/RealmtakeovertheSQlite?Asadeveloper
QUICK CONTACT
ABOUT ANDROIDHIVE
Advertise with us
AndroidHive is beginner's
Privacy Policy
Terms of Service
Sitemap
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/
20/20