How to make onUpgrade() statements run even on first installation? - android

In my application i have a database which is created using DB queries in the DBHelper class. I want the onUpgrade statement to run on installation of the apk as there is a possiblity that the user might unistall and install the same application.
In this case it becomes the first installation on the device and the onUpgrade does not run which causes the application to crash.
It works perfectly if the new app is updated on the previous app.
How do i reslove this?? What is solution for such cases??
Please help !! Thanks in Advance !!
Here is my DbHelper.java
public class Dbhelper extends SQLiteOpenHelper {
public Dbhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE_IMAGE);
database.execSQL(TABLE_CREATE_ATTEDANCE);
database.execSQL(TABLE_CREATE_STOCK);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.e("","upgrade ");
database.execSQL("ALTER TABLE stock ADD db_stock_id varchar(100)");//1.1
//
}
public void dropandcreate(SQLiteDatabase database)
{
database.execSQL("DROP TABLE IF EXISTS image");
database.execSQL("DROP TABLE IF EXISTS attendance");
database.execSQL("DROP TABLE IF EXISTS stock");
onCreate(database);
}
}

Call it yourself:
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE_IMAGE);
database.execSQL(TABLE_CREATE_ATTEDANCE);
database.execSQL(TABLE_CREATE_STOCK);
onUpgrade(database, VERSION);
}

Related

Table not creating on android device but creating on the virtual device

So I am trying to create a Database and a table in android studio. The database is created successfully but table is not creating when I am using my android phone but both the database and the table are created when I use Virtual device from the AVD.
public class Databases extends SQLiteOpenHelper {
public static final String dbname = "AttendanceDb11";
public Databases(#Nullable Context context) {
super(context, dbname, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE Student12 ( _id INTEGER PRIMARY KEY AUTOINCREMENT, Name Text)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("Drop table if exists Student12");
onCreate(db);
}
}
Here is my code
It looks like that app was already installed before you created the tables. I would do one of the following:
1: Uninstalling and re-installing the app.
2: The best and better approach is to drop and recreate table in onUpdate method, and increase the db version whenever you change the schema.

how to add table to the database when database is already created in android?

I have created a database with a table.I want to add more tables dynamically to that database on the user's command.
The onOpen() method is not useful as it also changes my previous tables that already exist in the database.
I assume you are using SQLite database. If that is the case, a working solution exists here:
Create new table in existing DB in separate SQLiteOpenHelper class.
see rmkrishna's answer from that post, below:
First check the current database version for this database
private final static String DATABASE_NAME = "MainDB";
private static final int DATABASE_VERSION = 1;
public BaseSQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and increment the database version(DATABASE_VERSION), and add your new table query in on Upgrade and oncreate method like below.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("old query no need to change");
db.execSQL("Create your new table here");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
db.execSQL("Create your new table here as well this for update the old DB");
}
}

Confusing with upgrading ORMLite schema

I've added a column(description) to my table account. I also read this guild to upgrade my database. However, I had a bit confusing of what is getHelper() method in this code:
Dao<Account, Integer> dao = getHelper().getAccountDao();
// change the table to add a new column named "description"
dao.executeRaw("ALTER TABLE `account` ADD COLUMN description INTEGER;");
and where did it come from? I didn't see getHelper() was declared in my DatabaseHelper class. Can someone help me?
You should have a class extending OrmLiteSqliteOpenHelper where you create the tables (in onCreate) and update them (in onUpgrade):
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "database.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Account.class);
} catch (SQLException e) {
throw new RuntimeException("Error when create database tables", e);
}
}
#Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
database.execSQL("ALTER TABLE `account` ADD COLUMN description INTEGER;");
//same as:
//AccountDAO dao = getDao(Acount.class);
//dao.executeRaw("ALTER TABLE 'account' ADD COLUMN description INTEGER;");
}
}
OrmLiteBaseListActivity, OrmLiteBaseService and
OrmLiteBaseTabActivity provide a method getHelper to access the
database helper whenever it is needed and will automatically create
the helper in the onCreate() method and release it in the onDestroy()
method.
Furthermore, if you are using classes above, you should have something like this:
public class MyACtivity extends OrmLiteBaseActivity<DatabaseHelper> {
//In this class, you can call getHelper() to obtain the DatabaseHelper instance
}

Android onUpgrade gets invoked every time

I am trying to upgrade a certain table by adding a column to a Sqlite table in my android app.I have added an alter table statement in the onUpgrade method of my DBHelper.
Here are the problems that I am seeing
I changed the value of Database version from 1 to 2, so ideally now the onUpgrade should get called.It does get called, but it gets called everytime I instantiate the class.As a result I get a column already exists error.
Here is the onUpgrade method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.d("old Version",oldVersion+"");
Log.d("New Version",newVersion+"");
db.beginTransaction();
try
{
String DATABASE_UPGRADE;
DATABASE_UPGRADE="alter table "+DATABASE_TABLE_MESSAGES+" ADD COLUMN "+ IS_READ+ " integer DEFAULT 0;";
db.execSQL(DATABASE_UPGRADE);
Log.d("upgrade", "Successful");
db.setTransactionSuccessful();
}
finally
{
db.endTransaction();
}
}
}
I am wondering why the onUpgrade gets called each time!!!
In the constructor of your database helper are you correctly passing the new version number?
EDIT: should look like this
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and DATABASE_VERSION should be 2.

Getting an Android Database Setup?

Typically, for a WinForm or a Web App, I create the database and tables through the RDBMS or through a separate install process. However, I haven't seen anything of the sort in Android. All the examples I've seen have the database creation scripts embedded in an activity like this.
The best thing I can come up with now is to call a method from the data access constructor to check whether the database is installed - if not - install it. However, this seems like a lot of overhead to me.
What's the cleanest way to execute a android database install and then forget about it?
When using SQLLiteOpenHelper (http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html), the onCreate method will be called only if the database doesn't exist. onUpgrade will be called when a new version of the database is introduced.
IF the database already exists, and no version upgrade occured, these methods won't be executed.
There is no need for implementing if-else checks in your activity.
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);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);
db.execSQL(DATABASE_UPGRADE);
}
}

Categories

Resources