I am getting following error while Version Creating My Database.
01-18 12:08:01.157: ERROR/AndroidRuntime(3079): Caused by: java.lang.IllegalArgumentException: Version must be >= 1, was 0
Please Help me regarding this.
Each database you create has a version number. That way you can keep track of them if you upgrade the application (perform necessary database changes for the upgrade on existing data). The version number must start from 1.
If you look at the following code:
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "
(id INTEGER PRIMARY KEY, name TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
onUpgrade will handle all necessary database upgrades. Sometimes you'll opt to just destroy (drop) the current database and create a new one.
it seems you have set previous version as 0, remove your app from phone, reinstall it, make sure new version is greater then previous one.
Related
I'm using GreenDao 3.2.2 for my DB,
On my first run on creating Entities via #tags everything worked ok.
Now I am editing the gradle schema to higher versions because I added some props to a table:
greendao {
schemaVersion 4
}
However the OpenHelper onUpgrade method is never called, thus my project is always crashing because some columns are not found.
Application class
//Init DB
UpgradeHelper helper = new UpgradeHelper(this, ENCRYPTED ? "db-encrypted" : "db", null);
Database db = ENCRYPTED ? helper.getEncryptedWritableDb("app-cipher") : helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
OpenHelper class
public class UpgradeHelper extends DaoMaster.OpenHelper {
public UpgradeHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//never gets called
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion);
//do migrations
}
}
am I missing something?
Got it!!! After hours of searching and reading GreenDAO code I understood the problem.
The problem is that getEncryptedWritableDb creates another kind of DB that does not extends SQLiteDatabase. So even when the EncryptedHelper gets the onUpgrade method, my helper class didn't catch it because it fell into another signature.
The solution was simply using the other signature that receives a DAO Database interface:
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by migrating all tables data");
//do migration
}
of course I needed to update all my Migration methods to receive a Database object instead of a StandardDatabase
I already have a database in my app using a 3rd party library. The library doesn't seem to have drop table functionality. So I was thinking to directly change it using SQLiteOpenHelper API. Is this possible?
I have created a class that extends SQLiteOpenHelper and give it the same db name as the one used in the library.
public class SqliteDatabaseHelper extends SQLiteOpenHelper {
// Database Info
private static final String DATABASE_NAME = "myDatabase";
private static final int DATABASE_VERSION = 1;
private Context context;
public SqliteDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
L.w("old: " + oldVersion + ", " + "new: " + newVersion);
if (oldVersion != newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + "deals_latest");
onCreate(db);
L.w("drop it like it's hot");
}
}
}
And I initialize it in Application class, just to see if it reflects the db class I created.
SQLiteDatabase db = new SqliteDatabaseHelper(this).getReadableDatabase();
L.w("version: " + db.getVersion());
L.w("path: " + db.getPath());
SqliteDatabaseHelper helper = new SqliteDatabaseHelper(this);
helper.onUpgrade(db, 1, 2); // this line suppose to invoke the drop table query
When running the app, onUpgrade() method doesn't seem to be called.
Mind you, I have never had any experience in using the native SQLite helper, so I have no idea what is going on here. My objective is just to see if the query in onUpgrade is executed or not. But the table still exists in the database.
How do I get around this?
The SQLiteOpenHelper class helps to manage versions of your own database.
It does not make sense to use it for a database that is managed by third-party code.
Just open the database directly with openDatabase().
I want to upgrade the DATABASE of my Android App, without losing data that users saved in a specific table (say "favourites" table, where I store the _id of "food" entries).
I'm simplyfing the structure of my DB to keep the code in this question shorter, anyway I'm using SQLiteAssetHelper and a ContentProvider
When I tried to upgrade the DataBase I received the error:
Caused by: android.database.sqlite.SQLiteException: Can't upgrade read-only database from version 1 to 2
Here my DB Helper class
public class CookingDBHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "cookingDB.db";
private static final int DATABASE_VERSION = 2;
public CookingDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
}
}
Let's say I have two tables in my DB: "food" table I want to upgrade, and "favourites" table I want to preserve it as the user saved.
Here the structure:
CREATE TABLE "food" (
`_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`name` TEXT NOT NULL,
`description` TEXT,
`category_id` INTEGER,)
CREATE TABLE "favourites" (
`_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`id_favourite` INTEGER NOT NULL,
FOREIGN KEY(`id_favourite`) REFERENCES food ( _id )
)
Could you please tell me how I can upgrade the food table without losing the favourites saved by the user?
Uninstall Your Apps In the Emulator or Phone And Re-install Your Apps. I In This way Think Your Problem Will be solved.
I learned a way which use SQLite3 on Android OS recently.
But it has a non acceptable part.
I can't understand why drop the table when called "onUpgrade" method of SQLiteOpenHelper.
Why need "onUpgarde" method?
If code executes "drop table", table data of old version DB will be removed, isn't it?
Why delete existing data of old DB?
How to restore existing DB data when drop the table?
[Here is learned code]
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
final String CONFIRMED_SHEETS_TABLE = "confirmed_sheets";
public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String sql = "create table" +
CONFIRMED_SHEETS_TABLE +
"_id integer primary key autoincrement, " +
"group text, " +
"num001 text, " +
"num002 text, " +
"num003 text, " +
"num004 text, " +
"num005 text, " +
"num006 text, " +
"date text)";
sqLiteDatabase.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// non acceptable part //
String sql = "drop table if exists " + CONFIRMED_SHEETS_TABLE;
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
}
If code executes "drop table", DB table data of old version DB will be
removed, isn't it?
Yup
Why need "onUpgrade" method?
If you are switching databases (for example because you added a new column), your app (usually) now depends on that change. Increasing the database version in your Helper class calls onUpgrade(), which allows you to take care of any migration to prepare the app to use your new schema.
Did you know why learned code executes "drop table"?
Convenience. It's not necessarily the right approach, but a database change can make it hard to take old data and merge it in the new table. Thus, it is easier logic-wise to simply start anew.
If you want to merge an existing and new table, have a look at this question.
You do not need to perform a DROP TABLE in onUpgrade(), as it is currently written in your code. The purpose of onUpgrade() is for your app to check if a new version of your app's database is being installed on a user's device, and if so, if there are any changes to your database, such as adding a new column, you can make those changes within onUpgrade(). If you never change your database schema, you never need to do anything in onUpgrade().
For more information and a introductory tutorial on Databases in Android, refer to the Notepad sample code here.
EDIT: also, here's an example of an onUpgrade() I wrote for one of my apps:
/**
* Handle upgrades to the database.
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(DBG) Utils.log(TAG, "DBHelper: onUpgrade()...");
// Logs that the database is being upgraded
Utils.log(TAG, "w", "Upgrading database from version " + oldVersion + " to "
+ newVersion);
/*
* Every time you add new columns to the database in the phone, you will want
* to increment the Database version above and then add a condition in here for
* upgrading to it. Otherwise it will cause upgrading users to be nontrivial and
* lead to unnecessary crashes or upgrade instructions.
*/
if (newVersion > oldVersion && newVersion <= 4) {
db.execSQL("ALTER TABLE " + TrackerDb.SomeTable.TABLE_NAME + " ADD COLUMN "
+ TrackerDb.SomeTable.COLUMN_NAME_DATE_MODIFIED + " TEXT");
}
}
OnUpgrade() is called when db versions "old and new" does not match; which means that the user wants to change Database Structure (Dropping a table, Adding new Table, Modifying Table definition).
So the OnUpgrade() should contain the logic as:
Take Backup of the existing data (e.g. Generate insert statements for existing
data).
Modify Database Structure accordingly.
Restore the data from the backup.
I'm trying to to create a database and insert some data into it but this doesn't seem to be working. Can anybody tell me what's wrong in my implementation? Here is my code for the database. Thank you.
SQLiteDatabase db = null;
db.openOrCreateDatabase("order", null);
db.execSQL("CREATE TABLE IF NOT EXISTS order ( id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, Price INTEGER)");
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', '100')");
SQLiteDatabase db = null;
db.openOrCreateDatabase.. will result in NullPointerException. You need to assign SQLLiteDatabase instance to db and then call openOrCreateDatabase on db.
Another issue is, 100 is integer, don't need in single quotes.
db.execSQL("INSERT INTO order (Name, Price) VALUES ('Paneer Tikka', 100)");
There is a really nice tutorial supplied by google. It take you through how to do the basics with the SQLite database.
http://developer.android.com/resources/tutorials/notepad/index.html
I would suggest going through that.
In that tutorial is suggests using a SQLHelper inner class something like this
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE_CELEBS);
db.execSQL(DATABASE_CREATE_CHECKINS);
Log.i("dbCreate", "must have worked");
} catch (Exception e) {
Log.i("dbCreate", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS celebs");
db.execSQL("DROP TABLE IF EXISTS checkins");
onCreate(db);
}
}
Then to get a new database you can call
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
You need to learn about SQLiteOpenHelper. Ask Google for some tutorials.
Incredibly Sqlite has much better performance "in transation" on inserts without transaction. I particularly, massive use transaction processes, or failure comes randomly at some point.