Вы находитесь на странице: 1из 83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

ReignDesign

Jobs

Blog

Labs

MARCH 3RD, 2009 | 768 COMMENTS

Juan-Manuel Flux

Using your own SQLite database in


Android applications
Most all of the Android examples and tutorials out
there assume you want to create and populate your
database at runtime and not to use and access an
independent, preloaded database with your Android

Tags

application.

Android,
Databases,

The method I'm going to show you takes your own

howto, Java,
SQLite
Categories
Technology

SQLite database file from the "assets" folder and copies into the system
database path of your application so the SQLiteDatabase API can open and
access it normally.
1. Preparing the SQLite database file.
Assuming you already have your sqlite database created, we need to do some
modifications to it.
If you don't have a sqlite manager I recommend you to download the opensource
SQLite Database Browser available for Win/Linux/Mac.
Open your database and add a new table called "android_metadata", you can
execute the following SQL statement to do it:

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

1/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')

Now insert a single row with the text 'en_US' in the "android_metadata" table:

INSERT INTO "android_metadata" VALUES ('en_US')

Then, it is necessary to rename the primary id field of your tables to "_id" so


Android will know where to bind the id field of your tables.
You can easily do this with SQLite Database Browser by pressing the edit table
button

, then selecting the table you want to edit and finally selecting the

field you want to rename.


After renaming the id field of all your data tables to "_id" and adding the
"android_metadata" table, your database it's ready to be used in your Android
application.

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

2/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Modified database

Note: in this image we see the tables "Categories" and "Content" with the id field
renamed to "_id" and the just added table "android_metadata".
2. Copying, opening and accessing your database in your Android
application.
Now just put your database file in the "assets" folder of your project and create a
Database Helper class by extending the SQLiteOpenHelper class from the
"android.database.sqlite" package.
Make your DataBaseHelper class look like this:

public class DataBaseHelper extends SQLiteOpenHelper{


//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

3/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

private static String DB_NAME = "myDBName";


private SQLiteDatabase myDataBase;
private final Context myContext;

/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}

