I would like to create a database in cache so it could be wiped out when user clicks Clear cache button.
In SQLiteOpenHelper constructor there is only argument to pass a name of database, not a directory (default is dadabases).
Is there any option to delete such DB when user wants to clear cache?
Here is an example of creating a database in your cache directory:
public class CachedDatabase extends SQLiteOpenHelper {
public CachedDatabase(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, new File(context.getCacheDir(), name).getAbsolutePath(), factory, version);
}
#Override public void onCreate(SQLiteDatabase db) {
// just for testing
db.execSQL("CREATE TABLE example (id INTEGER PRIMARY KEY AUTOINCREMENT, foo, bar, baz, qux)");
}
#Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
All you need to do is pass the absolute path as the name parameter in the constructor.
Tested just to make sure it was created in /data/data/[package_name]/cache:
CachedDatabase cachedDatabase = new CachedDatabase(this, "TEST", null, 1);
SQLiteDatabase database = cachedDatabase.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("foo", "foo");
values.put("bar", "bar");
values.put("baz", 123);
values.put("qux", true);
database.insert("example", null, values);
Checking for the database:
$ adb shell
$ run-as [YOUR_PACKAGE_NAME]
$ ls cache
TEST
TEST-journal
You can create and open a database in a specific location, but you need to use SQLiteDatabase class (choose one of the openOrCreateDatabase methods): as you mentioned you can't create a database in a different path using the provided SQLiteOpenHelper.
You can also modify the code of the SQLiteOpenHelper to match your needs. Take the source code from the link, copy in a new class of your project and modify the getDatabaseLocked method.
You can also take inspiration from SQLiteAssetHelper.
If you are looking to clear the data in tabledb.execSQL("delete * from "+ TABLE_NAME);
you can also delete the tables db.delete("TABLE_NAME", null, null);
Related
I have uploaded an application to play store couple of weeks back. This application involves sqlite database that stores information on username, password, other details that given are by user while using the application locally.
Now I have couple of more tables and fields added to database and wanna upload the application to playstore as an update?
My worry is if the user updates the application from playstore - After update - all the data stored in database will be saved or will the user has to recreate everything from scratch?
Let me know!
Thanks!
You have to override the onUpgade method of SQLiteOpenHelper. In the OnUpgrade method you can either erase the data(drop sqlite command) or maintain the data with the additional columns(alter sqlite command) or create new table (create sqlite command).
Refer the following snippet.
I assume your version would be 1.(Plz check the constructor of your SqliteOpenHelper class)
Increment the version by 1.
class DatabaseHelper extends SqliteOplenHelper{
private static final int DATABASE_VERSION = 2; //new version of the database
private static final int Database_name = "MyDatabase";
private static final String alterUserName = "alter table users add name text";
private static final String table_users = "create table if not exists "
+ users + "(" + "_id integer primary key autoincrement,"
+ "email text" + ")";
public DatabaseHelper(Context context) {
super(context, Database_name, null, DATABASE_VERSION);
cntxt = context;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(table_users);
db.execSQL(alterUserName);
}
}
Now everytime when you roll the next update with database changes be sure to increment the database version by 1 else let it remain the same.
This isn't done for you automatically. In your SQLiteOpenHelper, you need to increment the Schema integer. This will trigger the on upgrade method for your existing users.
Adding a table is not a problem, just do this in onUpgrade, nothing breaks.
However to add fields, you should use the 'ALTER TABLE' SQL command
If you add new columns you can use ALTER TABLE to insert them into a live table. If you rename or remove columns you can use ALTER TABLE to rename the old table, then create the new table and then populate the new table with the contents of the old tab
See the official reference here
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to check existing database before creating new database on Android 2.2?
I have an app which check the existence of database in the start up. If not exits create a new one and if there then access the database. Can you please tell me how to check the existence of db(SQlite)?
Android helps a lot developpers to manage a database.
You should have a class like this (a single table with only 1 column) :
public class MyDBOpenHelper extends SQLiteOpenHelper {
private static final String queryCreationBdd = "CREATE TABLE partie (id INTEGER PRIMARY KEY)";
public MyDBOpenHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(queryCreationBdd);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE partie;");
db.execSQL("DELETE FROM sqlite_sequence"); //table which contains the next incremented key value
onCreate(db);
}
}
Then you simply do this :
MyDBOpenHelper databaseHelper = new MyDBOpenHelper(context, "dbname.db", null, 1);
SQLiteDatabase bdd = databaseHelper .getWritableDatabase();
If necessary, Android will create the database (call the onCreate method) or give you the one that already exists. The fourth parameter is the version of the database. If the currently created database is not the latest version, onUpgrade will be called.
EDIT : The database path will be something like this :
/data/data/fr.mathis.application/databases/dbname.db
Take a look at query-if-android-database-exists
Open your database in try block with path of the databse like:
try{
SQLiteDatabase dbe = SQLiteDatabase.openDatabase("/data/data/bangla.rana.fahim/databases/dictionary", null,0);
Log.d("opendb","EXIST");
dbe.close();
}
if an exception occurs then database doesn't exist so create it:
catch(SQLiteException e){
Log.d("opendb","NOT EXIST");
SQLiteDatabase db = openOrCreateDatabase("dictionary", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS LIST(wlist varchar);");
db.execSQL("INSERT INTO LIST VALUES('খবর');");
db.execSQL("INSERT INTO LIST VALUES('কবর');"); //whatever you want
db.close();
}
that's it you are done :)
I use a boolean flag which is set to true when onCreate of SQLiteOpenHelper is invoked. You can find my full code here
I'm running into a very frustrating bug.
I have a java class that reads in data from a file, and enters it into the database.
package edu.uci.ics.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapter extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "mydb";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "fruits";
private static final String FRUIT_ID = "_id";
private static final String FRUIT_NAME = "name";
private static final String FILE_NAME = "fruits.txt";
private static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME + "("+FRUIT_ID+" integer primary key autoincrement, "+FRUIT_NAME+" text not null);";
private SQLiteDatabase mDb;
private Context mContext;
public DbAdapter(Context ctx){
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
mContext = ctx;
this.mDb = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
// populate database
try {
BufferedReader in = new BufferedReader(new InputStreamReader(mContext.getAssets().open(FILE_NAME)));
String line;
while((line=in.readLine())!=null) {
ContentValues values = new ContentValues();
values.put(FRUIT_NAME, line);
db.insert(TABLE_NAME, null, values);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public Cursor fetchAll() {
return mDb.query(TABLE_NAME, new String[] {FRUIT_NAME}, null, null, null, null, null);
}
}
EDIT:
To be more clear, this is what fails:
When I change the database name variable, the table name variable, the program force closes, indicating that something went wrong. Why can't I change the name of the table I create?
When I make changes in the fruits.txt file, I don't see anything reflecting those changes at run-time. Why does this happen?
SQLiteOpenHelper.onCreate() will only get called automatically if the database does not exist, which will only happen once. After that, the database file exists on the device's internal storage so it is simply going to load up the version it has.
If you want to create a new database when the external file is changed, you need to either delete the current database file (manual process) or also change the current database version the helper is created with. When Android sees that the version SQLiteOpenHelper is created with varies from the current file in internal storage, it will call onUpgrade() to allow the existing database to be modified to match the new "version".
EDIT:
To clarify, when you create a database, a db file is created (and persisted) on the device's internal storage, separate from your application's assets. When you re-run your application, persisted data storage does not clear out (or else it wouldn't be "persisted" anymore) so that database file from the last run of your application still exists...with all the settings from when it was created.
When you make changes to the variables in this class, it doesn't somehow magically modify the database file that already exists on the device, so now you are looking for tables and databases that don't exist (probably where your crashes are coming from).
If you simply need to clear out the database so it will reflect changes you've made during development, just clear the database manually on the device by going into Settings -> Manage Applications -> {Application Name} -> Clear Data. This deletes persisted files so they can be re-created by your application the next time you launch it.
If, however, you need this to somehow be a feature where your application automatically recognizes changes you've made to a file in /assets and modifies or re-creates the database as a result, then look at my previous suggestions about using the upgrade mechanism built into SQLiteOpenHelper
HTH
When you change the database name or table name in your code, they no longer reflect the names in the database on the device, so you get a force close. During development, the easy thing is to just uninstall your application and then reinstall whenever you make incompatible changes like that. When changing your database schema from one released version to another, you need to increase the database version number and do the right thing in onUpgrade().
For example, right now, you have
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
So when you change the table name in code from, say "fruits" to "veggies", onUpgrade() gets run, but table veggies doesn't exist, so it isn't dropped, and then you call onCreate(db) whith a conflicting shchema on top of the existing database. So you need to check oldVeresion and newVersion and do something more like
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion == 2 && oldVersion == 1) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME_V1);
db.execSQL("CREATE TABLE "+ TABLE_NAME ...);
}
}
If you're trying to change fruits.txt on the device, it won't work. That's how Android is designed: your assets never change, they're a read-only part of your APK. You need to write the fruit.txt file to the SD card if you want it to be able to change it.
In example apps database is in most cases single table, so db schema is stored in static variable.
Storing large schema in seperate file is more friendly for me.
How can I do that? I thought about using resources (R.strings.db_schema) but probably there is a better way.
Could somebody give me any advice?
You could put the schema data in a raw file under res/raw. Then you can just load and parse that file the first time.
The way I do is to have a class per table, named after the table with "Table" suffix (e.g. PlayerTable or EventTable).
These classes contain all the static variable for the table name and all the field names, and they also contain two static methods:
public static void onCreate(SQLiteDatabase database)
public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
So that my SQLiteOpenHelper can just call all of them, without having hundreds of static variables with all the fields and create queries. E.g:
#Override
public void onCreate(SQLiteDatabase database) {
PlayerTable.onCreate(database);
EventTables.onCreate(database);
..... any other table you have .....
}
This class is then injected into all my data access objects (select / update / insert queries). For them I have dedicated classes that contain all my methods, by functionality (e.g. EventHandlingDAO for all the queries that deal with event handling).
And finally, theses DAO are injected into the activities that need them, when needed.
EDIT: A few more details about my code:
My main objects are the DAO (data access objects), in which I have methods like:
// in EventHandlingDAO:
public void addEvent(Event event) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
try {
database.execSQL("INSERT INTO " + EventTable.EVENT_TABLE_NAME + " (...."); // list of fields and values
} finally {
database.close();
}
}
public List<Event> getAllEvents() {
final List<Event> result = new ArrayList<Event>();
SQLiteDatabase database = databaseHelper.getReadableDatabase();
try {
final Cursor cursor = database.rawQuery("SELECT " + EventTable.KEY_NAME + ", " + EventTable.KEY_DATE_AS_STRING + " FROM " + EventTable.TABLE_NAME, null);
cursor.moveToFirst();
// ... rest of the logic, that iterates over the cursor, creates Event objects from the cursor columns and add them to the result list
return result;
} finally {
database.close();
}
}
So in that DAO, I have my databaseHelper object, which instanciates my class that extends SQLiteOpenHelper with the methods I talked about above.
And of course, I have interfaces to all my DAO, so that I can inject a Stub or mocked implementation in my tests (or experiment with different implementations if I want to try another solution based on SharedPreference for example)
And the code for my PlayerTable table:
public static void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE); // TABLE_CREATE is my "CREATE TABLE..." query
}
public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
// A bit blunt, that destroys the data unfortunately, I'll think about doing something more clever later ;)
database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(database);
}
I have the following code (I simplified it & removed unrelevant parts)
public class MyDatabaseManager extends SQLiteOpenHelper {
private SQLiteDatabase myDatabase;
public DatabaseManager() {
super(MyApp.getAndroidContext(), DATABASE_NAME, null, DATABASE_VERSION);
myDatabase = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("create table t1 (t1key INTEGER PRIMARY KEY,data TEXT,num REAL,timeEnter NUMERIC);");
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
}
}
Now when I run queries against this database I get sqlite - no such table exception.
My breakpoint at database.execSQL hits and it doesn't raise any exception(for example if I change the code to database.execSQL("asda") I get syntax error exception) so I think my SQL code is correct. Yet the table is not created.
I copied the database file to my pc and I looked in it with Sqlite browser and indeed my tables don't exist there. There is only one table and that is something called android_metadata. Any ideas?
Sqlite doesn't have a datatype for DATE. I would suggest changing it to an INTEGER and storing date.getTime() in it.
Change your query and try something like:
create table t1 (_id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT,num REAL,timeEnter NUMERIC);
there should be a column _id in Android Sqlite Database table and better is it should be autoincrement.
Try passing the context when you instantiate the manager by changing the constructor as follows:
public MyDatabaseManager(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
public openDB() throws SQLException
{
myDatabase = getWritableDatabase;
}
Now pass getApplicationContext() to the new MyDatabaseManager instance in the activity's onCreate():
MyDatabaseManager manager = new MyDataBaseManager(getApplicationContext());
manager.openDB();
Ok, I fixed the problem. There were multiple problems:
1) My create table query had problems
2) I was programatically copying the database file to the sd card at the end of the onCreate and apparently there it was not yet written. I moved it right under myDatabase = getWritableDatabase();
and it worked.
Thanks all for triying to help.