This question already has answers here:
Query if Android database exists!
(7 answers)
Closed 7 years ago.
How can I quickly check if a database exists in Android?
(not a Table - the entire database)
Open your database and catch the SQLitException which will be thrown in case if database doesn't exist. Note that, you should not call the openOrCreateDatabase() method. See this post for details; Query if Android database exists!
My way to check to see if your database exists is to open a file handle on it and see if the file exists. from my experience using "openOrCreateDatabase()" function will not throw an error if the db doesn't exist. take a look a the name "Open OR Create Database". meaning if there's no db to open it'll just make a new one, so regardless of if there was one before there is one now. I think the only time you'll get an error thrown is if it can't do either. which from what the guy said I don't believe is what they are trying to test for, I think he wanted his program to know if the db was already there before hand, and not to automatically create a blank one if there wasn't. so Since all db's are stored as files, the first parameter in that open database command is the file name. So I think the best option is to check to see if the db file exists like so:
File dbtest = new File("/data/data/yourpackagename/databases/dbfilename");
//If you have Context, you could get the Database file using the following syntax
//File dbtest = getApplicationContext().getDatabasePath("dbfilename.db");
if(dbtest.exists())
{
// what to do if it does exist
}
else
{
// what to do if it doesn't exist
}
Related
I have this android application that I am developing in Unity. I am using SQLite to save and access my data.
When I run my code on Unity editor it works fine. But when I tried it in my android device after some changes in the database, it did not work. So I undid those changes and use Android Device Monitor to check what was happening. I found out that, even though it looked to be working, it was throwing a Unity error: Unable to find SQLite.
I just can't understand what is going on. It works on Unity editor, and, before changes in my database, it also worked (or that was what it seemed) on android device.
This is the code I use to connect to database:
private void conecta()
{
if (Application.platform != RuntimePlatform.Android)
{
dbFile = Application.dataPath + "/StreamingAssets/" + databasefile;
}
else
{
dbFile = Application.persistentDataPath + "/" + databasefile;
if (!File.Exists(dbFile))
{
WWW load = new WWW("jar:file://" + Application.dataPath + "!/assets/" + databasefile);
while (!load.isDone)
{
}
File.WriteAllBytes(dbFile, load.bytes);
}
}
print("aaaaaaaaaaaaaaa");
connection = new SqliteConnection("URI=file:" + dbFile);
print("bbbbbbbbbbbbbb");
}
On my project, I have some dll in my Plugins folder.
And I have libsqlite3.so in my Android folder that can be seen in the picture.
I don't understand what's going on, because when I run the app it accesses the database data and stores more data, but apparently it also throws this error. Can anyone please help me?
If this information is not enough, please let me know. I will complete my question.
UPDATE
I now know the exact line of code that is giving the error. I use the code above to establish a connection with the SQLite database in some scripts. But in this specific script, which is attached to the first screen of the application, the error is coming from this line:
connection = new SqliteConnection("URI=file:" + dbFile);
I don't know why. I use that code as a method and use it some times in this script. I have some buttons that only become interactable if I have data in my database. And when I run it on my device they became interactable. That's why I did not see the error until yesterday when I changed the database file. Below you can see the error when accessing the new column and the table structure in database.
I added one column in two tables, and when I try to access one of those columns it throws an error saying that the table does not have a column with that name.
NEW UPDATE
I got tired of this error and deleted my database file. After that I did a new one, with columns I addes before. What happened was that the Unable to find SQLite continues. After taht it keeps saying that my table does not have the especific column I added in the other file. I don't understant what's going on. That new database had the column from the very begining.
I still don't know what was the problem with the app. But I did a new database file with a different name and it is now working.
Using room in android for database. When I tried to see the data in sqlviewer then no tables found in database file
Myapp.db file is empty.
Data/data/packageName/databases/Myapp.db
Go to folder Data/data/packageName/databases/ There has to be three files .db, .db-shm, .db-wal, copy all three files to one location and then open your Myapp.db these two extra files are needed to open db file
in android studio 3.1.*
in tool window bar click on "Device File explorer" generally you can find this in bottom right corner of the screenn
open directory in data/data/your-application-package/databases
with new architecture 3 files is created in databases directory
your-database-name
your-database-name-shm
your-database-name-wal
you have to export all 3 in the same directory
then open first one file (that is with your-database-name only ) in any sqlite browser.
and now you can see all your data .......
your-database-name-shm
your-database-name-wal
these two extra files are needed to open db file
if you will open database file only, than you will not found any table in that file
Make sure your database is closed when you exit your app, which will ensure that all outstanding transactions are committed:
#Override
protected void onDestroy() {
super.onDestroy();
// close the primary database to ensure all the transactions are merged
MyAppDatabase.getInstance(getApplicationContext()).close();
}
Then you can copy the database off your device using the Device File Explorer in Android Studio (look under /data/data/<your app package name>/databases).
You are also able to force a WAL checkpoint instead of closing the database, but in my humble opinion this option is easier (unless you are trying to backup your database within the app programmatically or something like that) and closing databases is a good idea (even if it's not really mentioned in the Android Room documentation).
Read more about sqlite WAL here: https://www.sqlite.org/wal.html
I saved the whole folder and that's it, I could browse the table.
Once check your Database class,
#Database(entities = arrayOf(Test::class), version = 1, exportSchema = false)
abstract class MyDatabase:RoomDatabase() {
private var INSTANCE: MyDatabase? = null
abstract fun testDao(): TestDao
}
Here, MyDatabase is my Database class, Test is the table name and TestDao is the Dao class.
I am using my own SQLite3 database as opposed to creating a new one each time my app runs, as I have a few tables with static data that I am trying to display. I created my database and placed it in my assets folder. I then created my database helper and when I start my app I can open my database without problem but when I try to open my first table using the following code
private Cursor getData()
{
try
{
myDbHelper = new DatabaseHelper(this);
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor cursor = db.query("exhibitor", FROM, null, null, null,null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
catch(SQLiteException e)
{
String err = e.toString();
return null;
}
}
It throws an error saying android.database.sqlite.SQLiteException: no such table: exhibitor: , while compiling: SELECT _id, EXHIBITOR FROM exhibitor ORDER BY EXHIBITOR but when I check the database exhibitor is there.
What am I missing?
Settings -> Applications -> Manage Applications -> (Click on your application) -> Clear data
Whenever you create new table in an existing database the table doesnt create because the OnCreate function of database handler will not be called everytime but only if required(like database not initiated). If that is not the case your newly created table actually hasnt created. Clear the data to force the db to instantiate itself.
Have you moved the database from the assets folder to /data/data/YOUR_PACKAGE/databases/ on the emulator?
This is a good detailed post about moving the database to /data/data/YOUR_PACKAGE/databases/ if it does not exist.
Here is another short and simple solution to it.
Clear Data and uninstall application from your device and re-install application in device...
Settings -> Applications -> Manage Applications -> Your Application Name -> Clear data
Using SQLiteOpenHelper.onCreate() does not create a new database every time your app starts - rather it creates a database if it does not already exist.
It sounds like you might have an empty database created by or for your helper (if there was no database at all, I might expect a different exception), and your separate database that you created outside of Android. Looks like you and your app are not looking in the same place for your data.
Just clearing the data did not work for me.
What worked was:
Uninstall app
Restart device or emulator
Disable Instant run (Not just the main group but all individual instant run settings)
Build -> Clean Project
Build -> Rebuild Project
hapend to me once
change your DATABASE_VERSION
if your DATABASE_VERSION =1 it will see just three table
if your DATABASE_VERSION = 2 it will see just more table but i really didn't know how many
good luck
I just had a simple mistake.
Reason:
Solution:
Just happened to me. I don't exactly know why but changing the DB_VERSION attribute to a bigger number made it work. The thing is: each time i'm changing the fields of the DB (attributes of the SQLiteDB class), i need to change that number.
Here is my answer according to the description of #ReivieraKid.
No, Uninstall, No Restart, Just checking the app memory if it is your real database, if return false, then copy the database to the memory again. Then You will All set. But to apply this method, you have to know the minimum size of your database.
https://stackoverflow.com/a/73332470/7608371
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).
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);