/**
* Creates a empty database on the system and rewrites it with your own da
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{

//By calling this method and empty database will be created in


//of your application so we are gonna be able to overwrite that
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}

/**
* Check if the database already exist to avoid re-copying the file each t
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

4/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

try{

String myPath = DB_PATH + DB_NAME;


checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteData
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{

//Open the database


String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

5/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersio
}

// Add your public helper methods to access and get content from the d
// You could return cursors by doing "return myDataBase.query(....)" so
// to you to create adapters for your views.
}

That's it.
Now you can create a new instance of this DataBaseHelper class and call the
createDataBase() and openDataBase() methods. Remember to change the
"YOUR_PACKAGE" to your application package namespace (i.e:
com.examplename.myapp) in the DB_PATH string.

...
DataBaseHelper myDbHelper = new DataBaseHelper();
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

6/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
...

This article has also been translated into Serbo-Croatian by Anja Skrba from
Webhostinggeeks.com.

768 Comments
todd | March 3rd, 2009

Solid writeup. We should take a look at modifying a lightweight ORM to work on


Android. Something similar to iBATIS (http://ibatis.apache.org) with special
hooks to setup and upgrade the database.

Will | March 7th, 2009

Wow, much better then reading and executing 7000+ inserts. Brought an 18
second operation down to about 2 seconds.
Please note that on Firefox 3.0.7 on Ubuntu 8.10 the greater than sign in the
while loop shows up as its html code (& g t

burton miller | March 8th, 2009

Well presented. But not a good solution for large databases (fine for small ones).
This DOUBLES the footprint of your database. A better solution for any sizeable
database, is to download the database when the app is first run, as a secondary
installation.
This, at least, only eats up X precious megabytes once.
Still suboptimal is the fact that the database must reside in
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

7/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

/data/data/YOUR_PACKAGE/databases because anything bulky should be on


the sd card. I guess google will eventually let us access databases in other
locations, or install our apps directly on the SD card.

Justin Jaynes | March 8th, 2009

There is an HTML error in the code preventing a Greater Than sign from
appearing and the symbols %gt; instead. It is in the while loop of the
copyDataBase method.

fluxa | March 8th, 2009

HTML error in the code fixed, thanks for the feedback.

David | March 10th, 2009

This is exactly what I have been looking for.. But I am having an issue. I keep
getting a failed to open the database errors.
sqlite3_open_v2(/data/data/com.testapp/databases/database.db, &handle, 1,
NULL) failed. I have tried this on both .db and .db3 files and neither of them are
working. I followed you tutorial and placed the db in the assets directory, both in a
folder called databases and just in the directory. Is there something else I am
doing wrong?

David | March 10th, 2009

I just realized the issue is not the loading of the database it is actually the first
time it is read. Your tutorial is working properly thanks.

Will | March 12th, 2009

I came across one issue, based on the lack of complaints I think its fairly unique.
The first SELECT I ran on a table in the copied DB crashed with Android claiming
the table did not exist. I checked through adb and sqlite3 and the table *did* exist.
Eventually I tried CREATEing the table just before I SELECTed from it (since it
allegedly didnt exist). Androids response was that the database file was corrupt.
The solution was to programmatically open the database like normal, immediatly
close it, than open it again. Prior to that I did try copying a completely closed
database to /assets; the first SELECT still crashed.
Heres the first error for searchability:
03-12 01:17:22.810: ERROR/AndroidRuntime(512): Caused by:
android.database.sqlite.SQLiteException: no such table: tblMyTable: , while
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

8/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

compiling: SELECT

Zek | March 31st, 2009

To Will :
Try to add :
mOpenHelper.close();
Just before SQLiteDatabase db = mOpenHelper.getReadableDatabase(); in
query function of your provider.
Thats solve the same problem for me.

George F. | April 29th, 2009

For me I get an ioexception thrown on the first


read statement:
while ((length = myInput.read(buffer))>0){
Everything seems to get opened up just fine. Ive named
the db ls.db in the assets folder. Should it be in the assets
folder per se or under some subdir? Any suggestions on how
to debug the failed read?
Thanks much

fluxa | April 30th, 2009

George,
Better if you get rid of the extension of your database file ( just ls ).
Your database file in the assets folder is right, then:
InputStream myInput = myContext.getAssets().open(ls);
it should open your database file, put a break point after this line to see if its
working.
Also be sure that the path to your system application folder is right.
/data/data/your.package.name/databases/

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

9/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

then your output path should be


/data/data/your.package.name/databases/ls
good luck

Hamy | May 13th, 2009

Thanks for being the first post I have been able to find using multiple tables!
If you have time for another writeup, or an addition, it would be really useful to
see how you are grabbing the data from a multi-table database. Using Cursors is
obviously much harder than it is on one table, and I have not really found any
help on a recommended way to do that.
Thanks again!
Hamy

Wilson L. | May 21st, 2009

Excelent post! Congratz!


George F., I was wondering if you have solved your problem reading the
assets/your_db_name. Im facing the same problem now, and I dont know what
is going on, because I can read it in terminal with sqlite command. Also Im
proceeding exactly as fluxa said.
Thanks in advance!

fluxa | May 21st, 2009

Wilson:
Check you database file size, there is a limitation around 1.2 Mb for files in the
asset folder.
Wilson splitted up his db using Unix split command, added them in the res/raw
folder, and then opened them up at install time to read. Then proceeded to splice
them back together into the db and all worked fine.
Thanks George for this.

Wilson L. | May 22nd, 2009

Thank you very much fluxa!

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

10/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

It was indeed the file size.. I was able to redesign the database, actually the
problem was helpful somehow, because I cleaned the tables (the overall
schema).
Im dealing with a large amount of data, at first I was going to set up a web
service to retrieve the info online, but my tutor didnt like the idea of using
internet so Ok, lets try to downoad a little piece of internet and store it in a
sqlite database. Seems absurd (and it is), but he was very reluctant :/
Thank you again and Thanks George for a clever solution!

BGH | June 29th, 2009

Thanks for the tut, this is exactly what I need. Im having a problem though
When it starts it recognises that there is no db and creates the empty db fine.
Then in the copyDataBase method when it gets the the line
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
I get the error
06-30 00:01:35.901: INFO/WTF(29581): java.io.FileNotFoundException:
/data/data/bgh.com.spanishflashcards/databases/spanish
The path is correct. It has to be because it used the same path when creating the
blank db. The blank db definitely exists. If I pause the code before this step I can
see the blank db in DDMS.
Any reason why I would get that error?

Rams | July 9th, 2009

THanks For the tutorial


am also getting the same error like BGH sayshave any reason
BGH:Did u find the solution?

Tzur | July 11th, 2009

Hi,
thanks for addressing this important issue. Many apps need this flow.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

11/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

one question,
what if my table just doesnt have a column name id, what happens in this
case?
heres a sample schema of my table,
.schema OPR_CHEMISTRY_TAB
CREATE TABLE OPR_CHEMISTRY_TAB (ENTRY_ID text, INDEX_LETTER text,
INDEX_ORD int, ENAME text, DESCR text, HAS_IMAGES int);
CREATE INDEX ENTRY_ENTRY_ID_IX on OPR_CHEMISTRY_TAB(ENTRY_ID
asc);
CREATE INDEX ENTRY_ENTRY_LETTER_ORD_IX on
OPR_CHEMISTRY_TAB(INDEX_LETTER asc, INDEX_ORD asc);
what does the native android table structure expects in this case?
thanx!
tzurs

dennie | August 13th, 2009

Hi, I just want to know how can I delete the table after I created it?

Jimmy | September 10th, 2009

Is the android_metadata table necessary?

fluxa | September 10th, 2009

Hi Jimmy, yes it is.

p6majo | September 19th, 2009

Hi,
would it be possible to have a database that is kept on the sdcard?
I would like to have access to my database with other applications as well and I
cannot access it, when it is stored in the /data/data/ directories. Im not a
superuser on my phone and Im a little bit scared of loosing all my data when
doing this goldcard business to become a su.
Therefore, Im looking for a possibility of using the sql database in my
applications but storing its data on the sdcard.
Will it be possible?
Johannes.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

12/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

sara | September 29th, 2009

Try this,
Android Sqlite Databases
http://sarangasl.blogspot.com/2009/09/create-android-database.html

minhbu | October 2nd, 2009

Thanks for the tut, this is exactly what I need. But I having a problem when I try to
store file Image. I try to use some sqlite manager but not work. Please! Help me
to solve this problem.
Anyway, thanks a lot.

Serg Podtynnyi | October 3rd, 2009

I had problems with this code, it was not properly copied file into internal storage.
A added
this.close();
before copyDataBase();
and it works like charm.

Daniel Lew | October 16th, 2009

@BGH:
This is a little late now, but I had the same problem, but I figured out the problem.
The issue comes up when this db is the FIRST db you try to create. If thats the
case, then data/data/YOURPACKAGE/databases doesnt exist yet. You have to
create the /databases directory or the method will fail. Its pretty easy though:
File f = new File(DB_PATH);
if (!f.exists()) {
f.mkdir();
}

cousinHub | November 16th, 2009

There is also a table called sqlite_sequence


in a Android SQLite DB
This table has 2 columns : name and seq.
Do we need to take care of it ?
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

13/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

If I open the DB with:


public void openDataBase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
instead of using (OPEN_READONLY):
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
to be able to add records in the DB.
I then noticed that seq within the table sqlite_sequence is not changing,
even as I add or delete records successfully from the DB ???
I viewed this by doing a pull a file from the device within the DDMS view
/data/data/PACKAGE_NAME/databases/
(and then opening this file with SQLite Browser.
Is that normal/ ok ?
_id is set to INTEGER PRIMARY KEY (works fine to add records)
but should I also take care of seq an increase it by 1,
everytime a record is added to the DB ???
Txs for any advice on this.

deep | November 20th, 2009

hi,
I have more then 1.5 MB of DB so can anybody tell me how to connect the DB
with the android because i cant put my DB in assests folder(Assets can take only
upto 1.2 MB of DB).

David Weaver | November 21st, 2009

Hello,
The database apparently loads perfectly but when I come to try and run a query I
get the message:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

14/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

11-17 20:54:03.126: ERROR/AndroidRuntime(749): java.lang.RuntimeException:


Unable to start activity
ComponentInfo{com.allergycookbook/com.allergycookbook.AllergyCookBook}:
android.database.sqlite.SQLiteException: no such table: recipes: , while
compiling: SELECT _id, recipe_name FROM recipes
I double checked and the table exists in the database (as does the field). I think it
might be the same problem that Will posted above, but I tried to close and then
open the database and it didnt work.
Perhaps its my shaky knowledge of SQL to blame? The code I am using to run
the query was cribbed from the Android notepad tutorial and then modified
accordingly. See below:
private void fillData()
{
// Get all of the rows from the database and create the item list
mNotesCursor = myDbHelper.fetchAllNotes();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{DataBaseHelper.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.recipe_row, mNotesCursor, from, to);
setListAdapter(notes);
}
If anyone can help me Id be most grateful.

Alocaly | November 21st, 2009

Hi Deep,
Actually I had this issue too. The anwser is simple : cut your big database file as
several sub 1 Mo files !
I gave some explanations on this subject here :
http://androidblogger.blogspot.com/2009/05/how-to-ship-application-withpre-baked.html
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

15/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Hope it helps !

Deep | November 26th, 2009

Hi Alocaly,
Thanks for your help but the issue is that my DB is in SQLite manager so how to
cut SQLite DB so that we can able to connect it to our Android application. Please
help me out of this problem.
Thanks
Deep

Pieter Bonne | December 3rd, 2009

Thank you for this article! I succesfully use an embedded an sqlite database in
my application, but at first I had many issues with android not wanting to open the
database. I tried using most of the available opensource sqlite editors but they all
seemed to produce incompatible sqlite files. In the end I ended up building up my
database programmatically using a jdbc sqlite driver
(http://www.zentus.com/sqlitejdbc) which seems to produces files android has
no problem with!

Poson | December 8th, 2009

The DB is not found I have met the same problem too.Mybe we should think
about changing permissions of the DB file. But how to do it in code?
Please help me out of the problem.

Alocaly | December 12th, 2009

For Deep :
In my blog article, I explained how I cut my database, and remerge it at the first
launch of the game !
http://androidblogger.blogspot.com/2009/05/how-to-ship-application-withpre-baked.html

Michael | December 21st, 2009

Hi Everyone,
I have the same error in the logcat as David
sqlite3_open_v2(/data/data/com.testapp/databases/database.db, &handle, 1,
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

16/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

NULL) failed.. I have the method running on the initial activity that runs in my
app and it force closes. I close, then open the app up and no error. I cant figure
out why Im crashing only on the initial run
Any help would be great!

rabbit | December 28th, 2009

Hi everyone,
i have follow the article, but i got some error message shows :
java.lang.IlleagalStateException: database not open
but i did open the database before i access it.
anyone can help me ???
thanks .

jim | January 20th, 2010

I found a simplier way.


Just copy a good one and start with that.
Details:
1. Run the example called Events1. Its a bunch of example code (my Bible) from
The Pragmatic Bookshelf.
2. From eclipse->DDMS, get the file in data/data/Events/databases/events.db
3. eclipse->DDMS->top corner, Click on Pull a file from the device, put it on your
windows desktop, then click on Push a file into the device.

Mark Sherman | January 26th, 2010

Thanks for this post. It really helped us with our project.


Mark

vantan | January 26th, 2010

Hi all !
I have got a file /sdcard/data.db .How to insert record into file data.db

Joakim Lodn | January 28th, 2010

In order to waste less space, you should first compress your database file.
Then just reaplce:

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

17/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

//Open your local db as the input stream


InputStream myInput = myContext.getAssets().open(DB_NAME);
with
//Open your local db as the input stream
GZIPInputStream myInput = new GZIPInputStream(
myContext.getAssets().open(DB_NAME) );
for gzip or if you use zip
//Open your local db as the input stream
ZipInputStream myInput = new ZipInputStream(
myContext.getAssets().open(DB_NAME) );
myInput.getNextEntry();

Joakim Lodn | January 28th, 2010

My previous post on compressing the database to save storage space will not do
much, since the apk is compressed anyway.
But you can still use this method as a convenient method to shrink the file under
the 1MB limit (or you can just split the file in 1MB chunks and put it together when
copying).
Cheers!

Achie | February 2nd, 2010

Hello,
It is a nice and a very helpful tutorial. Thank you.
I have seen a couple of replies here which say that we can split large database
files and then join them on the device. I need to implement it since my database
size after compression is around 3MB.
Can some one also let me know how to split and join large files?
Thank you.

darkdusky | February 3rd, 2010

Hi, Ive followed the tutorial but cannot get it working. It crashes in the method
copyDataBase(), on the line:
OutputStream myOutput = new FileOutputStream(outFileName);
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

18/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

I tried the 2 suggestions of checking directory exists (if (!f.exists()) {f.mkdir();})


and this.close();. But neither worked. How do I check the error logs in emulator?
This is my first Android app, so sorry for basic question.

darkdusky | February 3rd, 2010

RE: size of db file I thought this link might be useful:


http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html
If the db file contains any fragmentation the easiest way is to copy its contents to
a new file (data is copied into a new unfragmented db)
(DOS / Win prompt)
> echo .dump | sqlite file1.db > file1.sql
> sqlite file2.db sqlite file1.db .dump > file1.sql
> sqlite file2.db < file1.sql

darkdusky | February 3rd, 2010

Found how to read log adb logcat >C:templog.txt


The error during copydatabase is:
W/System.err( 704): Cant dispatch DDM chunk 4d505251: no handler defined
E/Database( 704): sqlite3_open_v2(/data/data/MyApp/databases/main,
&handle, 1, NULL) failed
Using Google I found 4d505251 is hex for MPRQ, or Method PRofiling Query. But
still have no solution.

Mike Stubber | February 9th, 2010

Hi, thank you very much for this great tutorial!

sephy | February 11th, 2010

Thx for the tuto, but is there another way than with adb shell to see the folder
containing the database with the emulator?
Because, I cant find it on diskand to use SQLite browser i need to specifit the
place of the folder
Help plz

Dman | February 15th, 2010

I have some Newb questions:

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

19/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

The second half of the tutorial says declare the new helper like this:
DataBaseHelper myDbHelper = new DataBaseHelper();
However the error I get is that there is no constructor that takes no arguments.
So then I create my object all in one line:
DataBaseHelper myDbHelper = new DataBaseHelper(this);
Then I try to invoke this function:
myDbHelper.createDataBase();
And it says:
Syntax error on token createDataBase, Identifier expected after this token
What am I doing wrong?
Thanks!
Dman

Mikey | February 23rd, 2010

Just so that you know, god kills a kitten every time you write code such as this:
return checkDB != null ? true : false;
All you actually need to write is this:
return checkDB != null;

Barhoumi | March 6th, 2010

Hi!!
ive followed all the stapes youve indicated
ive created a database baseSQLite.db contain 3 tables and the meta one
ive COPIED the code of dataHELPER in a class called BDAccess
ive created an activity containin a textViw label that will indicate the
establishement of connexion to the database or the error msg
ive placed the database file into the asset folder
changed the name of DB_NAME (without puttin the extension .db
in the activity ive created an instance of the BDClass , in one line cause ive not a
constructor that accept no arguments
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

20/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

but i got an error while launchin, the app is not respondin and ive got to force it
to close
ive checked the /DATA/DATA. it contains the database but i dont know if its
empty (have you an idea how to check this)???
what shall i do
and THANKS!!!!!!

dalf | March 21st, 2010

Hi,
I got the same kind of error android.database.sqlite.SQLiteException: no such
table: recipes: , while compiling: SELECT _id, recipe_name FROM recipes
When debugging, I could see that checkDataBase() return true when running
the application for the first time.
Or it should return false!!

Benjamin Orchard | March 24th, 2010

I am trying to implement your method above, and it gives me a serious error:


When I try to access the activity that calls the DataBaseHelper class, it tells me
the app has stopped unexpectedly and crashes.
Here is my code that I used in DataBaseHelper
package com.TBOM;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper{
private static String DB_PATH = /data/data/TBOM/databases;
private static String DB_NAME = BOM;
private static SQLiteDatabase myDB;
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

21/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

private final Context myContext;


public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext=context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDB();
if(dbExist){
}else{
this.getReadableDatabase();
try{
copyDB();
}catch (IOException e) {
throw new Error(Database could not be copied);
}
}
}
private boolean checkDB(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}catch (SQLiteException e) {
//database does not yet exist
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDB() throws IOException {
//open local as input stream
InputStream myInputStream = myContext.getAssets().open(DB_NAME);

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

22/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

//path to newly created && empty db


String outFileName = DB_PATH + DB_NAME;
//open empty db as output stream
OutputStream myOutputStream = new FileOutputStream(outFileName);
//transfer bytes
byte[] buffer = new byte[1024];
int length;
while ((length = myInputStream.read(buffer))>0){
myOutputStream.write(buffer, 0, length);
}
myOutputStream.flush();
myOutputStream.close();
myInputStream.close();
}
public void openDB() throws SQLiteException{
String myPath = DB_PATH + DB_NAME;
myDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close(){
if(myDB != null)
myDB.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

23/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

}
}
I am calling like such:
public class Game extends Activity {
@Override
public void onCreate(Bundle Game) throws SQLException{
super.onCreate(Game);
setContentView(R.layout.game);
DataBaseHelper myDbHelper = new DataBaseHelper(this);
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error(Unable to create database);
}
try {
myDbHelper.openDB();
}catch(SQLException sqle){
throw sqle;
}
}
}
ANY suggestions on this would be extremely helpful.
Thanks.

chouk | March 26th, 2010

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

24/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

at this line : DataBaseHelper myDbHelper = new DataBaseHelper();


I found an error and precisely at semicolon

Ayub Malik | March 26th, 2010

Hi, thanks for this article was useful as I was struggling to get my database up
and running.
Ayub Malik

Vikram | March 31st, 2010

I am using this and the db works fine. I am facing problems with the upgrade. i
added a piece of code so that the db is set with the version #, the first time its
created. Even after changing the VERSION #, onUpgrade never gets called. Any
clue why ?

tony ob | April 2nd, 2010

Hi,
I moved the testDB into the projects assets folder but I get FileNotFound on
the getAssets().open(DBName) line.
I am using the Eclipse and the Emulator. If I getAssets().list(/) the file is not
shown (but there are entries for res and assets) but
getAssets().list(/assets) is empty.
Any ideas would be greatly appreciated.
tob

tony ob | April 2nd, 2010

Never mind I found this (finally) elsewhere


To get an ASSETS folder into your APK:
In /nbproject/project.properties, change
assets.dir=
to
assets.dir=assets
assets.available=true
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

25/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

In /nbproject/build-impl.xml, there is line in the if=assets.available target that


reads
that needs to be changed to

Ashish | April 8th, 2010

i m getting problem when i m trying to copy database from the assets folder
i got warning like Table Table_Name not exist
i am using eclipse IDE
Thnkks for help

Anders | April 12th, 2010

You can use SQLite Manager Eclipse Plugin here


http://code.google.com/p/questoidsqlitemanager/

iantila | April 14th, 2010

Can you give your code ,we cannot help you winthout code

khanhDQ | April 20th, 2010

This is my code for import android database from mysql database. Im using SQL
Data Browser tool to import but it dont work. Please help me.
CREATE DATABASE IF NOT EXISTS andorid;
USE andorid;
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`id_province` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_category_1` (`id_province`),
CONSTRAINT `FK_category_1` FOREIGN KEY (`id_province`) REFERENCES
`province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)
DROP TABLE IF EXISTS `item`;
CREATE TABLE `item` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

26/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

`name` varchar(100) DEFAULT NULL,


`address` varchar(200) DEFAULT NULL,
`image` varchar(45) DEFAULT NULL,
`url` varchar(200) DEFAULT NULL,
`tel` varchar(45) DEFAULT NULL,
`fax` varchar(45) DEFAULT NULL,
`id_category` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_item_1` (`id_category`),
CONSTRAINT `FK_item_1` FOREIGN KEY (`id_category`) REFERENCES
`category` (`id`)
)
DROP TABLE IF EXISTS `province`;
CREATE TABLE `province` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
)

kondortek | April 20th, 2010

Thanks, this is a really useful method, it populates the db very quickly as


compared to using a bunch of sql statements. Has anybody figured out how to
upgrade after using this method though? I figured out how to get the onUpgrade
method to fire, but then what? If I try to just call createDataBase again it blows
up. Any ideas?

kondortek | April 20th, 2010

to clarify, Im trying to completely recreate the db from a new file in assets. What I
would like to happen is, if the user already has my db, I want to delete it
completely and start over with the new one.

kondortek | April 20th, 2010

ok I think I solved my own problem, just in case anybody else is wanting some
direction Ill post my changes:
/**
* Creates a empty database on the system and rewrites it with your own
database.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

27/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
Log.d(TAG, db exists);
// By calling this method here onUpgrade will be called on a writeable database,
// but only if the version number has been bumped
this.getWritableDatabase();
}
dbExist = checkDataBase();
if (!dbExist) {
//By calling this method and empty database will be created into the default
system path
//of your application so we are gonna be able to overwrite that database with our
database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error(Error copying database);
}
}
}
then in onUpgrade:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
myContext.deleteDatabase(DB_NAME);
}

Keith | April 22nd, 2010

When attempting to open the database, I get Database not found.


private static String DB_PATH = /data/data/HelloListView/databases/;
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

28/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

private static String DB_NAME = ListDb;


The db is in the assets directory and is showing in the package explorer window.
I saw above the post about changing the assets= , however I dont see in eclipse
any places to make these changes. /nbproject/project.properties is this a Unix
thing.. anyway, I cant find where to make the changes.
If this is the solution, can someone post a bit more infor on making these updates
in Eclipse (on a windows system). Ive done a google search on how to update
these and come up blank.

nike jordan shoes | April 23rd, 2010

Hello everyone thanks for


good information.

kondortek | April 24th, 2010

Keith: are you sure this path is right? private static String DB_PATH =
/data/data/HelloListView/databases/;
this should be /data/data//databases
so, for example, if your package is com.example.hellolistview, the path would be
/data/data/com.example.hellolistview/databases/
hth,
Evan

kondortek | April 24th, 2010

edit: should be /data/data/fullpackagename/databases


sorry the brackets didnt show up

harry | April 24th, 2010

I have used this code and it throws an IOException when it reaches


while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
in the copyDataBase() method
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

29/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

any suggestions? im stuck

harry | April 24th, 2010

I checked the number of bytes available with myInput.available() and it gives the
correct number of bytes in the asset file. But when I call the myInput.read(buffer)
it throws IOException. How to sort this out?

Pablo | April 26th, 2010

kondortek can you explain how can i trigger onupgrade methods ? And can you
explain your solution ? Thanks !

ulf | April 26th, 2010

Odd, I followed the instructions but when I do my rawQuery like SELECT title
FROM titles WHERE title LIKE searchKeywords LIMIT 7, I keep getting an error
04-26 09:39:33.408: INFO/System.out(236):
android.database.sqlite.SQLiteException: no such table: titles: , while compiling:
SELECT title FROM titles WHERE title LIKE hy% LIMIT 7. The primary key of
table titles has been renamed _id, the dtabase is found in assets and copied
nicely. What could be wrong?

Martin | April 26th, 2010

Im facing the same problem as Ulf.


Connecting to the database works fine as when i Log at some points it says that
db is opend correctly.
But when i start retrieving some data it gives errors back.
This is my get all users functie that I made in the dbhelper
public Cursor getAllUsers()
{
return myDataBase.query(DATABASE_TABLE_USERS, new String[] {
KEY_ROWID,
KEY_EMAIL,
KEY_PASS,
KEY_NAME},
null,
null,
null,
null,
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

30/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

null);
}
In my mainActivity file i run this code under my db connection wich is explained in
the above tutorial :
Cursor users = myDbHelper.getAllUsers();
users.moveToFirst();
int gebruikers = users.getCount();
Log.w(TAG,Users+ gebruikers);
It already gives an error on the first line Cursor users, the error is :
ActivityThread.PerformlaunchActivity
Source not found.
Anyone got a fix for this or some tips on how to get the data out of the database?
Thanks in advance

Rohit | April 27th, 2010

Hi All,
I want to upgrade the sqlite database to SQLite 3.6.23 to avoid a database
corruption problem. How do i do this?
Above we are copying a sqlite database file from assets to actual location, what I
want to know is that how can I change the sqlite version?
Following is the site and the extract to avoid database corruption
http://osdir.com/ml/sqlite-users/2010-04/msg00090.html
Statically link your application against SQLite 3.6.23 instead of
using the SQLite 3.5.9 that is found on Android. The bug you are
hitting was fixed in SQLite 3.6.2.
Cheers,
Rohit

JIm | April 30th, 2010

Im with Harry on this one. I get IOException on the read of the assets file. Ive
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

31/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

tried variations of getAassets().open and myInput.read all to no avail. I suspect


this is somewhat off topic for the primary purpose of the thread namely copying
a database but seems to have something to do with reading assets in general
from an apk. Any suggestions here?

JIm | April 30th, 2010

Well I solved it
The problem is that my DB is sort of largish (> 1MB). It seems that it is
compressed and that causes confusion in the Android read on the InputStream.
The trick is to rename your asset to a file that the packager will NOT try to
compress. Renaming my db file from xxx.db to xxx.mp3 did the trick
GAG!

The Orz | May 1st, 2010

Thanks Jim! That was also my problem and your solution solved it for me.

Arun Pachauri | May 19th, 2010

Hello everyone..
anyone can tell me how can we execute insert , select , delete & update query
from own database.

Dan | May 23rd, 2010

How do you manage database version upgrades? This solution doesnt seem to
call the onUpgrade() method when the database version number changes
Thanks!

Kiran | May 25th, 2010

Hi,
I am new to android,I am trying to do database apps.I followed the instructions as
specified you people.I am not able to run my applications.
I want to know where can i find the db file weather created or not.If not so,What
should I do?
package com.softforceapps.FinPlanner;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

32/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataHelper extends SQLiteOpenHelper{
private static final String TAG = null;
private static String DB_PATH = /data/data/myapps/databases;
private static String DB_NAME = myapps;
private static SQLiteDatabase myDB;
private final Context myContext;
public DataHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext=context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDB();
if(dbExist){
Log.d(TAG, db exists);
this.getWritableDatabase();
}else{
this.getReadableDatabase();
try{
copyDB();
}catch (IOException e) {
throw new Error(Database could not be copied:);
}
}
}
private boolean checkDB(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}catch (SQLiteException e) {
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

33/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

//database does not yet exist


}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDB() throws IOException {
//open local as input stream
InputStream myInputStream = myContext.getAssets().open(DB_NAME);
//path to newly created && empty db
String outFileName = DB_PATH + DB_NAME;
//open empty db as output stream
OutputStream myOutputStream = new FileOutputStream(outFileName);
//transfer bytes
byte[] buffer = new byte[1024];
int length;
while ((length = myInputStream.read(buffer))>0){
myOutputStream.write(buffer, 0, length);
}
myOutputStream.flush();
myOutputStream.close();
myInputStream.close();
}
public void openDB() throws SQLiteException{
String myPath = DB_PATH + DB_NAME;
myDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close(){
if(myDB != null)
myDB.close();
super.close();
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

34/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
myContext.deleteDatabase(DB_NAME);
}
}
and i am calling this DataHelper class methods as
DataHelper myDbHelper = new DataHelper(this);
myDbHelper = new DataHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error(Unable to create database);
}
try {
myDbHelper.openDB();
}catch(SQLException sqle){
throw sqle;
}
I want to create a table I have to do insert/select/update tasks in my table
CREATE TABLE preferences ( id INTEGER PRIMARY KEY, inflation NUMBER,
pmntNotificationDays INTEGER, date_format INTEGER, roi NUMBER)
INSERT INTO preferences (id,inflation,pmntNotificationDays,date_format,roi)
VALUES (1,1.85,1,3,3.5)
SELECT * FROM preferences;
I have to do these 3 operations
Could any help mePlease.
TQ
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

35/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

petershine | May 28th, 2010

Hi! Everyone,
Iam trying to use a large DB file. Its as big as >8MB
I built it using sqlite3 in Mac OS X, inserted UTF-8 data(for I am using Korean),
added android_meta table with ko_KR as locale, as instructed above.
However, When I debug, it keeps showing IOException at
length=myInput.read(buffer).
I suspect its caused by trying to read a big file. If not, I have no clue why.
I tested the same code using much smaller text file, and it worked fine.
Can anyone help me out on this? Ive searched many places, but no place gave
me the clear answer, or good solution.
Good meaning efficient or easy.
I will try use BufferedInput(Output)Stream, but if the simpler one cannot work, I
dont think this will work either.
Can anyone explain the fundamental limits in file input/output in Android, and the
right way around it, possibly?
I will really appreciate anyones considerate answer. Thank you.

yoppy | May 29th, 2010

@petershine
the maximum asset file that the InputStream read is 1024Kb,
so if your DB file big as >8MB its seem like impossible to push the DB to your
APP
CMIIW

lenin | June 2nd, 2010

@darkdusky: I had the same problems and tried all the same things as you did,
but it turned out that in my case, opening FileOutputStream threw an exception
because my package name (after /data/data/) was wrong in DB_PATH.

mm | June 3rd, 2010

how to call onUpgrade method and replace existing database with new
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

36/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

version..????

Lorenz | June 8th, 2010

Hi, thanx for the tutorial. It really helps for beginners like me on how to create
preloaded sqlite db.
Keep up the good work.

kumar reddy | June 8th, 2010

hi good morning,
i want learn android.can you seggest what are prerequisite to android and i would
like to know best institute.
thanx,
please suggest me to learn android.
have a good day.

ganesh | June 8th, 2010

thanks for sharing this informative post.In your post you have accessed the
DataBaseHelper class by below code
DataBaseHelper myDbHelper = new DataBaseHelper();
myDbHelper = new DataBaseHelper(this);
try

myDbHelper.createDataBase();
.
try
.
myDbHelper.openDataBase();
..
//start using to query db
myDbHelper.query(..);
In few other sample programme which i came across uses code like below
DataBaseHelper myDbHelper = new DataBaseHelper();
SQLiteDatabase db = myDbHelper.getReadableDatabase();
//stat using to query
db.query(..);
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

37/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

instead of calling DataBaseHelpers createDataBase and openDataBase


can you point out the difference between those two ,and while importing db you
asked to add underscore to id column name ,i cannot guess the reason for that.
I will be glad to know the answer .
thanks
ganesh

Deaviato | June 11th, 2010

can anyone site a solod example on how to import SQLite database from android
to my local server..thanx

Amol Pathak | June 12th, 2010

NICE ARTICLE

Desmond | June 17th, 2010

Future classic.

fred pepito | June 23rd, 2010

This is a great post/article. The code works for me. It save me a lot of time.
Thank you very much.

david | June 24th, 2010

Peter shine posted that his db was large (>8mb)


Mine is about 5 mb.
Yopi said:
May 29, 2010 at 2:43 am
@petershine
the maximum asset file that the InputStream read is 1024Kb,
so if your DB file big as >8MB its seem like impossible to push the DB to your
APP
CMIIW
on the file explorer, on my /data/data/package_name/databases the file size is
3072 bytes
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

38/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Why is not the file being moved completely to the assets folder in the package?
also:
tony ob says:
April 2, 2010 at 11:00 pm
Never mind I found this (finally) elsewhere
To get an ASSETS folder into your APK:
In /nbproject/project.properties, change
assets.dir=
to
assets.dir=assets
assets.available=true
In /nbproject/build-impl.xml, there is line in the if=assets.available target that
reads
that needs to be changed to
But using exclipse i cant see where to modify this info
PLEASE HELP

david | June 24th, 2010

tony ob says:
April 2, 2010 at 11:00 pm
Never mind I found this (finally) elsewhere
To get an ASSETS folder into your APK:
In /nbproject/project.properties, change
assets.dir=
to
assets.dir=assets
assets.available=true
In /nbproject/build-impl.xml, there is line in the if=assets.available target that
reads
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

39/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

that needs to be changed to.. (posts ends like that)

but i cant see where to modify this eclipse


Please help a poor beginner
~dh

moon | June 25th, 2010

Good morning everybody thank you for your help but I have a really problem I
cant open my database yet I used the same program .If there is someone who
solved the problem could send me his program.
Please help me its urgent

androidboy7 | June 28th, 2010

You ROCK!!! Instructions worked FLAWLESSLY!


@dalf
Your return statement should be the query itself. In my project, it looks like this:
return myDataBase.query(TABLE_NAME, FROM_FREE, null, null, null, null, null);
Dont forget to declare your objects. In my case it looks like this:
public final String TABLE_NAME = museums;
And for the query, it looks like this:
private static String[] FROM_FREE = {KEY_ROWID_01, KEY_MUSEUM,
KEY_ADDRESS, KEY_ADMISSION};

androidboy7 | June 28th, 2010

@moon
Send me an email at androidboy7@yahoo.com

Tim | June 29th, 2010

I keep getting the following error. Sounds like a few others are having the same
issue.
06-28 21:29:39.556: ERROR/AndroidRuntime(5701): Uncaught handler: thread
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

40/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

main exiting due to uncaught exception


06-28 21:29:39.556: ERROR/AndroidRuntime(5701):
android.database.sqlite.SQLiteException: no such table: Wine: , while compiling:
SELECT DISTINCT _id, varitial FROM Wine WHERE type=1
I run the same query in SQLite Database Browser and it works fine.
Database is in the assets folder.
Any help would be greatly appreciated.
Eclipse IDE 3.4
Android 2.1

androidboy7 | June 29th, 2010

I think I know where youre problem is. Heres my code with my query.
Documentation kinda blows on querying SQLite with Android. KEY_TYPE is the
same as your type. Instead of using like you would use = .
Let me know if it works. If it doesnt, send me the code snippet at
androidboy7@gmail.com
public Cursor listArt(){
return myDataBase.query(TABLE_NAME, FROM_MANSIONS, KEY_TYPE +
like %art%', null, KEY_MUSEUM, null, KEY_MUSEUM);
}

mahesh | July 3rd, 2010

To make this code work on an Upgrade, we need to call


this.getWritableDatabase()
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
this.getWritableDatabase();
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

41/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Joe Masilotti | July 6th, 2010

Thanks SO much for this great post! Is really helping me move along with the
application I have been making.
If it helps anyone else, I got the onUpgrade to work.
In the DataBaseHelper class:
Add a global variable:
private static final int DATABASE_VERSION = 1;
Change the constructor to:
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
Change the createDataBase to (thanks @kondortek):
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
Log.v(DB Exists, db exists);
// By calling this method here onUpgrade will be called on a
// writeable database, but only if the version number has been
// bumped
this.getWritableDatabase();
}
dbExist = checkDataBase();
if (!dbExist) {
// By calling this method and empty database will be created into
// the default system path of your application so we are gonna be
// able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error(Error copying database);
}
}
}

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

42/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Change onUpgrade to:


public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
Log.v(Database Upgrade, Database version higher than old.);
myContext.deleteDatabase(DB_NAME);
}
Now if you attach a newer version of your database and change
DATABASE_VERSION, it should re-copy the database.
Work for anyone else?

harry | July 8th, 2010

How can I put my larget DB( 5MB) into my android?


@petershine & @david
Do you solve this problem??

Rodney | July 10th, 2010

Hi this page is really helpful. Thank you all

Karl | July 15th, 2010

This was really helpful. Thank you.

SteveC | July 18th, 2010

Thanks for this helpful article. Perhaps Im missing something but shouldnt the
original assets be deleted to avoid duplicate/redundant data storage utilization?

jiqqaman | July 19th, 2010

I dont see example on reading

androiddev | July 20th, 2010

Thanks for this wonderful example.This is example was very helpful to me.plz
help me hw can i copy large DB(30MB) from assests folder to database
folder.Above example is giving problem.plz..help me

Victor | July 20th, 2010

Thank you for your post. It was helpful so far. E encountered a problem when
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

43/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

trying to query the DB and the application simply crashes. I only added a line at
the end of your code:
Cursor result = dbHelper.myDataBase.rawQuery(SELECT * FROM Networks,
null);
and it seems to crash the entire app. Everything goes well until the program
reaches that line. Do I have to add any permission to the manifest file to be able
to query the DB?

Christina | July 24th, 2010

I keep getting the no such table error when I try to perform a select, update, or
insert statement against the database. Ive read all the comments on this page
regarding this error, but none have solved the problem. Any suggestions?

James | July 24th, 2010

How do you handle tables with an aggregate key?

James | July 24th, 2010

Disregard

Prerna | July 26th, 2010

Hi When I am trying to delete the database the -id value is not resetting to 0.
Hence when I add data again the values are added to the inceemented _id and
Hence when I am trying to access the first row value I am not able to do so as
there is no _id by that number.

Nemanja | August 10th, 2010

I had same problem with application crash when trying to operate with database.
I think I have a solution (at least it works for me):
at the end of createDataBase() method I put this.close().
I think this is forcing the app to reaopen (copied) database, cause without this, its
working with empty database
(opened before copying with this.getReadableDataBase()) and thats why it cant
find (existing) tables.
Hope this helps
Cheers
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

44/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Zayar | August 13th, 2010

Its really useful.I put my database file (.sqlite) into assets folder. Umm, but i got
error message: that file encrypted or not a database.
I hope your help..

SkyDiver | August 15th, 2010

That hit the spot! Excellent article!!!


(*) My app runs with no problems even if I dont add the extra table or change to
_id.

Kenny | August 22nd, 2010

I noticed that the methods added dont over ride or in anyway hook into the
OpenHelper. Wy dont you hook into the onCreate() over-ride?

Jake | August 30th, 2010

Hey guys/girls,
I was able to get this working and after reading the follow-up, thought I would
post a couple things here:
Not sure if it is the most efficient but it works without issues and was tested in
HW.
1) Reading: Get the database and set the cursor using query. This example just
displays the returned database values into a listview
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null,
ORDER_BY);
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.fourteener_item, cursor, FROM_OUT, TO);
setListAdapter(adapter);
registerForContextMenu(getListView());
2) Updating database. I would like to keep updating this pre-loaded database
with fields and thus needed a way to update the database without copying it over
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

45/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

everytime the app loaded. I created a static int representing the database version
and then checked to see if was updated:
private static final int DATABASE_VERSION = 3;
In checkDataBase(), I added the following lines:
if(checkDB != null){
if (checkDB.getVersion() != DATABASE_VERSION) {
checkDB.execSQL(DROP TABLE IF EXISTS + TABLE_NAME);
checkDB.close();
return false;
} else {
checkDB.close();
return true;
}
} else {
return false;
}
This way, the database doesnt get copied over everytime. However, the updated
DB will replace the current one if the version
was updated. I tried doing this by overriding onUpgrade() but could never get it to
work.
Hope this helps someone. If there is a more efficient way to do this, I would love
to hear about it.

Ace | September 1st, 2010

Hello Jake
Could you explain how I can implement the code example you have implemented
above?
I Dont understand how you can use FROM_OUT, TO and still get the code to
compile. Are these supposed to be strings?
Does anybody know how I can query the database once I have set up as above?

Jake | September 1st, 2010

Hello Ace,
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

46/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Those are strings.


ORDER_BY = FIELD_NAME + ASC; // also a string that states how to order the
list
private static String[] FROM_OUT = { FIELD_NAME }; // this is the field name you
want to display in a listview
private static int[] TO = { R.id.title}; // this maps to the textview which corresponds
to each item in the list
Hope this helps.
Jake

gundesli | September 3rd, 2010

To Will and David Weaver i had same error too (no such table ).The error is
occuring because of you are not using the name of your database correctly.You
need to include file extention in the name, for example DB_NAME = test.db.

Michelle | September 9th, 2010

I guess I dont really understand databases after all. In order to just create a
database using
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
am I supposed to have SQLite installed on my computer?

Bjrn L | September 26th, 2010

Thanks for a great tutrial. I really like this approach instead of dealing with actual
SQL-code. I wonder though if the copy db approach is recommended when doing
an upgrade of database, or its better to do a drop table/create table/insert into
procedure then? Does anyone have any thoughts on this?

ravi | September 27th, 2010

hi can u provide sample code for retrieving the EditText data stored in DB sqlite
android

Max | September 29th, 2010

Nice post, helped me some way.


http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

47/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

I like to work simple and lazy so the ideo of building a new private class was quite
frustrating to me.
I tried to use the static member of SQLiteDatabase
openOrCreateDatabase(string path, CursorFactory)
but could not make it work simply providing the name of the database. I guess,
android tried to create it at the root :(.
Thanks to you it occured to me that I had to provide the package database path
and tried this way:
say that I called my package app.myApp
string DB_PATH = /data/data/app.myApp/databases/
string DB_NAME = theDatabase
SQLiteDatabase myDB = SQLiteDatabase.openOrCreateDatabase( DB_PATH +
DB_NAME, null );
then you can continue accessing your database with classical SQLite queries,
creating a table for exemple:
myDB.execSQL(CREATE TABLE IF NOT EXISTS myTable +
(ID INTEGER PRIMARY KEY AUTOINCREMENT, +
name TEXT));
adding data to the table:
string aName = harry;
myDB.execSQL(INSERT INTO myTable(name) +
VALUES( + aName + ));
fetching information:
Cursor cTemp = null;
try{
cTemp = myDB.rawQuery(SELECT ID, Name FROM myTable ORDER BY
ID,null);
}
catch (SQLiteException exception){
Log.e(DatabaseAccess, exception.getLocalizedMessage());
return null;
}
the Log.e command is usefull to debug the program, it is part of the package
imported with import android.util.Log;
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

48/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

the exception is launched when there is an access issue, it is also very usefull.
after playing with you database, you may want to close it:
myDB.close();
there my be some code mistakes, but I know that I would have be happy to find
those informations a month before.

keith | September 30th, 2010

Max I liked your idea but I cant get it to work. The program wont read the
database file directly from the asset folder the way you wrote things. The DB file
in assets still has to be moved into the database folder of the program. I was
hoping your way would work because its much simpler and the whole idea of
using bytestreams just seems like fancy overkill, but so far I cant find a simpler
way to do this.

kailash | September 30th, 2010

great it worked on my motorola phone. thanks for help

Abhishek | October 4th, 2010

Hello Guys,
Can anybody help me with the updatation of the Sqlite DAtabase file. I can
access the file for fetching the querys. I can also get the data after inserting.
But the problem is that the database file is not getting updated. I can see the data
after inserting.
Can any body help me with this
Inserting the data with the following code.
public void onInsertTable(String strInsert)
{
try
{
this.getWritableDatabase();
// getWritableDatabase().execSQL(strInsert);
sdbDatabase.execSQL(strInsert);
}
catch (Exception e)
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

49/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

{
e.printStackTrace();
// TODO: handle exception
}
}

Abhishek | October 7th, 2010

I there anybody solve the above problem

Ralf | October 9th, 2010

In my version of the programme, the checkDataBase() always yielded true. I


then used this instead, which works:
private boolean checkDataBase2() {
SQLiteDatabase checkDB = null;
boolean isnull = false;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database doest exist yet.
}
if (checkDB != null) {
isnull = true;
checkDB.close();
}
return isnull;
}

Ralf | October 9th, 2010

Sorry folks, the reason why checkDataBase() always yields true was that I put
db = myDbHelper.getReadableDatabase();
somewhere before myDbHelper.createDataBase();
I didn*t know that myDbHelper.getReadableDatabase() already creates an empty
database (almost-empty, except the android_metadata table) of the same name.
Anyhow it works now. Cheers.

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

50/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Bjrn L | October 11th, 2010

Have anyone got overridden function onUpgrade() to be called when upgrading


your application and increasing the database_version?
Also, Juan-Manuel maybe you should include a database_version and not only
version 1 in the constructor of the class? If you have a way to implement the
onUpgrade() override, please post it. Would be highly appreciated.

Txema | October 15th, 2010

Great article!
Why dont you just check if the database file exists?
private boolean checkDataBase() {
String myPath = DB_PATH + DB_NAME;
return new File(myPath).exists();
}

Txema | October 15th, 2010

Another improvement.
You can use myContext.getDatabasePath(DB_NAME) to dynamically get
database path instead of hardcoded DB_PATH.

Jrg | October 20th, 2010

Hi,
if you run into the following error:
Caused by: java.io.IOException
E/AndroidRuntime( 7315): at
android.content.res.AssetManager.readAsset(Native Method)
E/AndroidRuntime( 7315): at
android.content.res.AssetManager.access$700(AssetManager.java:35)
E/AndroidRuntime( 7315): at
android.content.res.AssetManager$AssetInputStream.read(AssetManager.java:540)
then take a look at http://ponystyle.com/blog/2010/03/26/dealing-withasset-compression-in-android-apps/
The bottom line: just give the DB a file extension of files that wont be
compresses (e.g. *.jpg, etc.)

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

51/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

kishore | October 21st, 2010

Hi I tried your code, there is an error while creating instance for DataBaseHelper
class and call the createDataBase() and openDataBase() methods,
it says The constructor DataBaseHelper() is undefined,
DataBaseHelper myDbHelper = new DataBaseHelper();
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error(Unable to create database);
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
}
}
wat to do, help me.

Glenn | October 24th, 2010

/*
I found that Db in a lot of cases was being recopied from the assets folder every
time it was accessed. This was because the copied db wasnt updated to reflect
the new (in this case hard-coded) db version.
The way I manage the upgrade of the db is by manually changing my db version
class constant, and then creating a reference to the db file after a successful
copy and using checkDB.setVersion(DATABASE_VERSION) to set the version to
the new DATABASE_VERSION.

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

52/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

This works for me: */


