Sie sind auf Seite 1von 14

24/11/2014 AndroidSQLiteDatabaseTutorial

Ravi Tamada

Android SQLite Database Tutorial Hyderabad, INDIA

457 Comments . By Ravi Tamada on 27th, Nov 2011 - 02:32 PM Tweet 87 102 Like 749

Subscribe to get latest updates to your inbox.


-- I dont spam!

Enter your email here SUBSCRIBE

Android provides several ways to store user and app


data. SQLite is one way of storing user data. SQLite is a
very light weight database which comes with Android
OS. In this tutorial Ill be discussing how to write classes
to handle all SQLite operations.

AndroidHive

In this tutorial I am taking an example of storing user contacts in SQLite database. I am using a table Like

called Contacts to store user contacts. This table contains three columns id (INT), name (TEXT),
phone_number(TEXT).
24,836peoplelikeAndroidHive.

Contacts Table Structure


Facebooksocialplugin

Tag Cloud

Action Bar Adapter Animation API

Apps Async Beginner Camera

Chat Dashboard Database facebook

Fragments GCM GDK Gestures

Google Google Glass Google Plus

GPS Grid Grid View HTTP

Intermediate json Libstreaming

List View Locale Maps MySQL

Navigation Drawer PHP Pinch

Writing Contact Class Quick Tips REST sessions Slim

Sockets Speech Input Spinner


Before you go further you need to write your Contact class with all getter and setter methods to
sponsored SQLite Swipe Tab View
maintain single contact as an object.
Twitter UI Video Video Streaming

Contact.java View Pager Volley Wearable xml

packagecom.androidhive.androidsqlite;

publicclassContact{

//privatevariables
int_id;
String_name;
String_phone_number;

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 1/14
24/11/2014 AndroidSQLiteDatabaseTutorial
//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; Ravi Tamada
} google.com/+RaviTamada
//gettingID
publicintgetID(){ Seguir
returnthis._id;
} 7.465 seguidores

//settingid
publicvoidsetID(intid){
this._id=id;
} Most Popular

//gettingname 1 Android SQLite Database Tutorial - 917,090
publicStringgetName(){
returnthis._name; views
}
2 How to connect Android with PHP, MySQL -
//settingname
publicvoidsetName(Stringname){ 782,451 views
this._name=name;
} 3 Android JSON Parsing Tutorial - 737,758

views
//gettingphonenumber
publicStringgetPhoneNumber(){
returnthis._phone_number; 4 Android Custom ListView with Image and
} Text - 716,734 views

//settingphonenumber
publicvoidsetPhoneNumber(Stringphone_number){ 5 Android Push Notifications using Google
this._phone_number=phone_number; Cloud Messaging (GCM), PHP and MySQL -
}
} 646,310 views

6 Android Login and Registration with PHP,


MySQL and SQLite - 511,363 views

7
Writing SQLite Database Handler Class Android Tab Layout Tutorial - 437,406 views

8 Android Sliding Menu using Navigation


We need to write our own class to handle all database CRUD(Create, Read, Update and Delete) Drawer - 431,806 views
operations.
9 Android GPS, Location Manager Tutorial -
1. Create a new project by going to File New Android Project. 388,328 views
2. Once the project is created, create a new class in your project src directory and name it as
10 Android Login and Registration Screen
Da t aba s eH a ndl e r. ja va ( Right Click on src/package New Class)
Design - 360,666 views
3. Now extend your DatabaseHandler.java class from SQLiteOpenHelper.

