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
Related
Firstly, I create a database called "mydb" in my Android app:
DBHelper dbHelper = new DBHelper(context, "mydb", null, 1);//DBHelper is my custom class
And write some data into it's table:
SQLiteDatabase db = dbHelper.getReadableDatabase();
db.execSQL("insert into mytable(name, text) values ('allen','hello')");
Here, everything is ok. But then, i delete this database manually not by programming, with a software "R.E. explore" (Certainly on a rooted device).
Then, in my code, i read this table of the database. What is astonishing is that i still could get the data I stored.
Cursor cursor = db.query("mytable", new String[]{"name","text"}, null, null, null, null, null);
Why?
Quoting from the Android Developers reference website:
Once opened successfully, the database is cached, so you can call
this method every time you need to write to the database. (Make sure
to call close() when you no longer need the database.)
This is from the description of the getWritableDatabase() method, however both getReadableDatabase() and getWritableDatabase() return basically the same object for reading the database.
Please note that you should use getWritableDatabase() if you want to persist the changes you make to the database on the device's internal memory. Otherwise they will be valid only for the duration of the application's runtime and will be discarded once the app is closed. If you wish to delete the database completely, you should call the SQLiteDatabase's close() method in order to invalidate the cache.
use SQLiteDatabase.deleteDatabase(File file) API to delete the database
Deletes a database including its journal file and other auxiliary files that may have been created by the database engine.
Make sure you have closed all the connections that are open.
In case you are not able to do that,
just cal the deleteDatabase followed by kill process.. - not recommended
You need to delete the app from your phone then install again
I am trying to write a code in Android and going through following errors. I am opening a SQLite database and using Cursor.
Java Code
for(int y3=0;y3<10;y3++)
{
String sql_query5= "SELECT * FROM Data WHERE Id="+y3+"";
Cursor cur5 = SQLiteDatabase.openDatabase(db, null, SQLiteDatabase.OPEN_READWRITE).rawQuery(sql_query5, null);
if(cur5.moveToNext())
{
//
}}
So i need to display the Age in the layout but i am facing SQLiteCantOpenDatabaseException and Database object not closed. I don't understand the errors.
Please let me know some solution and suggestion !!!
Do not use hard-coded file paths. You have no guarantees about the structure of the filesystem.
Learn to use SQLiteOpenHelper. This is what helps you create and maintain your SQLite database. Instead of trying to open the database yourself, you create a new SQLiteOpenHelper and call getReadableDatabase().
When you are done reading from a Cursor, call cursor.close().
If you want to close the database, you can call close() on it as well; just be aware that any cursors you got by querying it will no longer be able to give you data, so make sure you are finished them those before closing the database.
add '' in your
String sql_query5= "SELECT * FROM Data WHERE Id='"+y3+"' ";
I am experiencing some trouble with an SQLIte database in my Android application.
The issue is that the database is never updated, not even on multiple restarts of the emulator, of Eclipse or after deletion from DDMS.
This is my onCreate method, located in a class that extends SQLiteOpenHelper:
public void onCreate(SQLiteDatabase database) {
try {
database.execSQL(ESSENCE_TABLE_CREATE);
database.execSQL(PACCO_TABLE_CREATE);
database.execSQL(TAVOLE_TABLE_CREATE);
database.rawQuery("insert into essenza values(1, 'Rovere')",
null); // added later
} catch (SQLException e) {
Log.e("DB", e.getMessage());
}
}
After instantiating the helper, I request a reference to the database:
helper = new DBHelper(context, dbpath + "/" + DATABASE_NAME);
database = helper.getWritableDatabase();
It seems that the rawQuery statement (which was added at a later time) is not executed and that the database in use is instead cached from a previous version. I also tried to change the version of the database, but it did not work. Am I missing something? Thanks in advance.
You have two options:
Use DDMs to delete the database file from your device (look in /data/data/). This will force Android to run onCreate again.
In your constructor, increment the database version you pass to SQLiteOpenHelper. Add your raw query to onUpgrade.
You probably want option 1. Option 2 is better if you have users of your app whose databases you want to update.
I have an app that uses a database with 3 tables in it. Those 3 tables have data read from and written to them by activities and services.
Having gotten a few "android.database.sqlite.SQLiteException: database is locked" crashes, I went in to the database adapter class and wrapped every write, update, or delete function with a synchronized statement, so like:
public int deleteExpiredAlarms() {
String whereClause = FIELD_EXPIRED + " = 1";
int val = 0;
synchronized(dbWriteLock) {
val = db.delete(ALARM_DATABASE_TABLE, whereClause, null);
}
return val;
}
That seemed to make it better. But lately it's gotten bad again as I've added more services that read and write to different tables.
Do I need to synchronize ALL db access statements, including queries?
The exception is occurring on the attempt to open the writable database via the open helper...should I synchronize that act also?
I've heard that I should only be using one db helper so that there won't be issues with multiple threads accessing the db. How do I use only one db helper? Every example I've seen so far has the db helper as an instantiated value inside the db adapter....so wouldn't that be a separate db helper per db adapter instantiated (one in an activity, one in a service running,etc)
I've looked at using a content provider instead, as it's been claimed to solve problems like this, but it's really more work than I want to do if I should be able to have direct db access without locking issues. And I do not plan to make this db accessible to other apps.
Thanks for the help.
I would like to delete the database file from the Android file system programatically? Can I have a shell script launch adb which in turns runs a shell script in the Android space to do the database deletion? Can I get this done from within a JUnit test case (with a system() call)?
How do I delete an entire database in Android? I need to make the whole thing go away so I can test database creation. I can drop tables, but that's not enough. This is in the emulator, not on a phone.
Once you have your Context and know the name of the database, use:
context.deleteDatabase(DATABASE_NAME);
When this line gets run, the database should be deleted.
The SQLiteDatabase.deleteDatabase(File file) static method was added in API 16. If you want to write apps that support older devices, how do you do this?
I tried: file.delete();
but it messes up SQLiteOpenHelper.
Thanks.
NEVER MIND! I later realized you are using Context.deleteDatabase(). The Context one works great and deletes the journal too. Works for me.
Also, I found I needed to call SQLiteOpenHelp.close() before doing the delete, so that I could then use LoaderManager to recreate it.
It's easy just type from your shell:
adb shell
cd /data/data
cd <your.application.java.package>
cd databases
su rm <your db name>.db
Try:
this.deleteDatabase(path);
or
context.deleteDatabase(path);
context.deleteDatabase("database_name.db");
This might help someone. You have to mention the extension otherwise, it will not work.
Also from Eclipse you can use DDMS which makes it really easy.
Just make sure your emulator is running, and then switch to DDMS perspective in Eclipse. You'll have full access to the File Explorer which will allow you to go in and easily delete the entire database.
context.deleteDatabase(DATABASE_NAME); will delete the database only if all the connections are closed. If you are maintaining singleton instance for handling your database helper - it is easy to close the opened Connection.
Incase the databasehelper is used in multiple place by instantiating directly, the deleteDatabase + killProcess will do the job even if some connections are open. This can be used if the application scenario doesn't have any issues in restarting the app.
Delete old Db when uninstall the app.
Setting android:allowBackup="false" in the application tag in AndroidManifest.xml fixed the problem. It seems that for some weird reason the Android OS was restoring from a backup every time I deployed the app.
you can create a file object of current database path and then delete it as we delete file from folder
File data = Environment.getDataDirectory();
String currentDBPath = "/data/com.example.demo/databases/" + DATABASE_NAME;
File currentDB = new File(data, currentDBPath);
boolean deleted = SQLiteDatabase.deleteDatabase(currentDB);
I used Android database delete method and database removed successfully
public bool DeleteDatabase()
{
var dbName = "TenderDb.db";
var documentDirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentDirectoryPath, dbName);
return Android.Database.Sqlite.SQLiteDatabase.DeleteDatabase(new Java.IO.File(path));
}
I have used the following for "formatting" the database on device after I have changed the structure of the database in assets. I simply uncomment the line in MainActivity when I wanted that the database is read from the assets again. This will reset the device database values and structure to mach with the preoccupied database in assets folder.
//database initialization. Uncomment to clear the database
//deleteDatabase("questions.db");
Next, I will implement a button that will run the deleteDatabase so that the user can reset its progress in the game.
If you are going to delete Table or Database , this way is worked:
1- Delete Table - It means keep Database but clean data from a table
* Just in DataHelper class add
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from " + TABLE_NAME);
2- Delete Database - It means clean all records but keep file name
In the Activity
myDb = new DbHelper(this);
myDb.close();
myDb.delAll(getApplicationContext());
recreate();
In DataHelper class add
public void delAll(Context context) {
context.deleteDatabase(DB_NAME);
}
From Application Manager, you can delete whole application with data. Or just data by it self. This includes database.
Navigate to Settings. You can get to the settings menu either in
your apps menu or, on most phones, by pulling down the notification
drawer and tapping a button there.
Select the Apps submenu. On some phones this menu will have a
slightly different name such as Application Manager.
Swipe right to
the All apps list. Ignore the lists of Running and Downloaded apps.
You want the All apps list.
Select the app you wish to disable. A properties screen appears with
a button for Force Stop on the upper left and another for either
Disable or Uninstall updates on the upper right side.
Delete data.