private static final int DATABASE_VERSION = 2; //change this value manually to
force recopy of db
..
private void copyDB() throws IOException
{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
SQLiteDatabase checkDB = null; //get a reference to the db..
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
// once the db has been copied, set the new version..
checkDB.setVersion(DATABASE_VERSION);
}
catch(SQLiteException e)
{
//database doest exist yet.
}
//Close the streams
myOutput.flush();
myOutput.close();
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

53/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

myInput.close();
}
//hope that helps someone out there.

Robb | October 27th, 2010

This page comes up a lot in Android sql searches, so I wanted to add some
feedback that hasnt yet been posted. First of all, if you pass the
SQLiteDatabase.NO_LOCALIZED_COLLATORS flag to the
SQLDatabase.openDatabase call (in addition to OPEN_READONLY), it will avoid
the need to add the Android-specific table android_metadata into your
database. Useful if youre trying to keep your database as platform-independent
as possible. I cant speak to whether renaming your first table field to _id is
really necessary.
Secondly, I was getting exceptions when stepping through copyDatabase when
the InputStream was being read from the assets. Code was fine, database was
fine, so I couldnt for the life of me figure out what was wrong. It turns out that if
your database is somewhere around 1 MB or larger, Android will automatically
compress it if it recognizes your file extension as a text file (.db, .sql, .sqlite, for
instance). The solution for me was to use an extension that the operating system
wont compress, such as mp3.
Now everything works just fine, although it took several hours to debug. I hope
this saves someone else some time!