publicclassDatabaseHandlerextendsSQLiteOpenHelper{

4. After extending your class from SQLiteOpenHelper you need to override two methods onCreate()
and onUpgrage()
o n Cr e a te () These is where we need to write create table statements. This is called when database
is created.
o n Upg r ade () This method is called when database is upgraded like modifying the table structure,
adding constraints to database etc.,

publicclassDatabaseHandlerextendsSQLiteOpenHelper{

//AllStaticvariables
//DatabaseVersion
privatestaticfinalintDATABASE_VERSION=1;

//DatabaseName
privatestaticfinalStringDATABASE_NAME="contactsManager";

//Contactstablename
privatestaticfinalStringTABLE_CONTACTS="contacts";

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 2/14
24/11/2014 AndroidSQLiteDatabaseTutorial
//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+"TEXT,"
+KEY_PH_NO+"TEXT"+")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

//Upgradingdatabase
@Override
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
//Dropoldertableifexisted
db.execSQL("DROPTABLEIFEXISTS"+TABLE_CONTACTS);

//Createtablesagain
onCreate(db);
}

All CRUD Operations (Create, Read, Update and Delete)

Now we need to write methods for handling all database read and write operations. Here we are
implementing following methods for our contacts table.

//Addingnewcontact
publicvoidaddContact(Contactcontact){}

//Gettingsinglecontact
publicContactgetContact(intid){}

//GettingAllContacts
publicList<Contact>getAllContacts(){}

//GettingcontactsCount
publicintgetContactsCount(){}
//Updatingsinglecontact
publicintupdateContact(Contactcontact){}

//Deletingsinglecontact
publicvoiddeleteContact(Contactcontact){}

Inserting new Record

The a ddCo n t a ct () method accepts Contact object as parameter. We need to build ContentValues
parameters using Contact object. Once we inserted data in database we need to close the database
connection.

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 g e t Co n t ac t () will read single contact row. It accepts id as parameter and will
return the matched row from the database.

getContact()
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 3/14
24/11/2014 AndroidSQLiteDatabaseTutorial
getContact()
//Gettingsinglecontact
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,null,null);
if(cursor!=null)
cursor.moveToFirst();

Contactcontact=newContact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2));
//returncontact
returncontact;
}

g e t A llCo n t a c 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(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
//Addingcontacttolist
contactList.add(contact);
}while(cursor.moveToNext());
}

//returncontactlist
returncontactList;
}

g e t Co n t ac t sC o u nt ( ) will return total number of contacts in SQLite database.

getContactsCount()
//GettingcontactsCount
publicintgetContactsCount(){
StringcountQuery="SELECT*FROM"+TABLE_CONTACTS;
SQLiteDatabasedb=this.getReadableDatabase();
Cursorcursor=db.rawQuery(countQuery,null);
cursor.close();

//returncount
returncursor.getCount();
}

Updating Record

u pda t eC o n t ac 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+"=?",

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 4/14
24/11/2014 AndroidSQLiteDatabaseTutorial
newString[]{String.valueOf(contact.getID())});
}

Deleting Record

de le t e Co n 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();
}

Complete DatabaseHandler.java Code:

DatabaseHandler.java
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";
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+"TEXT,"
+KEY_PH_NO+"TEXT"+")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

//Upgradingdatabase
@Override
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
//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());//ContactPhone

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 5/14
24/11/2014 AndroidSQLiteDatabaseTutorial

//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,null,null,null);
if(cursor!=null)
cursor.moveToFirst();

Contactcontact=newContact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2));
//returncontact
returncontact;
}

//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(0)));
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();
}

}

Usage:

AndroidSQLiteTutorialActivity
packagecom.androidhive.androidsqlite;

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 6/14
24/11/2014 AndroidSQLiteDatabaseTutorial

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()+",Phone:"
//WritingContactstolog
Log.d("Name:",log);
}
}
}

Android Log Cat Report:


I am writing output to Log report. You can see your log report by going to Windows Show View
Other.. Android Log Cat.

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 7/14
24/11/2014 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.

Share this article on

8 749 102
87

0
Like Tweet

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 8/14
24/11/2014 AndroidSQLiteDatabaseTutorial

You May Also Like

Android SQLite Android Populating Android Login and Android RSS Reader
Database with Spinner data from Registration with Application using
Multiple Tables SQLite Database PHP, MySQL and SQLite Part 1
SQLite

457Comments AndroidHive Login

SortbyNewest Share
Favorite

Jointhediscussion

buildakicker 12daysago

