Replace sql database but keep old records - android

After a lot of work I managed to build my first app, but I stick with one question. For my app I am using a sql database.. Suppose I want to add 30 records to a certain table. How is it possible that when I put a new version in the android market with a new sql table to use this one for the future, but to keep the records of the previous database?
Does it has to do something with:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
EDIT
my databasehelper code:
public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.test.com/databases/";
private static String DB_NAME = "quizDb";
private SQLiteDatabase myDataBase;
private final Context myContext;
private Cursor c;
static int numberOfLevels = 10;
private final static int DB_VERSION = 2; // = until level 10
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (!dbExist) {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if (c != null)
c.close();
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public File getDatabasePath(String name) {
File file = myContext.getDatabasePath(name);
return file;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("ATTACH DATABASE ? as AttachedDB",
new String[] { getDatabasePath("quizDbNew").getPath() });
db.execSQL("INSERT OR IGNORE INTO questions (_id, file, answer, level) SELECT _id, file, answer, level FROM AttachedDB.questions");
db.execSQL("DETACH AttachedDB");
}

The concept of using "DROP TABLE" in onUpgrade() is as primitive as database management gets, however more useful techniques require more SQL savvy. A smarter way to upgrade your databases by using "ALTER TABLE" to add new columns or otherwise finagle the old data into your new schema.
Addition
Below in the comments you stated (more or less):
I want to copy the content from my backup file of Db v1 into my current Db v2
So let's set up a couple hypothetical tables:
Database Version One (DBv1):
CREATE TABLE Foo(_id INTEGER PRIMARY KEY, bar TEXT, bar2 TEXT, bar3 TEXT);
Database Version Two (DBv2):
CREATE TABLE Foo(_id INTEGER PRIMARY KEY, bar2 TEXT, bar4 INTEGER);
First let's see a regular upgrade from DBv1 to DBv2. SQLite only supports ADD COLUMN and RENAME TO, not REMOVE COLUMN or anythings else. So we have to re-create the entire table:
#Override // DBv1 => DBv2
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("ALTER TABLE Foo RENAME TO OldFoo");
db.execSQL("CREATE TABLE Foo(_id INTEGER PRIMARY KEY, bar2 TEXT, bar4 INTEGER)");
db.execSQL("INSERT INTO Foo (_id, bar) SELECT _id, bar2 FROM OldFoo");
db.execSQL("DROP TABLE OldFoo");
}
Again this created a table with DBv2's schema and kept all of the valid, existing data from DBv1 by inserting the appropriate columns into DBv2. (Then it removed the old data by dropping the old table.)
You have wisely chosen to backup your database over time in a separate file, but now you want to bring the old data into the new table schema. To start make sure that your backup SQLite file is in the same directory as your current SQLite file (data/data/<reverse.package.name>/databases/). It will obviously need a unique name, let's call it DBBackup. Now let's attach DBBackup to your current database and perform a similar action from above:
// DBBackupv1 => DBv2
public void restore(SQLiteDatabase db) {
db.execSQL("ATTACH DATABASE ? as AttachedDB", new String[] {getDatabasePath("DBBackup").getPath()});
db.execSQL("INSERT OR IGNORE INTO Foo (_id, bar2) SELECT _id, bar2 FROM AttachedDB.Foo");
db.execSQL("DETACH AttachedDB");
}
I used INSERT OR IGNORE to restore any rows that were deleted but left the current existing rows untouched. You can use INSERT OR REPLACE to revert to the backed up version. There are many more options to suit your needs.

Related

Updating SQLite database when releasing new version of the android app on the store