Thomas | October 27th, 2010

If I publish an update to an app that uses a database, will the update replace the
users current database? Im not sure how the updates work in the android
market, but I hope that they just patch the users current version of the app and
dont replace it.

Toby | October 27th, 2010

kishore, try adding null as argument to new DataBaseHelper(); on first line i.e.
DataBaseHelper myDbHelper = new DataBaseHelper(null);. Worked for me.

Team Roster | October 30th, 2010

Maybe you should make changes to the webpage name title Using your own
SQLite database in Android applications | ReignDesign Blog to more better for
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

54/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

your content you make. I enjoyed the the writing yet.

Mobalick | November 1st, 2010

Hi can anyone please send me a working exemple of this cuz i caint get it
working there always something wrong

miktr | November 3rd, 2010

I have the same problem as kishore, I tried what Toby suggested but it doesnt
work for me.
DataBaseHelper myDbHelper = new DataBaseHelper(null);
I get the following error:
Syntax error on token ; ,{exptected after this token

slee89 | November 3rd, 2010

Hey Guys,
I am completely new to Android development (just started yesterday). I was
wondering how would you retrieve data from a database and show it in a
spinner?
Your help would be very much appreciated!

soni | November 3rd, 2010

Hi.
When i use this code i have same problem so please tell mi below code where
we put
DataBaseHelper myDbHelper = new DataBaseHelper();
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
}
catch (IOException ioe)
{
throw new Error(Unable to create database);
}
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

