When my application starts for the first time it needs to create the database it'll be using. I don't know at what point I should be creating the database if it doesn't already exist yet, and I don't know how to ensure I don't try to create the database if it already does exist. Currently, the following works, where I execute CreateTable when the first activity in my app runs:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
base.SetContentView(Resource.Layout.SiteListLayout);
DataManager.CreateTable<Site>();
DataManager.CreateTable<PanelLog>();
DataManager.CreateTable<Trace>();
}
Basically, this works because the CreateTable method checks to see if the table already exists before creating it. However, I don't like the idea of frivolously running some code knowing it's going to fail because of some of some exception to its expectations. I'd prefer to be more explicit.
Therefore, how can I execute code the first time my app runs to test if the tables need to be created, and if so to create them? And any subsequent time my app runs it doesn't check that code.
This is what I use to create or upgrade my database, and it seems to work really well. It's a hack from various sources in the web. It creates 4 tables, unless they already exist. I haven't included the static variables but that should be clear enough to follow?
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE_2);
db.execSQL(DATABASE_CREATE_3);
db.execSQL(DATABASE_CREATE_LIST_SUB);
}
#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 " + DATABASE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_2);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_3);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_LIST_SUB);
onCreate(db);
}
}
You can use other data storage options in android.take a look at http://developer.android.com/guide/topics/data/data-storage.html#filesInternal.You may find any storage option that are specific and secure to be used by a single app and their lifetime will be until you uninstall the app.So store in it the information either you created database or not,and check that storage everytime you run that app.
Create your database at the main_activity if you want, you can even create it on the splash screen activity if you have one.
As long you don't change the tables names, they will be created only one time, which is the first time the class that contains create table commands is called.
UPDATE
Check this Website, there you ll find a very simle tutorial, a bit long but very helful, if you don't have time you can try to use the code for creating your tables.
Related
Whenever I try to run my project second time (doesnt matter if I change anything or not), I end up getting a crash. If I change the db name or version, the application starts working again.
As far as I have understood (I am new to Android Development), that after you do getWritableDatabase() the database is actually created. After that, if the database is created for the first time, the onCreate method is called in the helper class, otherwise onUpgrade is called (please correct me on the last phrase). Now my OnCreate and OnUpgrade are fairly simple:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TOI);
db.execSQL(CREATE_TABLE_HINDU);
db.execSQL(CREATE_TABLE_NEWSPAPER);
db.execSQL(CREATE_TABLE_CATEGORY);
db.execSQL(CREATE_TABLE_NEWSPAPER_CATEGORY);
Log.d(TAG, "in onCreate MySQLhelper");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TOI);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HINDU);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWSPAPER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORY);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWSPAPER_CATEGORY);
onCreate(db);
}
After the getWritableDatabase command in my DAO class, I call a class Tables where I use SQLiteStatement to preload the tables. This is where the app crashes. From the logcat, the error being "Caused by: android.database.sqlite.SQLiteConstraintException: PRIMARY KEY must be unique (code 19)".
I dont remember where but I read somewher on StackOverflow regarding a problem (I dont remember the problem either), the answer was to change the database name and try, and it had worked for OP. I tried the same and it worked for me.
So now, I have to change the database name or number for every run.
My Files:
Logcat
Tables.java
MySQLiteHelper.java
Every time you create an instance of Tables, you are inserting data into the database. This does not make much sense in general -- probably you want to move that logic into onCreate() of you MySQLiteHelper class.
If for some reason you really do want to insert data every time you create an instance of Tables, you need to use unique values for your PRIMARY KEY columns. Your current code tries to insert 1, 2, 3, and 4 each time for your four rows. That will work the first time, but the second time, those rows are already there, and so you get the unique-constraint violation.
I m following this tutorial.http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
can any body please make me clear this chunk of code.
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
Questions
What is the purpose of onUpgrade(); method?
When it is Called? as docs says this is Called when the database needs to be upgraded what does it means by upgrading the database?
Important
why we drop the table in this method and recreate?
Thanks in advance.
onUpgrade is basically for handling new db changes(could be new columns addition,table addition) for any new version of your app.
Droping the table is not always necessary in onUpgrade it all depends on what your use case is. If the requirment is to not to persists the data from your older version of app then drop should help,but if its like changing schema then it should only have alter scripts.
Upgrade means changes have been made to the database schema(version numbers are different) and it needs to be upgraded. Dropping the table and recreating is one way to do that. You could also issue "alter table" statements.
When you open your database it checks the version number and whether or not it exists. You can just "upgrade" your database rather than creating it new.
A good tutorial: http://www.vogella.com/articles/AndroidSQLite/article.html
This method is called when you update your database version. It drops the existing tables and creates it again when onCreate method is called again.
Replying to your 4 questions:
1) The purpose of onUpgrade is to manage a new database structure. You could start you app with simple features, then you need for instance to add a new column, so you need to increase the version of your database from 1 to 2 and in onUpgrade
give the instruction to add a new column, so that if the user update the app, the new column become added.
2) onUpgrade is called when you have a new version of your database and you incremented the int number in the super method( here is 1, so you eventually change it to 2)
public static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super (context,DATABASE_NAME,null,1);
}
3) Please see above regarding what does it means to update the db
4) We Drop the table and recreate, because to modify the table (example for adding a new column that fits a new feature) a logic way to proceed could be, before to "destroy"/DROP the table and then create a new one with all the data. But this can be not the way to go although recreating the data could mean that the id numbers will be consecutive( usually are not consecutive: you could have 1, 2, and..4 because 3 has been deleted), hence dropping and then creating the table again, and eventually loading the previous data you could have this id consistency.
Sometimes you may want to use ALTER instead of DROP. Why? Usually because using DROP the user loses the content already has in the database, then if you want to learn more about Best practices and more complex real life scenarios please have a look at this amazing reply
I have updated the application's database. But users who have updated the application from market will see a crash everytime app is started because new database structure is not compatible with old database. Its not good to ask them to uninstall and install the app, I need to perform an operation just for single time at the time of installation i.e. clear the old database and create new one. This should not be called everytime the app starts, only at the time of installation..or when the app starts for the first time.
I think I have clearly defined my situation, now where do I go from here? Should I bug users to uninstall and install app or its possible to do what I have asked?
Just change the version of your database and by overriding onUpgrade on your DatabaseHelper class.
private static final int DATABASE_VERSION = 2;
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CREATION);
onCreate(db);
}
Why don't you implement the onUpgrade() method of SQLiteOpenHelper?
This class provides useful onCreate() and onUpgrade() methods.
See here : Is the onUpgrade method ever called?
Or here : How to update table schema after an app upgrade on Android?
First of all it is really a bad idea to clear the old database and create a new one (Users will be really pissed seeing there data lost).
You should always try to upgrade the previous data with new columns and stuff. Instead of clearing the whole data, you should always try to alter the structure of tables without clearing the data.
One more thing is that you can upgrade to new database in onUpgrade() method of the DBHelper class.
I'm adding a table to my app's SQLite DB. All my syntax there is fine, not the issue. But I'm having some trouble getting the new table to be created properly. I added the new table....
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(CREATE_REQUESTS);
db.execSQL(CREATE_OVERRIDE);
}
My on create method. I have 3 tables. When I updated the version number, I got an error saying "table requests (referring to CREATE_REQUESTS) has already been created." A look at my onUpgrade method...
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
Led me to understand that the line db.execSQL("DROP TABLE IF EXISTS contacts"), which refers to my DATABASE_CREATE table in the onCreate method, is used to drop the old table, then the next line, onCreate(db); recreates it. I did not add requests into that execSQL line, which is what caused the error. Here is the issue: I would rather not lose the data in the two tables I already have. Is there a way to add a table like I am trying to do, and not lose all the old data? Thanks.
You can do anything you want in onUpgrade. You can use ALTER to add new columns to your table.
Worst case, if your schema is completely and entirely different, you'll have to create the new table, populate it using data from the old table, and then delete the old table.
In any case, onUpgrade was designed to allow for a smooth upgrade without any loss of data. It's just up to you to implement it properly.
if DB version : 6
Ex : There is a table with 5 columns
When you upgrade to : 7 ( I am adding 1 new column in the 3 tables)
1. We need to add the columns when creating a table
2. onUpgrade method:
if (oldVersion < 7)
{
db.execSQL(DATABASE_ALTER_ADD_PAPER_PAID);
db.execSQL(DATABASE_ALTER_LAST_UPLOADED);
db.execSQL(DATABASE_ALTER_PAPER_LABEL);
}
Where : "DATABASE_ALTER_ADD_PAPER_PAID" is query.
EX: public static final String DATABASE_ALTER_ADD_PAPER_PAID = "ALTER TABLE "
+ TableConstants.MY_PAPERS_TABLE + " ADD COLUMN " + COLUMN_PAPER_PAID + " TEXT;";
After above two operation it will works fine for the fresh install user and app upgrade user
I have an app that uses a database. At startup I check to see if my tables are missing and if so I create them. Works great.
I've noticed that if I "adb uninstall" then the next time I run my app the tables are created again (this is what I need), but what about when updating through the marketplace?
I'm in the process of releasing an update, and I've made major changes to the tables. I'd like it if the tables were completely wiped and re-created, in fact my app needs this to happen. If someone updates and has the old tables then there will be a force close.
Does anyone know the specifics of this scenario?
My tables are only for lookup, I store no user data so I dont really care about losing data on the updates.
Of course I know an option is to use some type of "version" table and check to see if I need to manually drop and create, but I was wondering if that was even needed.
Thanks.
On an update the tables are left alone. I'm going to assume you have implemented a subclass of SQLiteOpenHelper to explain this. The way Android is able to handle version changes is through the use of onUpgrade in the SQLiteOpenHelper class. This method is called from SQLiteOpenHelpers constructor if the DB version is older than the version the app expects. From inside onUpgrade is where you are going to drop your old tables and create the new ones.
onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion){
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
//we can change this to perform different behaviors
db.execSQL("DROP TABLE IF EXISTS "+MYDB.TABLE_NAME);
onCreate(db);
}
It is important to note the way Android tells if you are using a new DB version.
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
That field DATABASE_VERSION is used, so you should use a final static int member as part of your DB implementation.
Hope that helps, leave me a comment if you have questions.