How to access an existing sqlite database in Android? - android

So far we have developed apps in android that create database on runtime. We like to know how can we access a pre-built or existing database/sqlite file in our android app? Please provide detail

Take a look at the documentation for android.database.sqlite.SQLiteDatabase.
In particular, there's an openDatabase() command that will access a database given a file path.
SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, 0);
Just specify the path to your database as the path variable, and it should work.

I have followed the same road and found two issues:
Include the _id field on any table you create and make sure it is
part of the columns to return when you query any table.
You may run into an error like Failed to open the database. closing
it.. This is because we are copying the database from an existing
file instead of creating tables on top of a db created by the sqlite
android API and the table android_metadata may not exist. For
creating it just run the following query on your db:
CREATE TABLE android_metadata (locale TEXT);
And add the corresponding locale, for example en_US

First copy your SDCARD and give it's path in the variable "DBNAME" in the following example.
it will be something like "/sdcard/persons.db" if you are directly pulling it to sdcard.

Use this for accessing database in application :
Context context = getApplicationContext();
context.getDatabasePath(DataBaseHelper.database_Name);

Related

How can load some value in the sqlite-database

I have a database now i have to check whether it is empty or not. if empty i have to write the code for insert values otherwise i have to update the values of the fields.
please help me..
You can try something like this:
// Open or crare
myDB = this.openOrCreateDatabase("MyDatabaseName", MODE_PRIVATE, null);
//Check if exists (if not create the table)
myDB.execSQL("CREATE TABLE IF NOT EXISTS MyTableName (Name1 VARCHAR, Name2 VARCHAR);");
//Insert or update your lines
myDB.execSQL("INSERT INTO MyTableName (Name1 , Name2 ) VALUES ('XXX', 'YYY');");
Have you done the Google Notepad tutorials 1,2,3? they have a bunch of database help
Hope that can help
It's possible to include a .db file in your application package and use that as the starting point for your device-side database. It goes in the assets folder. You'll have to manually copy the values out of that .db into the one on the device in your startup method, but it saves putting a bunch of SQL INSERT calls in code.
The MOTODEV Studio Database perspective will assist you with this. You can use it to create a .db from scratch and populate it with your default values. Then, there is a wizard that will set up a content provider and accessor classes for the fields if you need them.
Disclaimer: I'm the product manager for MOTODEV Studio.

call sql from another class for android app

Hi
I have created a database for my application and i have added items to the database using methods from the database class. I am encountering a problem do when i try to execute a sql query in the other class(app.java), i need to reference a database and thats where im having the problem!
this is the sql query im trying to execute(in database.java)
public void getData(SQLiteDatabase db, String data){
String sql =
"SELECT permissions FROM genres WHERE name = "+data+";";
db.execSQL(sql);
}
and this is how i am calling it(in app.java)
appData.getData(db, chosenGenre);
I just dont no what to put for the "db" part in appData.getPermissions(db, chosenGenre);
Does anyone know how to do this?
Thanks
You would typically use a SQLiteOpenHelper to create the database files (if necessary) and obtain a SQLiteDatabase object which is used to access the actual database (files on disk read by SQLite).
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Here's a nice tutorial
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/2/
You don't show the code where you define the database manager 'db'! If you are using a database created outside the android device, you might get some help from this link:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
Also, I have found that it's best to frame all table names and supplied values in single quotes a la -
String sql = "SELECT permissions FROM 'genres' WHERE name = '" + data + "'";
Note that the semicolon is not required.

How to read sqlite file using cursor and display data in a listview

Hi im trying to read sqlite file which is placed in assets/databases folder
i followed this link to read data from sqlite file
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
im getting error
no such table : while compiling
SELECT _id, name, address FROM
stores
Is there any permission i need to write in manifest to read sqlite file data?
Please let me know how i can solve this issue. Or else please give me any reference link to follow.
Thanks in advance
The way you'd want to do this is to make a new DBManager object that creates the database in its onCreate method--that way when the DatabaseHelper is first instantiated, the table will be created for you. Then you'd instantiate one and call getReadableDatabase() on it to get a DB object which you can then query.
This tutorial may help you more, it's more succinct and up to date: http://developer.android.com/guide/topics/data/data-storage.html#db
After that, to set up the list view in a ListActivity, you can call setListAdapter and pass in a SimpleCursorAdapter. Here's a tutorial on that: http://developer.android.com/guide/appendix/faq/commontasks.html#binding
Check if database already exists or not.
If you are running on emulator.
write following on terminal/shell:
adb shell
cd data/data/your package name(ex. com.android.etc)
ls
if there exists databases directory then may be database is created
cd databases
ls
it will show your database if exists;
sqlite3 "your db name"
then write
.tables
it will show the name of table if exist:
now write your query over here to check for errors for ex:
sqlite> SELECT _id, name, address FROM stores
hope it helps.....
and yes there are no as such required permissions for this.