55/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

try
{
myDbHelper.openDataBase();
}
catch(SQLException sqle)
{
throw sqle;
}

sanjeev | November 4th, 2010

thanks a lot..

sanjeev | November 4th, 2010

hi soni..
place it where u want ur database to be opened, generally its d main activity of ur
app.
n den u can simply create function in ur databasehelper class n call dem from db
object

Steven | November 6th, 2010

Hi really interesting post, now im a noob and coudent find an example on how to
build queries base on form input anyone got an example or tutorial i could see
the code and get an idea?? would be much apriciated.

kane | November 10th, 2010

Im also very interested about using a database to populate a spinner activity. can
someone help out with this code. Its so hard to find information about using your
own database in the app as opposed to creating the database in the app.
So when you say
2. Copying, opening and accessing your database in your Android application.
Now just put your database file in the assets folder of your project and create a
Database Helper class by extending the SQLiteOpenHelper class from the
android.database.sqlite package.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

56/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

what exactly do you mean by put your database in the assets folder?
Thanks
kane

miktr | November 11th, 2010

kane: Take your database e.g myDb.db and copy it to


/workspace//assets/myDb.db
Now you will see the database in the assets-folder in your project..

Noliuz | November 16th, 2010

very helpful. thank you

kane | November 17th, 2010

