Using Your Own SQLite Database in Android Applications - ReignDesign
Using Your Own SQLite Database in Android Applications - ReignDesign
ReignDesign
Jobs
Blog
Labs
Juan-Manuel Flux
Tags
application.
Android,
Databases,
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
Now insert a single row with the text 'en_US' in the "android_metadata" table:
, then selecting the table you want to edit and finally selecting the
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
2/83
22/10/2014
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:
3/83
22/10/2014
/**
* 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{
/**
* 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
try{
5/83
22/10/2014
}
@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
}
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
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
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
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.
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?
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.
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
compiling: SELECT
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,
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
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:
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.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
10/83
22/10/2014
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!
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?
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
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
Hi, I just want to know how can I delete the table after I created it?
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
Try this,
Android Sqlite Databases
http://sarangasl.blogspot.com/2009/09/create-android-database.html
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.
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.
@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();
}
13/83
22/10/2014
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).
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
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
Hope it helps !
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
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!
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.
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
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
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!
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 .
Hi all !
I have got a file /sdcard/data.db .How to insert record into file data.db
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
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!
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.
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
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
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
19/83
22/10/2014
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
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;
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
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!!!!!!
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!!
21/83
22/10/2014
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
22/83
22/10/2014
23/83
22/10/2014
}
}
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.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
24/83
22/10/2014
Hi, thanks for this article was useful as I was struggling to get my database up
and running.
Ayub Malik
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 ?
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
25/83
22/10/2014
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
Can you give your code ,we cannot help you winthout code
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
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.
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
* */
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);
}
28/83
22/10/2014
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
29/83
22/10/2014
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?
kondortek can you explain how can i trigger onupgrade methods ? And can you
explain your solution ? Thanks !
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?
30/83
22/10/2014
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
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
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
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!
Thanks Jim! That was also my problem and your solution solved it for me.
Hello everyone..
anyone can tell me how can we execute insert , select , delete & update query
from own database.
How do you manage database version upgrades? This solution doesnt seem to
call the onUpgrade() method when the database version number changes
Thanks!
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
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
34/83
22/10/2014
}
@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
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.
@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
@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.
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
version..????
Hi, thanx for the tutorial. It really helps for beginners like me on how to create
preloaded sqlite db.
Keep up the good work.
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.
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
can anyone site a solod example on how to import SQLite database from android
to my local server..thanx
NICE ARTICLE
Future classic.
This is a great post/article. The code works for me. It save me a lot of time.
Thank you very much.
38/83
22/10/2014
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
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
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
@moon
Send me an email at [email protected]
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
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
[email protected]
public Cursor listArt(){
return myDataBase.query(TABLE_NAME, FROM_MANSIONS, KEY_TYPE +
like %art%', null, KEY_MUSEUM, null, KEY_MUSEUM);
}
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
41/83
22/10/2014
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
Thanks for this helpful article. Perhaps Im missing something but shouldnt the
original assets be deleted to avoid duplicate/redundant data storage utilization?
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
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
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?
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?
Disregard
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.
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
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..
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?
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
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.
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?
Hello Ace,
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
46/83
22/10/2014
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.
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?
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?
hi can u provide sample code for retrieving the EditText data stored in DB sqlite
android
47/83
22/10/2014
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
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.
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.
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
{
e.printStackTrace();
// TODO: handle exception
}
}
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
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();
}
Another improvement.
You can use myContext.getDatabasePath(DB_NAME) to dynamically get
database path instead of hardcoded DB_PATH.
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
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.
/*
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
53/83
22/10/2014
myInput.close();
}
//hope that helps someone out there.
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!
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.
kishore, try adding null as argument to new DataBaseHelper(); on first line i.e.
DataBaseHelper myDbHelper = new DataBaseHelper(null);. Worked for me.
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
Hi can anyone please send me a working exemple of this cuz i caint get it
working there always something wrong
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
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!
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
try
{
myDbHelper.openDataBase();
}
catch(SQLException sqle)
{
throw sqle;
}
thanks a lot..
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
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.
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
what exactly do you mean by put your database in the assets folder?
Thanks
kane
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.
@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
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
Great tutorial!!!!! really helped me out a lot. do you have a tutorial for
reading/writing from/to said database?
thanku
I got error message on querying table that table does not exist although it
definetely exists
58/83
22/10/2014
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?
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
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.
@Neeraj:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
60/83
22/10/2014
@Neeraj:
for me the second comment on this article helped:
http://huuah.com/using-sqlite-from-your-android-app/
cheers
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?
i want to save the data entered in an edittext, in to the database .Can anybody
help me for this.
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
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.
Great post! One question. How to upgrade the database schema in future
versions? It looks like OnUpgrade is not called.
Thanks a lot.
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.
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
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
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
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
63/83
22/10/2014
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
+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!
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.
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?
@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
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
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
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!
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
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
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!
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
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?
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 !
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?
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.
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
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
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)
Hello,
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
69/83
22/10/2014
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.
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.
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
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
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
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
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
72/83
22/10/2014
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.
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.
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
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: 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
75/83
22/10/2014
}
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
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.
(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.)
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
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
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?
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
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
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?
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.
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!
@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;
80/83
22/10/2014
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.
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
ce tutoriel).
Je suis bloque
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.
82/83
22/10/2014
myOutput.close();
myInput.close();
}
// Not grab the
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
83/83