2012-04-28 4 views
2

Я пытаюсь получить это право, но я не знаю, чего мне не хватает. У меня есть приложение для Android, и я хочу добавить к нему еще одну таблицу. Однако я не могу этого сделать, и у меня нет исключений (не нравятся эти тихие убийцы !!).create table on Upgrade

Ниже мой код мой SQLiteHelper класс

public class DbCreator extends SQLiteOpenHelper { 

public DbCreator(Context context) { 

    super(context, Constants.DB_NAME, null, Constants.NEW_VERSION);//NEW_VERSION=2 

    this.myContext = context; 
} 

//Rest of code 

//Checks if DB is present and create if reqd. 
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 : " + e); 

     } 
    } 

} 

    //Check DB is present 
    private boolean checkDataBase() { 

    SQLiteDatabase checkDB = null; 

    try { 
     String myPath = Constants.DB_PATH + Constants.DB_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, 
       SQLiteDatabase.OPEN_READONLY); 

    } catch (SQLiteException e) { 
     Log.v("DB", "No DB"); 
     // database does't exist yet. 

    } 

    if (checkDB != null) { 

     checkDB.close(); 

    } 

    return checkDB != null ? true : false; 
} 

/** 
* Copies your database from 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.getResources().openRawResource(
      R.raw.diary_database); 

    // Path to the just created empty db 
    String outFileName = Constants.DB_PATH + Constants.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(); 

} 

    //**This is the problem area 
    @Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    Constants.log(TAG, "Upgrading started..."+db.getVersion()); 
    if (db.getVersion() == Constants.OLD_VERSION) { 
      db.beginTransaction(); 
     Constants.log(TAG, "Upgrading started...transaction"); 
     db.execSQL("create TABLE Thought( StartDate DATETIME, Content TEXT, EndDate DATETIME, Title TEXT)"); 
     db.setVersion(Constants.NEW_VERSION);//NEW_VERSION=2 
      db.endTransaction(); 
     Constants.log(TAG, "Upgrading started...transaction finished"); 

    } 

} 

Худшая часть я вижу все журналы происходит и даже запрос выполняется успешно, когда я это сделать на консоли.


редактирует

Мой DB не обновляется: -

Я вытащил мою БД из эмулятора и даже видел журналы от версии No.is не changed.I использование ниже линий в моя активность, чтобы посмотреть версию БД.

DbCreator dbCr = new DbCreator(this); 
SQLiteDatabase myDataBase = dbCr.getMyDatabase(); 
Constants.log(TAG, "Db Version : "+myDataBase.getVersion()); 
+0

Как вы определяете, что он не сработал? – Barak

+0

@Barak: добавил logs.see редактирует .. –

ответ

5

Я настоятельно рекомендую вам перейти на SQLiteAssetHelper, который имеет весь пакет-зе-база-в-приложение шаблон выработанный.

Тактически, вы не совершаете транзакции. Правильный рецепт для операций с несколькими операторами является:

try { 
    db.beginTransaction(); 

    // do SQL here 

    db.setTransactionSuccessful(); 
} 
finally { 
    db.endTransaction(); 
} 

setTransactionSuccessful() Без вызова endTransaction() будет делать ROLLBACK.

+0

выглядит красиво ... попробует ... спасибо –

+0

да это делается. Просто попробовал db.setTransactionSuccessful(), но даже SQLiteAssetHelper кажется очень приятным и легким. Я думал использования версии приложения в качестве проверки onUpgrade и наличия БД с новой таблицей в моем активе. Таким образом, у новых пользователей будет даже самая последняя таблица. –

+0

Полезно знать об AssetHelper. – Khan