Hi,HowdoIcreateamethodtocheckforexistingrecords?Idon'twanttoaddduplicatesfor
example.Thanks!
Reply Share

RusseliusErnestius amonthago

somemethodsdidnotClosedatabaseortheCursor...)
Reply Share

Guest amonthago

neverForgettoclosetheCursorinmethodgetAllContact!)
Reply Share

Maryea 2monthsago

hyee....
iamfacingdatabaseupgradationproblem..usingaprepopulatedsqlitedatabase...itworksfine..bt
whenitrytoupdateitbyinsertingvaluesinexistingtableusingsqlitebrowser..itneverupgrades...
andshowsnosuchrecord..
Anyideaforsolution???
Reply Share

Agilitis 2monthsago

Helloeveryone!I'mfacingaprettyirritatingproblem...Myappstartsonmymobilebutitshutsdown
withoutanyerrors,anyideas?
Reply Share

baus 3monthsago

whereisthethe"("intheCREATE_CONTACTS_TABLEString?
Reply Share

mukesh 3monthsago

atlogcathereelementsaddonebyonewhenconnectionisgenerate.............
THEPROBLEMHERE

if(cursor.moveToFirst()){

do{
Contactcontact=newContact()
contact.setID(Integer.parseInt(cursor.getString(0)))
contact.setName(cursor.getString(1))
contact.setPhoneNumber(cursor.getString(2))
//Addingcontacttolist
contactList.add(contact)
}while(cursor.moveToNext())
}

REDUCEIT........
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 9/14
24/11/2014 AndroidSQLiteDatabaseTutorial
REDUCEIT........

THANKSWITHBESTREGARDS

2 Reply Share

DilberiusBi Boji 3monthsago

Doesanyoneknowhowtodisplaydatabaseintextvieworinanythinglikedatabase?Iwouldliketo
makeahighscorebutdonotknowthecodetodisplaystringsintextviewplsanswerat
dilberius@gmail.com
Reply Share

FDM.Pro 3monthsago

Whyusestaticvariablesincontactclass?
Reply Share

FDM.Pro >FDM.Pro 3monthsago

SorryinHandlernotincontact.
Reply Share

NikaKirkitaZe 3monthsago

Hi.Thankyouforthistutorial,itisreallyhelpful.

UnfortunatelymyappgivesID=0toeverytime,itried(INTEGERPRIMARYKEY),('_id'
INTEGERPRIMARYKEYAUTOINCREMENT),(idINTEGERPRIMARYKEYAUTOINCREMENT
NOTNULL),

Butiamgettingsameresultalways.whatcanido?
Reply Share

Midomed 3monthsago

whatifIwantedtocreateaquerytosearchforaparticularidoraname?
Reply Share

NewtoAndroid 4monthsago

forpackagecom.androidhive.androidsqlite
Reply Share

NewtoAndroid 4monthsago

Thetypejava.lang.Objectcannotberesolved.Itisindirectlyreferencedfrom
required.classfiles
Thetypejava.lang.Stringcannotberesolved.Itisindirectlyreferencedfrom
required.classfiles

AboveerrorinDatabaseHandler.javafile
Reply Share

Anas 4monthsago

Nicearticle,veryuseful!
Reply Share

tok 4monthsago

IsthereanypossibilitytoaddArrayListasatypeofrow?
Reply Share

junka 4monthsago

Thankyouverymuchforthetutorial.ItworkedverywellexceptforthegetContactsCount()
function.ItwasgivingmeanerrorsayingthatIwastryingtoreadavaluefromaclosedobject.I
changedthecodeto:

publicintgetContactsCount(){
StringcountQuery="SELECT*FROM"+TABLE_CONTACTS
SQLiteDatabasedb=this.getReadableDatabase()
Cursorcursor=db.rawQuery(countQuery,null)
intcount=cursor.getCount()//addedlinehere
cursor.close()

returncount
}

Afterthateverythingwasworkingsmoothly.Thanksagain.

3 Reply Share

Jomel >junka 3monthsago

howtousethatgetContactCount
Reply Share