Hey all, this is a great article but its still not very clear for a newbie.
Can someone take this code and improve and test on Eclipse and post the
working code with all the .java and .xml code from their Eclipse. So we can
understand how this database could for instance display the database info in a
simple list view, or populate a spinner. This site is very popular in all forums so I
think it would be nice if it actually help newbies understand what they are doing.
I dont know where to add this code for instance. Is it a separate class from the
main oncreate() class?
Thanks, I bet you that a lot of people would appreciate it.

thefsfempire | November 22nd, 2010

@kane I had the same problem as you. The article shows you how to transfer the
database from assets to the device in /data/data but does not show you how to
query the database and populate a listView. I learned how to do this by following
the guide at Sai Geethas blog (link below). The guide shows you how to populate
a listView using data retrieved from a database.
http://saigeethamn.blogspot.com/2009/10/android-developer-tutorial-part12.html

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

57/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Shwetha | November 22nd, 2010

Hi all
I tried executing few programs which extends Activity but am getting error has
The method setListAdapter(SimpleCursorAdapter) is undefined for the type Class
name
My problem is I have an datbase in an seperate class and i want listView inside
an Activity not inside ListActivity .Has my Activity has even other things to display
so i dont want to display in an other screeen
Can anyone please help with sample code
Thanks a lot

Adam Bartlone | November 24th, 2010

Lovely just what I was searching for.

Leeran | November 25th, 2010

Great tutorial!!!!! really helped me out a lot. do you have a tutorial for
reading/writing from/to said database?

AswiniKumar | November 25th, 2010

thanku

albedo | November 27th, 2010

I got error message on querying table that table does not exist although it
definetely exists

quelcom | November 30th, 2010

thanks for the post.


what is the point of..
DataBaseHelper myDbHelper = new DataBaseHelper();
myDbHelper = new DataBaseHelper(this);
is it actually a typo?
I got it working by doing DataBaseHelper myDbHelper = new
DataBaseHelper(this);
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

58/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

DataBaseHelper constructor expects the context anyway.


BR,

Mark | December 2nd, 2010

I am new to Android but know database fairly well. I am trying to understand why
we have to copy the SQLite DB from the assets folder. Why cant it stay in
assets?

Vukasin | December 3rd, 2010