What is the android_metadata table?

I try to integrate an existing database file into my Android project.
I follow the instructions on this blog. They write that I have to add a table android_metadata with a column called locale and put en_US into it.
I try to figure out what this table is used for. Because my database content is german. Maybe i then should not put en_US into it? Is this required for localisation of the database content or is the table not needed at all?
the metadata table will be generated automatically. if you have content of german try updating the metadata table 'de_DE'.
If you're okay opening the DB with read-write access then you can let the openDatabase(...) call automatically generate it. For example in Android:
SQLiteDatabase.openDatabase(m_szMainDBPath, null, SQLiteDatabase.OPEN_READWRITE);
The metadata table is required to hold (as its name suggests) meta information about the application. This table is auto-generated in some cases (since api 4 if i remember correctly) but you may want to add it yourself.

How does android access a sqlite database included in the assets folder

I already have a SQLite database. I put it in the assets folder of my project. I read the Android documentation. It said that for all the databases in Android, the path is data/data/pack_name/database_name.
This confused me. I just placed it in the assets folder, so the path is data/data/assets/database_name?
The package name is not the project name, the package name is the namespace. From Anthony's link.
Remember to change the "YOUR_PACKAGE"
to your application package namespace
(i.e: com.examplename.myapp) in the
DB_PATH string.
For example, from the Hello World tutorial, the project name is HelloAndroid but the package name is com.example.helloandroid
If this application had a database, it would be stored at data/data/com.example.helloandroid/database
To see how it is for the other applications you can start your emulator. On the menu bar you have your avd's name (I think it stands for Android Virtual Device). On mine it s "avdessay:5554"
(On Linux) From command line, type:
adb -s emulator-5554 shell
You have to replace 5554 by whatever port you are using.
if you have the command prompt '#' you can type:
cd data/data
There, you will see that eveything is in a form of a package name.
More info here
When you create a database by utilizing the SQLiteDatabase or SQLiteOpenHelper classes, it creates the database in your data/data/package_name/database.
You can access that resource by using
InputStream myInput = myContext.getAssets().open(your_database_here);
Any other information, look at Using your own SQLite database in Android Applications
The package_name portion of the path, would be the name of your package. You can find the name of the package at the first line in your .java files.
As an example, my class starts with this at the top
package com.forloney.tracker;
So my database is in data/data/com.forloney.tracker/database folder.
Hope this makes sense.
#ScCrow I too followed this example and had the same problems you did until I realized I was not using the DataBaseHelper correctly (or rather it had a quirk I overlooked).
When you use your DatabaseHelper class in your activity, you have to make sure you call createDatabase first! If you look at the code for openDatabase it does NOT check to see if the database exists, so you either have to (attempt to) create the database in each activity you use it in, or modify the openDatabase method to check to make sure the db exists. The link posted does actually instruct you to use it this way but you (like me) may have glossed over that.
Bad:
DBAdapter db = new DBAdapter(this);
db.openDataBase(); //Bad! db not created yet!
Good:
DBAdapter db = new DBAdapter(this);
db.createDataBase(); //needs exception handling
db.openDataBase();
When I try to open my DB, I get "unable to open database file". I assume its not finding the DB and not some other programmer error. In the log I see the following which looks good to me.
sqllite3_open_v2("/data/data/com.isildo.HelloListView/databases/ListsDB" ...
This is the setup
private static String DB_PATH = "/data/data/com.isildo.HelloListView/databases/";
private static String DB_NAME = "ListsDB";
In my projects assets in the Package Explorer, I see the ListsDb database.
So I at least think I have it all correct. I am using the example at
[http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/]
In one of the posts here, someone offers a suggestion about setting some Assets parameters.
{no response to post there}
**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**
Is this something we need to do, and if so, can we get a little better direction on the changes required. I could not find the places to make the suggested changes I looked at the project settings, and other things.
Yep, Im new to the environment, so I may just be not finding them. Im using Eclipse on windows.
In your DBAdapter.java, change the return type of openDatabase method to SQLiteDatabase.
When you access the database simply use SQLiteDatabase data = db.openDatabase(), where db is DBAdapter db = new DBAdapter(this).

Categories

Resources