Jongsik 5monthsago

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 10/14
24/11/2014 AndroidSQLiteDatabaseTutorial
Jongsik 5monthsago

Veryusefularticle!Thankyou:D
Reply Share

RaviTamada Mod >Jongsik


5monthsago

Youarewelcome:)
Reply Share

AsadAliJogi 5monthsago

howtosavedatafromsoaptosqlitedatabaseinandroid

IamgettingGetVehiclesmethodofSOAPWSDLfromSOAPwebservicesandcallthatGetVehicles
resultinTextViewwhenclickingonaButtonevent.

whenIrunprogram,IwanttostorethatresultshowninTextViewinSqlitedatabase?

HowcanIdothat?

IhavemakeaclassgetterSetteranddatabasehandlerwhichextendsSQLiteOpenHelper?

5 Reply Share

santosh 5monthsago

howdoishowthisdataintablerow
Reply Share

Mike 5monthsago

Hi,

FortheAndroidSQLiteTutorialActivityclass,iamfacinganerrorwherethecode

DatabaseHandlerdb=newDatabaseHandler(this)

givesmeanerrorsaying:TheconstructorDatabaseHandler(SQLiteSubmit)isundefined

Doesanyoneknowhowtosolveit?ShouldtheclassextendSQLiteOpenHelperinsteadofActivity?
Reply Share

SushreekantMishra >Mike 5monthsago

TryDatabaseHandlerdb=newDatabaseHandler(AndroidSQLiteTutorialActivity.this)
Reply Share

Mike >SushreekantMishra 5monthsago

Hithanksforthehelp!

Iamnewtoandroiddevelopmentanddatabases.CanicheckwhetherdataSQLite
databaseisonlyaccessibleto1user/device?

Forexample,ifthereisaContactsdatabase,andmanyusersallovertheworldwant
toaccessthisdatabasetoretrieveinformation,whatkindofdatabaseshouldbeused?
Reply Share

DavidDoyle >Mike 5monthsago

Thisonlyallowsyoutostoreinadbaccessibleonthedevicetooneapplication.
Touseashareddb,accessiblefrommultipledevices,you'dneedtocallaweb
service(thoughyoustillmightwanttostorealocalcopyofanyinformationfor
cachingpurposes).
Reply Share

piter09100 6monthsago

Thankyou,greattutorial:)

ButIdontunderstandhowyousetIDs.MyappgivesID=0toeverysaveandIdontknowwhy??
Reply Share

DavidDoyle >piter09100 5monthsago

ThedefinitionfortheI'dcolumnusing'Integerprimarykey'shouldautomaticallyincrement
onaninsert.Ifthatisnotworkingtry'integerprimarykeyautoincrementnotnull'.
Reply Share

piter09100 >DavidDoyle 5monthsago

Thanks,itworksnow,I'vechanged...+KEY_ID+"INTEGERPRIMARYKEY,"..to
...+"KEY_IDINTEGERPRIMARYKEY,"...
Reply Share

SarthakMajithia >piter09100 4monthsago

Youneedtochange"INTEGERPRIMARYKEY"to"INTEGERPRIMARY
KEYAUTOINCREMENTNOTNULL"
1 Reply Share

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 11/14
24/11/2014 AndroidSQLiteDatabaseTutorial

MiladNozari 6monthsago

Thanks,goodtutorial.ButmayIaskwhyareyouusing:

Integer.parseInt(cursor.getString(0))

insteadof:

cursor.getInt(0)

Thanks
Reply Share

Manoj >MiladNozari 3monthsago

ithasstorethedatainstringformat
Reply Share

Manoj >Manoj 3monthsago

Checkthisone...db.addContact(newContact("Ravi","9100000000"))

itsstoringdatainstringformat...notstoredin
db.addContact(newContact("Ravi",9100000000))
Reply Share

gdguradio@gmail.com 6monthsago