Hi,
I have big problem to implement you class.
Im receiving error in initialization process:
ERROR/AndroidRuntime(280): java.lang.ClassCastException:
com.dict2go.Dict2GO$1
ERROR/AndroidRuntime(280): at com.dict2go.DataBaseHelper.
(DataBaseHelper.java:37)
ERROR/AndroidRuntime(280): at
com.dict2go.Dict2GO$1.onClick(Dict2GO.java:64)
ERROR/AndroidRuntime(280): at
android.view.View.performClick(View.java:2408)
ERROR/AndroidRuntime(280): at
android.view.View$PerformClick.run(View.java:8816)
ERROR/AndroidRuntime(280): at
android.os.Handler.handleCallback(Handler.java:587)
ERROR/AndroidRuntime(280): at
android.os.Handler.dispatchMessage(Handler.java:92)
ERROR/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(280): at
android.app.ActivityThread.main(ActivityThread.java:4627)
Here is my implementation:
public class Dict2GO extends Activity {
private EditText text;
public TextView textView_translation;
public WebView WebView_translation;
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

59/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.Input_word2translate);
textView_translation = (TextView) findViewById(R.id.textView_translation);
Button Button_translate = (Button) findViewById(R.id.Button_translate);
Button_translate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Editable inputText = text.getText();
SQLiteDatabase db = null;
File f = new File(/data/data/com.dict2go/databases/dict2go.db);
Boolean checkIfDbExist = f.isFile();
if (checkIfDbExist.equals(false)) {
try {
DataBaseHelper myDbHelper = new DataBaseHelper(this);
myDbHelper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
Any Idea ?

Neeraj | December 3rd, 2010

I already created a database using SQLite and try to access it using android
project.Unfortunately its not working for me.Will anybody help me for the .As I
followed the tutorial an error occurred-Error in copying Database..I already
copied the database to assets folder.please give me clarification about the
DB_path.

carbi84 | December 7th, 2010

@Neeraj:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

60/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

same for me, did you solve the problem?


anybody else?
any help is highly appreciated

carbi84 | December 7th, 2010

@Neeraj:
for me the second comment on this article helped:
http://huuah.com/using-sqlite-from-your-android-app/
cheers

Gurpreet | December 12th, 2010

I have a sqlite database created with the required tables as mentioned in the
start of this article. I am trying to create a database and then copy all the
contents from database to newly created database. The same way as mentioned
in this article.
But I am having a strange problem. When I uninstall my app from android device,
/data/data/myfoler also gets deleted. This is normal. That means mydatabase file
doesnt exist in android device anymore.
When I try to run the app again on device after installing it, the following line
always can open the database. Even if it didnt exist before.
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
Because of above problem, code doesnt reach to copydata function.
Has anyone faced such issue? Is there any problem with above code?

Sinha | December 14th, 2010

i want to save the data entered in an edittext, in to the database .Can anybody
help me for this.

void | December 15th, 2010

Gurpreet: I have the same issue, am trying to figure it out. do you have solution
yet?
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

61/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Rodrigo Guilfoil | December 16th, 2010

Good post. I recently happened upon your web page and needed to convey that I
have certainly relished reading your webpage posts. Anyways I will be opting-in
to your feed.

Chang | December 25th, 2010

Great post! One question. How to upgrade the database schema in future
versions? It looks like OnUpgrade is not called.

AEHP | January 1st, 2011

Thanks a lot.

Bjrn L | January 7th, 2011

I recently have experienced some troubles with this database distribution


method/usage for users running Android 2.2.1. It works fine with Android 2.2 on
my own device and fine on both 2.2 and 2.3 in the emulator. Is there anyone else
that experienced this and found out what the problem is? I havent had the
possibility to debug it on a 2.2.1-device yet but Ill follow up here if when I find out
whats wrong.

nirmal | January 10th, 2011

How can we perform a comparison between the data entered through an edittext
and that stored in a database,as in the case of a password checking.Can
anybody help me for this.

William | January 10th, 2011

Hi,
I have the same problem as Bjrn L. My application works fine but on the HTC
Desire HD version 2.2.1 (1.72.405.3), the database created but the copy doesnt
work.
It works fine with Android 1.6, 2.2 and 2.2.1 on my own device (HTC Magic) and
fine on both 2.2 and 2.3 in the emulator.
I search a solution but it is difficult without the device.
I hope that we will find a solution.
Best Regards
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

62/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Bjrn L | January 10th, 2011

William: Too bad you have the same problem but good to hear that Im not the
only one. It would be really awesome if someone with a Desire HD could try to do
some debugging and see if they find whats wrong. Ill get hold of a Desire HD
hopefully this weekend and do some debugging then.
I think Ill post to Stackoverflow since theres alot of skilled Android developers
there that might have a clue what might be the cause of the problem.
William and others: Ill post the link to the Stackoverflow-post when its done.
Drop me a line if you want to do som thinking togeather on gtalk or you want me
to let you know directly if I find a solution. Cheers! b dot lindahl (at) gmail dot com

andy80 | January 11th, 2011

Hi,
Im an italian android application publisher.
I have the same problem that you describe in your post. I always use this method
to manage database files in my android applications.
These applications work fine on Acer Be Touch E400 (android 2.1), Samsung
GalaxyTab (Android 2.2), HTC Magic (Android 2.2.1), but not on HTC Desire HD
(Android 2.2.1). Ive received many error advices and bad comments about my
application from this kind of device.
The stack trace is the same: android.database.sqlite.SQLiteException: no such
table: mydata, while compiling: SELECT.;
Can you help me? I dont try to emulate this kind of device.
Bjorn: i wait your post on Stackoverflow. Can you put its link in this post?
Thanks! and sorry for my english.
Bye

Bjrn L | January 11th, 2011

Ive posted a question to Stackoverflow now. I hope its accepted despite its very
specific nature. Heres the link to it as requested:
http://stackoverflow.com/questions/4651797/database-handling-stopedworking-on-android-2-2-1-desire-hd-1-72-405-3

William | January 12th, 2011


http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

63/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

Hi,
we arent alone :).
There are other links:
http://forum.xda-developers.com/showthread.php?t=895942
http://stackoverflow.com/questions/4585790/problem-with-testing-anddebuging-of-android-apps
Best Regards

Will | January 13th, 2011

+1 for the Android 2.2.1 database copy not working. Desire HD users and custom
2.2.1 ROM users get the FC on my app. Any suggestions to fix appreciated. I
have a relatively big populated db that I distribute this way with my app, it would
be crazy to try and script the whole database!

Craig Lurey | January 14th, 2011

having similar problem. I have a lot of Android users and only HTC desire is
causing problems. I believe there is a mismatch between our code and the
libraries in this version of Android. Its creating database files that cannot be read
elsewhere.

Mark | January 14th, 2011

Hi,
at first thanks for this tutorial. I tried to use the DataBaseHelper with a DB larger
than 1MB and i get an error when it comes to copy the file from assets to
database folder:
ERROR/Database(3565): sqlite3_open_v2(/data/data/XXX/databases/test.db,
&handle, 1, NULL) failed
DEBUG/asset(3565): Data exceeds UNCOMPRESS_DATA_MAX (3780608 vs
1048576)
Can anybody give me a hint on how to avoid that?

Bjrn L | January 14th, 2011

@Mark: There are different ways to solve it. Either you can name the database
with a file extension (mp3 for instance) which corresponds to a already
compressed file format, which will tell Android not to uncompress the file.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

64/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

It seem to work if you put the database in the raw folder as well. See this
question for instace: http://stackoverflow.com/questions/2860157/load-filesbigger-than-1m-from-assets-folder

hyunjungsoh | January 15th, 2011

Wow! This has been helpful! Thank you so much!


Ill be sure to study this.
~hyunjungsoh

William | January 15th, 2011

Hi,
I have found a solution thanks to a user of my application.
Here the solution:
http://www.anddev.org/networking-database-problems-f29/missing-tablein-sqlite-with-specific-version-of-desire-hd-t50364.html
Thanks.
Best Regards
William

Bjrn L | January 15th, 2011

That doesnt solve it for me. Im debugging on a Desire HD right now but the
error is when calling getReadableDatabase(). It render in:
getReadableDatabase SQLiteDiskIOException disk I/O error
Not sure why this is but Ill continue to see if I find out whats the problem. If
anyone have an idea I should try, dont hesitate to contact me on gtalk or mail on:
b dot lindahl at gmail dot com
or through the comments here. Cheers!

William | January 16th, 2011

Hi,
warning your error is not the same problem.
you : disk I/O error
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

65/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

me : android.database.sqlite.SQLiteException: no such table: LISTE: , while


compiling: select _id from LISTE
Best Regards
William

nirmal | January 17th, 2011

Hi,
I got the following error while trying to select a record from database table.How
can i solve this.thanks in advance.
01-17 05:08:23.933: ERROR/CursorWindow(767): Bad request for field slot 0,-1.
numRows = 1, numColumns = 5
01-17 05:08:23.951: ERROR/AndroidRuntime(767): Uncaught handler: thread
main exiting due to uncaught exception
01-17 05:08:23.972: ERROR/AndroidRuntime(767): java.lang.RuntimeException:
Unable to start activity : java.lang.IllegalStateException: get field slot from row 0
col -1 failed

Johanovski | January 17th, 2011

Greetings!
Thanks for the tutorial! Im trying to get it working in my app, but Im facing some
problems. Maybe theres quite obvious, but Im a newbie on Java and Android
programming: where is the class Context? It cant be found when I create the
DataBaseHelper class, and I dont which which package I should import
Thanks in advance!

Johanovski | January 18th, 2011

Buf, seems that there are some important errors here Ive coded the whole
example and it seems that works well (no errors are thrown after all), but when I
try to access the DB through a query it crashes as the table doesnt exist (when
in fact it does). The only table that I can access is the android_metadata table
and it shows the default value en_US, when my DB has the es_ES value (so it
proves that in fact its creating a new database)
Ive tried to access the DB in the checkDataBase method and it seems that the
SQLiteDatabase.openDatabase() method creates an empty database, so itll
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

66/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

always return true as if the database really exists, when in fact it should return
that the database doesnt exist and it should be copied in a new DB
Any help with this?

Abhinav | January 21st, 2011

Apparently some people have been able to solve the issue of the
SQLiteException by following the pointers given on this link
http://www.anddev.org/networking-database-problems-f29/missing-tablein-sqlite-with-specific-version-of-desire-hd-t50364.html
Im trying to see if it works for me !

Bjrn L | January 21st, 2011

For me the error occurs already when trying to create an empty database that I
wantt to copy over. Each call to either
this.getReadableDatabase();
or
this.getWritableDatabase();
seem to cause an exception for me.
Anyone else experiencing this?

Nelson F | January 24th, 2011

I was really wasting a lot of time on this problem of my table not being found.
Your fix worked perfectly and there is absolutely no chance that I would have
worked this out for myself, and the folks on Basic4Android (which Im using) didnt
seem to know what was wrong.
Thanks a million! I owe you big time.

Nicolas | January 26th, 2011

Well guys, Ive modified this helper class a little bit. Seems to work just fine if you
have or not the database created on the O.S (its in portuguese sorry, if anyone
has trouble to understand please leave me a note that ill translate it ok?). Here it
goes:
package org.me.mydroidapp;

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

67/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class ControleBD extends SQLiteOpenHelper {
//Constantes
private static final String DB_NAME = mydroidapp; //change this to your
database name
private static final String DB_PATH = /data/data/org.me.mydroidapp/databases/
+ DB_NAME; //change the package name to suit your needs
private static final int DB_VERSION = 1; //leave it this way
private static final String AGENDA_TABLE_CREATE = CREATE TABLE agenda
(id INTEGER PRIMARY KEY AUTOINCREMENT, nome TEXT);; //an example
table
ControleBD(Context c) {
super(c, DB_NAME, null, DB_VERSION);
//if the database does not exists, creates it
if(!checkDB()){
criaDB();
}
}
//Creates the database
public void criaDB(){
//Cria DB
this.getWritableDatabase();
}
//check if the database is already created
public boolean checkDB(){
SQLiteDatabase db = null;
try{
db = SQLiteDatabase.openDatabase(DB_PATH, null,
SQLiteDatabase.OPEN_READONLY);
db.close();
return true;
}catch(SQLiteException e){
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

68/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

return false;
}
}
//An insert method example
public void insereNome(String nome){
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH, null,
SQLiteDatabase.OPEN_READWRITE);
db.execSQL(INSERT INTO agenda(nome) values ( + nome +));
db.close();
}
//A select method example
public Cursor selectNome(){
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery(select * from agenda, null);
db.close();
return c;
}
@Override
public void onCreate(SQLiteDatabase db) {
//Cria as tabelas
db.execSQL(AGENDA_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Nothing to do
}
}
Simple isnt it? Any contribuitions?
Cya
Nicolas
http://www.cacaiada.info (help me to start my forum lol)

Joemarie Amparo | January 26th, 2011

Hello,
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

69/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

I had made a a DB named dbPractice with the table named User and its
attributes: _id,firstName, middleName, and lastName
I save this DB inside my /res folder of the project. My problem is I dont know how
to use/access this DB through codes.
Is this right that I put in
//since i put the db inside the /res folder of the project
private static String DB_PATH = /res/;
//db name
private static String DB_NAME = dbPractice;
?
How am i going to go after here.
Thanks.

Bjrn L | January 28th, 2011

I finally seem to have got my app to work on Android 2.2.1 on Desire HD. I
havent had the chance to debug on it personally to try out exactly whats causing
the problem.
One thought that popped up is the hard coded path to where the database file is
located.
DB_PATH = /data/data/YOUR_PACKAGE/databases/;
Isnt it possible that this isnt valid on Android 2.2.1 for Desire HD? I exchanged
this path with:
Environment.getDataDirectory() + /data/YOUR_PACKAGE/databases/ +
DB_NAME;
which might be a solution to my problem. Ill try to pin point the issue so I can
clear up alot of test code I put in my code up to the point where I got it to run. Ill
post back on this thread when I had the chance to test on the actual phone
myself. If anyone test this solution, please let me know if it solves it.

Brad | February 2nd, 2011

Firstly AWESOME post, this is exactly what Im looking for, and for the complexity
of the problem this solves it is such a simple solution. For those of you having
issues with this code here are some gatchas I ran into.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

70/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

I passed the Contex object required from an activity into this class (trying to be
clever), but I did so by calling the SqlLiteHelper class on instantiation of the
activity. (I know thats muddy.heres what I mean):
public class PlayGame extends Activity {
private SQLHelperClass sqlHelper = new SQLHelperClass(this);
}
The problem is that even though this will pass as a valid Context object, it is not
properly instantiated for the purposes of the SQLiteHelper class (SorryI did not
look into specifically why). The solution looked like this:
public class PlayGame extends Activity {
private SQLHelperClass sqlHelper;
public void onCreate(Bundle savedInstanceState) {
sqlHelper = new SQLHelperClass(this.getApplicationContext());
}
// ..etc
}
I also ran into the same issue mentioned above with the tables not being found
on a droid 2, however I think my issue may have been the result of a file
extension. The sqlite database manager mentioned in the tutorial will
automatically add the sqlite extension to the file in the assets folder, and I stupidly
thought android would just read the file anywayI was wrong. (I know this is
stupidIm not suggesting any one else will make the same stupid mistake but if
they do I hope this saves you the 4 hours I spent figuring it out)
Lastly, in conjunction with the previously mentioned issue, I found with debugging
that I needed to delete the database that had been incorrectly created w/out the
sqlite file I provided before the app would load the file I wanted it to. This is very
straight forward but here is how I did that:
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
SQLiteDatabase db_read = null;
Log.d(DEBUG, Does the database exist already? + dbExist);
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

71/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

if (dbExist) {
// DONT!!!!!! do nothing database already exist
myContext.deleteDatabase(DB_NAME);
// This will surely throw an errorbut your app will no longer be
// aware of the database and you can re-run the app and try again to get
// the sqlite file to load.
} else {
etc
Again, Ill re-iterate that I am in no way suggesting anyone has made the same
mistakesbut if you do I hope this helps a little.
AND THANK YOU FOR A GREAT POST!!!!! A nice solution to a problem I did not
want to solve alone
Brad

Richard | February 2nd, 2011

Hi Guys
DOES NOT WORK. Example code required please.
I have got my database and I run it through the process as above, however,
when i try to access the database it comes up with an error message saying that
the source file not found.
Can someone put some example code up of how they can use their predefined
sqlite database in their android application???
Thanks

Anna | February 4th, 2011

Hi! I am a beginner and I cant get the implementation to work.


DataBaseHelper myDbHelper = new DataBaseHelper();
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

72/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

} catch (IOException ioe) {


throw new Error(Unable to create database);
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
THis part above should be entered in the .java file right? Or from where should I
implement it? I keep getting an error on the first line, have you who have gotten
this to work, figured it out another way?
Best regards, A

Connor Boade | February 6th, 2011

Hello,
The fore-mentioned code does in fact work. It required a couple of tweaks here
and there though, Ill try and get the changes listed by tomorrow.

Ken | February 7th, 2011

Something seems amiss. Ive followed the tutorial accurately (copy-paste and
adjust for my own case).
I can query the android_metadata table, but when I try to query my own words
table from the same file I get a table does not exist exception. The table is there,
and its primary integer key column is called _id.

Ken | February 7th, 2011

The problem is the data from the database file only gets copied in if a database
does not exist at DB_NAME+DB_PATH. However, it certainly does after
checkDatabase is called beforehand; SQLiteDatabase.openDatabase() creates
a database if one does not exist. Consequently copyDatabase() does not get
called.

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

73/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

A fairly immediate fix, with added care, is to just call copyDatabase() in your
createDatabase() method, nothing more.
This should help other posters I noticed who had the same problem.
A database existing and the data being loaded already are not the same thing.
Sorry, I (personally) found this code misleading, frustrating, and it wasted a
chunk of my time.

Thomas | February 9th, 2011

Ken can you give me Ur email, Ive this problem.

Ken | February 9th, 2011

@Thomas: The following works for me, give it a shot. (Dont forget to adapt
package names to suit you etc.) Comment here and Ill get notified. Ill be glad to
help!
//////////////////////////////////////////////////////////////////////////////
package com.SpecialK.MyApp;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class GameDatabaseHelper extends SQLiteOpenHelper {
private final Context mContext;
private static String DB_PATH = /data/data/com.SpecialK.MyApp/databases/;
private static String DB_NAME;
private SQLiteDatabase myDatabase;

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

74/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

public GameDatabaseHelper(Context context, String dbName) {


super(context, dbName, null, 1);
mContext = context;
DB_NAME = dbName + .sqlite;
try {
createDatabase();
openDatabase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void createDatabase() throws IOException {
System.out.println(creating);
//************Create an empty database if one doesnt exist, and always overwrite
regardless!
if (this.checkDatabase()) {
this.copyDatabase();
} else {
System.out.println(error creating database);
}
}
public String queryString (String word) {
String resultString = null;
Cursor c = myDatabase.rawQuery(SELECT * FROM words WHERE name=' +
word + ;, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String age = c.getString(c.getColumnIndex(age));
if (resultString == null) {
resultString = age;
} else {
resultString += + age;
}
} while (c.moveToNext());
}
}
return resultString;
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

75/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

}
private boolean checkDatabase() {
SQLiteDatabase db = null;
try {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
catch (SQLiteException e) {
//An SQLite database file does not exist at myPath
db = null;
db = getReadableDatabase();
}
if (db != null) {
db.close();
}
return db != null ? true : false;
}
private void copyDatabase() throws IOException{
//Open local db as the input stream
InputStream myInput = mContext.getAssets().open(DB_NAME);
//Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase() throws SQLException {
//Open the database
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

76/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

String myPath = DB_PATH + DB_NAME;


myDatabase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDatabase != null) {
myDatabase.close();
}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}

Bob | February 9th, 2011

Shouldnt you / can you use the File class File.exists() to determine if the
database already exists? It would seem a more logical way to do this.

Ken | February 9th, 2011

(I should add that the code I posted is not the final code Ive used. Its just
enough to solve the problem I encountered. Please keep that in mind.)

Malsy | February 11th, 2011

Hi folks,
I used this guide, to use an existing database on my device (HTC desire). I had a
load of problems (SQLiteException:unable to open databse) on my device, but
not the emulator. Solved it by surrouding the bulk of the copy database code with
a try/catch.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

77/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

InputStream myInput = myContext.getAssets().open(DB_NAME);


try{
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
catch (IOException e)
Also if your databse does not copy over a new version, its because the
checkDataBase() will check, see a databaser and return true, copy() will never be
called. For a hack, throw copy() in:
if(dbExist){
copy()
}
Thats all Ive got, good luck.

Steve | February 14th, 2011

Im quite new to Android and I found this article very helpful because I have a
number of tables with static data that I want to use with my Android app. I
followed all the steps outlined and can open my database successfully but when I
try to read from the first table using the following code
private Cursor getData() {
try{
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor cursor = db.query(exhibitor, FROM, null, null, null,
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

78/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
catch(SQLiteException e){
String err = e.toString();
return null;
}
}
It throws an error saying no such table: exhibitor:. Yet when I open the database
in assets using the Sqlite Database Browser it shows the table is there. What am
I missing?

JamesCR | February 15th, 2011

Hi Everyone,
I have be working on this project for hours now and i believe i have gotten every
error you can get. I am not sure what i did wrong so i will explain what i did and
see if anyone can spot the problem. I have a database that has 2 tables, each
has the ID field _id . I followed the instructions on how to add the extra table.
When i saved the database it had no file extension so i left it like that. I was able
to load the database but it could not find my tables. It found the android table but
the others said that they did not exist. Is there a solution to this?
After that i changed the database and removed some values to make it under 1
mb. After that it was unable to open database, i tried to go back to the file that it
opened and it now cant load that. The first error it says is
sqlite3_open_v2(data/data) failed, Select locale From android_metadata
failed. Can you change the database file after you have run the program with
another file? Should you add the .sqlite extension to the file?
I am unable to get it working at all and it seems like i am going backwards now.
Any thoughts about my problem? Thanks
James

Chris | February 18th, 2011

Great example. I have everything working except one thing. How do I update the
database in the future after the app is downloaded? This should never need to
be done but in case there is an error with the data I would want to include a new
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

79/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

db file with the app update. What can I do to get the onUpgrade() method to
trigger after an update to the app and is there a way to test the code with the
Eclipse emulator?

Mathieu | February 18th, 2011

This use to work for me but since Gingerbread (Android 2.3 SDK 9), it doesnt
work anymore.
Its still working on the emulator but not on the Nexus One running
CyanogenMod-7.0.0-RC1 for example.
Ive read that it may be related to the WAL feature of SQLite.
Ive been working on this issue for a couple of hour and I cant make it work.

Jon | February 20th, 2011

I have the same problem as JamesCR.


please help!
I noticed that the old database does not change the folder / data / data / /
database.
Can some one help me update the database?

Chris | February 21st, 2011

I am having the same problems on devices and ROMS with WAL feature
enabled, the copy simply does not work and am totally stuck ! help!

Mathieu | February 21st, 2011

@Chris Ive decided to ship a SQLite dump of my database with the app and
deploy the database on the first start of the app.
To create the dump file:
> sqlite3
> .output dump.sql
> .dump .quit
You may need to remove those lines from the dump:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;

CREATE TABLE android_metadata (locale TEXT DEFAULT en_US);


http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

80/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

INSERT INTO android_metadata VALUES(en_US);


..
COMMIT;
Then, Ive spitted the SQL dump file in 2 files because raw/assets files larger than
1 MB are compressed during the compilation and that causes a problem on
Android 1.5. You can also just rename the dump file with .mp3 or .jpg extension
but the dump files wont be compressed at all and you APK will be much larger.
I have use this method http://notes.theorbis.net/2010/02/batch-insert-tosqlite-on-android.html to run 18000 SQL queries faster well kinda it takes
around 30seconds on my Nexus One (Android 2.3) and a couple of minutes on
my Dream/G1 (Android 1.5).
I suggest you show a progress bar and initialize the database in an AsyncTask.
My app is open-source, feel free to copy what you need.
Here is the initDatabase() method:
http://code.google.com/p/montrealtransit-for-

android/source/browse/trunk/MonTransit/src/org/montrealtransit/android/provider/StmDbH
r=393#206
Here is the progress bar and the AsyncTask:
http://code.google.com/p/montrealtransit-for-

android/source/browse/trunk/MonTransit/src/org/montrealtransit/android/activity/MainScre
r=393
Hope that helps everyone.

Maria | February 21st, 2011

hi,
I m having the same probleme that Chris and Steves :
android.database.sqlite.SQLiteException: no such table: cutomers .
Please help us. I m totaly stuck.
I translate the message in French,
Jai suivi le tutoriel ci-dessus, le dploiement de la base de donnes eu lieu
avec succs, mais il est impossible daccder aux donnes de lune des tables de
la base ( part celle des mta-donnes android_metadata).
a maffiche le message suivant : android.database.sqlite.SQLiteException: no
such table: cutomers .
Merci de nous apporter votre aide (sil y a un lecteur francophone qui passe par
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

81/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

ce tutoriel).
Je suis bloque

Chris | February 21st, 2011

Fixed it
See below for new code. I also do a delete of all associated files in the files
directory on new version upgrade simply in my whats new pop up code.

public SQLiteDatabase loadDb(Context context) throws


IOException,SQLiteException{
//Close any old db handle
if (db != null && db.isOpen()) {
db.close();
}
File fileTest = context.getFileStreamPath(DATABASE_NAME);
boolean exists = fileTest.exists();
if(exists==false)
{
// The name of the database to use from the bundled assets.
InputStream myInput = context.getAssets().open(DATABASE_NAME,
Context.MODE_PRIVATE);
// Create a file in the apps file directory since sqlite requires a path
// Not ideal but we will copy the file out of our bundled assets and open it
// it in another location.
FileOutputStream myOutput = context.openFileOutput(DATABASE_NAME,
Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
// Guarantee Write!
myOutput.getFD().sync();
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

82/83

22/10/2014

Using your own SQLite database in Android applications | ReignDesign

myOutput.close();
myInput.close();
}
// Not grab the

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

83/83

Вам также может понравиться