I'm using sqlite in my android app, my database file is called data.db. Let's suppose that I have two table in it one is having static values(read only) and second is saves dynamic values and pushed the app to the playStore.
In the next version I updated the data.db and I updated the values in first table, added new columns in second table and added third new table and push the app to the PlayStore. So how I can check if user is updating the app and what is best possible way to save existing data and how I can update data.db programmatically when it is a update not a fresh install?
You can use SQLiteOpenHelper's onUpgrade method. In the onUpgrade method, you get the oldVersion as one of the parameters.
In the onUpgrade use Switch case and in each of the cases use the version number to keep track of the current version of Database that was sent for each new Version of Database.
Its best that you loop over from oldVersion to newVersion, incrementing version by 1 at a time and then upgrade the database stepbystep. This is very helpful when someone with Database version 1 upgrades the app after a long time, to a version using database version 7 and the app starts crashing because of certain incompatible changes.
Then the updates in database will be done stepwise, covering all possible cases i.e incorporating the changes in the database done for each new version and thereby preventing your application from Crashing.
There are two ways
1] Changed database version so that when user updates an app SQLiteOpenHelper's onUpgrade() method gets executed in this method you can write a code to drop tables n create new tables according to new schema and send network calls to fetch data.
2] Push app with pre-installed db.
Create database with db version and save it in assets folder.
Whenever app runs compare versions of assets's db & app's db.
if asset's db version is higher than app's db then this means you need to update database.
Directly copy Assete's db into folder structor and sends delta call to fetch data.
In this example you have add a new column so the changes in this case should be like this (here you gonna not lose your data).
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " +
"name_of_column_to_be_added" + " INTEGER";
db.execSQL(sql);
}
I advice you to use http://www.activeandroid.com/ library. It supports migrations. You just need to write [n].sql files in assets/migrations folder for n version of you database model. Active android carries about existing version and applies required migration.
private static String DB_PATH = Environment.getDataDirectory()+"/data/package-name/databases/";
private static String DB_NAME = "name_of_the_database"; // student.db
private void copyDataBase() throws IOException
{
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty d inb
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
//Copy successful
outFileName = DB_PATH + DB_SUCCESS;
myOutput = new FileOutputStream(outFileName);
myOutput.write(1);
myOutput.flush();
myOutput.close();
}
package com.example.sqllite_db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabseAdapter extends SQLiteOpenHelper
{
public static String DatabaseName="NewDatabase";
public static int DatabaseVersion=1;
public DatabseAdapter(Context context)
{
super(context,DatabaseName,null,DatabaseVersion);
// TODO Auto-generated constructor stub
}
/*public static String TableUser="tb1";
public static String keyId="id";
public static String keyName="name";
public static String keyPass="pass";*/
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
String createQuery="create table tb1(name text,pass text);";
db.execSQL(createQuery);
//String createQuery1="create table tb2(pass text);";//("+keyName+"text,"+keyPass+"text);";
//db.execSQL(createQuery1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("drop table tb1");
onCreate(db);
//db.execSQL("drop table tb2");
//onCreate(db);
}
}
drop the database in on Upgrade method then again call on Create method in it and your database will update when you upload new database.

SQLiteOpenHelper: onCreate() method not called on physical device