"ContactgetContact(intid)"
howtousethisfunctionpleasegivesampleonhowtodoitlikeiwanttogetnamesonlysoiwantto
checkthecolumnnameonlyandgetallthenamesthatarejohnanysampleonthis?becausewheni
useit,itthrowanexceptionlikethis
"thrownewCursorIndexOutOfBoundsException(mPos,getCount())"
andhowtouse
List<contact>contacts=db.getAllContacts()

withoutusingthiscode

for(Contactcn:contacts){
Stringlog="Id:"+cn.getID()+",Name:"+cn.getName()+",Phone:"+cn.getPhoneNumber()
//WritingContactstolog
Log.d("Name:",log)

likeifiwanttouseiftocompareifigetsamevaluefromthename?likeifiwanttogetallnameof
johnfromthelist

3 Reply Share

Jagdeep 6monthsago

Cursorcursor=db.rawQuery(countQuery,null)
cursor.close()

//returncount
returncursor.getCount()

Errorherecannotaccessthecursorafterclosingitbetterputthecountinsomeanothervariableand
returnthatvariable.
Reply Share

rameshbs >Jagdeep 6monthsago

Youshouldnotclosethecursorafteruquery,cursoristheonewhichholddata&other
objects.Soifuclose,itwontgiveucount.Onceallcursoroperationsiscompleted.closeit
Reply Share

ZahidulIslam 6monthsago

goodtutorialbutonething..datareinsertedwhilerunthetutorialagain.i.efourrowsinsertedas20
rowswhenrunthetutorial5times.plzsolve.

1 Reply Share

Faisal >ZahidulIslam 6monthsago

thisisnotaproblem~
Reply Share

TrevorL. 6monthsago

Thanks,yourtutorialsaremuchappreciated.
Reply Share

CnuFederer 7monthsago

Hi,
thanksforneattutorial.
I'munabletoseethecreateddbfilesphysicallyinmydevice.(/data/data/<packagename>/)
http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 12/14
24/11/2014 AndroidSQLiteDatabaseTutorial

doyouhaveanyideawhythishappens?

7 Reply Share

arefchegini 7monthsago

Hello,
ThankyouforTutorial.

howdoyoustoregroupdatainthesqllitedatabaseandwhenimcreateaprogramineclipsandim
installinthemobaildatabaseisvoid.
Reply Share

AbdullahBenNakhi 7monthsago

HowdoyoustoreimagesintheSQLitedatabase?

6 Reply Share

AlsoRavi 7monthsago

NeverbeforehaveIgonethroughatutoriallikethisandhaditworkonthefirsttime.RaviTamada
youaretheman!
Reply Share

ShimaShirazi 8monthsago

Somebodyanswermyquestion,plz
Reply Share

Chrisantics 8monthsago

hello!howdoiwanttoviewthedatabaseinsqLitebrowser?Ican'tseemtofindthe.dbfile??

4 Reply Share

Hendrik 8monthsago

Hi,intheaddContactmethod,cansomeoneexplainwhyonlyKEY_NAMEandKEY_PH_NOare
beingadded?DoesKEY_IDnotneedtobeadded?Thanks
Reply Share

Noman >Hendrik 8monthsago

becauseitisautoincrement
2 Reply Share

KamolpornSanamlao 8monthsago

Iwouldliketothanks,thistutorialishelpful.:)
Reply Share

ShimaShirazi 8monthsago

Hi,
ThankyouforTutorial.
Iwouldbeverythankfulifyouanswermyquestion:
WherecanIseemydatabaseapplicationin(android)phone?
Irootedthephone,butIcannotfindfoldersuchas/data/data/my_app/databade

8 Reply Share

Arsal >ShimaShirazi 6monthsago

data>data>seeyourpackagename>databases>
Reply Share

Loadmorecomments

Subscribe
d AddDisqustoyoursite Privacy

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 13/14
24/11/2014 AndroidSQLiteDatabaseTutorial

Copyright 2014 AndroidHive. All rights reserved Advertise . Privacy Policy . Terms & Conditions

http://www.androidhive.info/2011/11/androidsqlitedatabasetutorial/ 14/14

Das könnte Ihnen auch gefallen