I have done many tests on an android emulator running in version 4.4.
On my app I create a sqlite database with one table using SQLiteOpenHelper:
package com.findwords.modeles;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import com.findwords.MainActivity;
import com.findwords.controleurs.MenuController;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by louk on 02/01/14.
*/
public class DictionaryDbHelper extends SQLiteOpenHelper{
// declare constants fields
private static final String DB_PATH = "/data/data/com.findwords/databases/";
private static final String DB_NAME = "dictionary_db";
private static final int DB_VERSION = 1;
// declared constant SQL Expression
private static final String DB_CREATE =
"CREATE TABLE dictionary ( " +
"_id integer PRIMARY KEY AUTOINCREMENT, " +
"word text NOT NULL, " +
"definition text NOT NULL, " +
"length integer NOT NULL " +
");";
private static final String DB_DESTROY =
"DROP TABLE IF EXISTS dictionnary";
/*
* constructor
*/
public DictionaryDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = MenuController.getInstance().getMainActivity().getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/*
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
try {
createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DB_DESTROY);
onCreate(db);
}
}
Moreover I have written an adapter with a method open:
/*
* open database connection
*/
public DictionaryDbAdapter open() throws SQLException {
mDbHelper = new DictionaryDbHelper(mContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
It's working well on the emulator so the onCreate() method of the SQLiteOpenHelper class is called and create the database, but is not called on my phone (Google Nexus 5).
My phone is not rooted so I can't access the folder /data/data/com.myapp/databases .
However I want this application to work on any phone so I don't want to root my phone.
Thanks in advance to anyone who could help me.
Let i try to explain you some things.
In an application to connect to the database , we specify the name and version of the database . In this situation, the following may occur :
1) There is no database . This may be for example in the case of initial setting program. In this case, the application itself must create the database and all the tables in it. And further, it is already working with the newly created database.
2) Database exists, but its version is outdated. It may be the case update. For example a new version of the program need additional fields in the old tables or new tables . In this case, the application must update existing tables and create new ones if necessary.
3) There is a database and its actual version . In this case, the application successfully connects to the database and running.
As you know , the phrase " application must " tantamount to the phrase " the developer must ", ie it is our task . To handle the situations described above , we need to create a class that inherits for SQLiteOpenHelper. Call it DBHelper. This class will provide us with methods to create or update the database in case of their absence or obsolescence.
onCreate - a method that will be called if the database to which we want to connect - does not exist(it's your case)
The onCreate method is called only for the first time - when the DB is actually created. So if you uninstall your app and then install it again - it will get called, but if you install on top of the existing copy onCreate will not be called (since the DB already exists)
As #Asahi said, Database is only created only if you reinstall the app. But since you said that My phone is not rooted so I can't access the folder /data/data/com.myapp/databases, I want to point out that you can connect your mobile to the computer, install the correct USB drivers and use DDMS to see the file structure of your mobile phone. There you can see the database of your app along with the Shared Preferences and other files.
PS :- To see all the folder of real device on ddms you need root access. If your device is not rooted and you don't want to root your one then you can install the device on emulator which shows all folders in DDMS.

Fetch data from existing sqlite database

I am having an existing sqlite database. I am developing an android app and I want to connect it with this existing sqlite DataBase.
Problem 1:
I have already included the sqlite database in my project via "DDMS push database function" as per my instructor's advise. Now I want to fetch the data from database, do I need to use SQLiteOpenHelper. If yes, how to use it and what will be coded in onCreate(SQLiteDatabase db) function and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) function as we already have the Database with us, we don't really need to create it.
Problem 2:
What should be done to simply fetch the required data from the existing database.
Being a newbie, I am quite confused, can someone please explain these concepts and guide me to overcome this issue. Any help would be appreciated.
I have seen a tutorial also for this purpose as sugggested by #TronicZomB, but according to this tutorial (http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/), I must be having all the tables with primary key field as _id.
I have 7 tables namely destinations, events, tour, tour_cat, tour_dest, android_metadata and sqlite_sequence. Out of all, only tour_dest is not fulfilling the conditions of having a primary key named as _id. How to figure out this one?
Following is the screenshot of table which is lacking the primary key field necessary for binding id fields of database tables.
The onCreate and onUpgrade methods will be empty since you already have the database. There is a great tutorial on how to achieve this here.
You could then access the database like such (example):
public ArrayList<String> getValues(String table) {
ArrayList<String> values = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT value FROM " + table, null);
if(cursor.moveToFirst()) {
do {
values.add(cursor.getString(cursor.getColumnIndex("value")));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return values;
}
Unless you are very comfortable with queries, databases, etc. I highly recommend you use http://satyan.github.io/sugar/ , it will also remove a lot of the boiler plate code required to do sqlite in Android
1. If DB already exists, onCreate will not invoke. onUpgrade will be invoked only if you will change DB version. onUpgrade you should to use if there some changes in your APP's database, and you have to make migration on new structure of data smoothly.
public class DbInit extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "name";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE = "create table connections . .. . ...
public DbInit(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (isChangeFromToVersion(1, 2, oldVersion, newVersion)) {
//Execute UPDATE here
}
}
private boolean isChangeFromToVersion(int from, int to, int oldVersion, int newVersion ) {
return (from == oldVersion && to == newVersion);
}
....
2. Simple example how to open connection to DB and get cursor object.
public class DAO {
private SQLiteDatabase database;
private DbInit dbHelper;
public ConnectionDAO(Context context) {
dbHelper = new DbInit(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public Connection getConnectionById(long id) {
Cursor cursor = null;
try {
open();
cursor = database.query(DbInit.TABLE_CONNECTIONS, allColumns, DbInit.COLUMN_ID + " = '" + id + "'", null, null, null, null);
if (!cursor.moveToFirst())
return null;
return cursorToConnection(cursor);
} finally {
if (cursor != null)
cursor.close();
close();
}
}
private Connection cursorToConnection(Cursor cursor) {
Connection connection = new Connection();
connection.setId(cursor.isNull(0) ? null : cursor.getInt(0));
connection.setName(cursor.isNull(1) ? null : cursor.getString(1));
.....
.....
return connection;
}

How do i upgrade my pre-populated sqlite database on my device without re-creating tables?

I have my code below. It correctly reads my sqlite database file(that i have already created using the SQLite Database Browser) in my assets folder - moves it to the /data/data/packagename/databases/ path on my device then i am able to use a query and cursor to get my information and it works great. Code here:
public class DatabaseHelper extends SQLiteOpenHelper {
private Context myDbContext;
private static String dbName = "restaurant.db";
private static String outfilePath = "/data/data/dev.mypackage.com/databases/";
private static String path = outfilePath + dbName;
private static SQLiteDatabase db;
public DatabaseHelper(Context context){
super(context, dbName, null, 2);
this.myDbContext = context;
db = openDb();
String s = "select * from menu";
Cursor c = db.rawQuery(s, null);
Log.e("DB Constructor Row count", String.valueOf(c.getCount()).toString());
while(c.moveToNext()){
Log.e("DB Constructor", c.getString(c.getColumnIndex("category")));
Log.e("DB Constructor", c.getString(c.getColumnIndex("menuItem_id")));
Log.e("DB Constructor", c.getString(c.getColumnIndex("title")));
Log.e("DB Constructor", c.getString(c.getColumnIndex("desc")));
Log.e("DB Constructor", c.getString(c.getColumnIndex("price")));
Log.e("DB Constructor", c.getString(c.getColumnIndex("icon")));
}
c.deactivate();
c.close();
}
private void copyDataBase(File dbFile) throws IOException {
try{
InputStream dbStream = myDbContext.getAssets().open(dbName);
OutputStream newDbFile = new FileOutputStream(outfilePath + dbName);
byte[] buffer = new byte[1024];
int length;
while((length = dbStream.read(buffer)) > 0){
newDbFile.write(buffer);
}
newDbFile.flush();
newDbFile.close();
dbStream.close();
}
catch(IOException e){
throw new IOException("trying to copy the database - ERROR: " + e.getMessage());
}
}
private SQLiteDatabase openDb() throws SQLiteException{
File dbFile = myDbContext.getDatabasePath(dbName);
if(!dbFile.exists()){
Log.e("openDb", "file does not exist");
try {
copyDataBase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public void loadRestaurantInfo(){
}
#Override
public void onCreate(SQLiteDatabase db){
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
Now i had to go back and add a row of information to one of the tables(in the database in the assets folder), using the SQLite Brower, - but that is not being reflected in my cursor output - I understand why this is happening - because if(!dbFile.exists()) fails so there is no copying to be done. So my question is - is what code do i need to add to make this work? I never created the tables with code so i dont see how useful the onUpgrade method is going to be for me.
You have three options:
Use onUpgrade() (preferred)
Delete the existing database and copy the new one (not a good idea)
Copy the data in the existing database, delete the existing database, copy the new database, insert data from old database into new database (too much work when the new database schema can be upgraded in onUpgrade).
So, to answer your question, you upgrade your database in onUpgrade() without having to recreate any tables.
On the other hand, if you just added a new row to a particular table, the database schema has not changed and you can just insert the new row at runtime... of course, not knowing what your application's purpose is this may not be a good idea as you can easily lose track of changes to your "static" database.
The "right" way to do things is quite different from how you've set out. Rather than go there, I'll assume you want to keep your current method of creating your database and I'll offer a suggestion to work with it. Add a table to your database which has a single row of meta data, which will include the database version (as well as anything else you like). If the database file already exists, open it and check the version. If the version is old, close it and replace it.

Database onUpgrade from Assts Folder

When my app is created, my database is copied from the assets folder to my app.
Now if i want to do an onUpgrade, i just want to overwrite all Tables EXCEPT of one.
But how can i do this?
I just can write the whole database or nothing...
Please help me with this.
This doesnt work of course, because it doesnt overwrite the existing tables, it just backups the one i do not replace..
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
myDataBase = this.getWritableDatabase();
} else {
myDataBase = this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("onUpgrade", "newVersion: "+newVersion+", oldVersion: "+oldVersion);
try{
if(newVersion > oldVersion){
db.execSQL("ALTER TABLE Results RENAME TO temp_Results");
db.execSQL("CREATE TABLE Results (lektionenId INTEGER PRIMARY KEY, testPassed Integer, lektionPassed Integer)");
db.execSQL("INSERT INTO Results (testPassed, lektionPassed) SELECT testPassed, lektionPassed FROM temp_Results");
db.execSQL("DROP TABLE IF EXISTS temp_Results");
}
} catch(Exception e){
Log.i("exc", ""+e);
}
}
EDIT:
Where i call the Database:
myDbHelper = new LernAppOpenHelper(this, "LernApp", DbConfig.DB_VERSION_LERNAPP);
try {
String[] columns = {"_id","description"};
myDbHelper.createDataBase();
myDbHelper.openDataBase();
cursor = myDbHelper.getQuery("Uebersicht", columns, null, null, null, null, null);
And my onUpgrade Method:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion){
if("LernApp".equals(DATABASE_NAME)){
myContext.deleteDatabase(DATABASE_NAME);
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
}
Step #1: Copy your table data from the old database into memory.
Step #2: Restore your database from your copy in assets.
Step #3: Update your new database from the table data in memory.
If the table might be too big for that, copy the data to a file and then back from a file.
EDIT
Or:
Step #1: Copy your old database (the one being replaced) to a new database using standard Java file I/O.
Step #2: Restore your database from your copy in assets.
Step #3: Open both databases.
Step #4: Load the table you are keeping from the old database and pour its contents into the new database. Be sure to watch your transactions: the default of one-transaction-per-statement can make this sort of work very slow.
Step #5: When done, close the old database and delete it.

Categories

Resources