在sqlite中没有调用onUpgrade

时间:2014-10-14 17:48:48

标签: java android sqlite

我正在更新我的应用。在此更新中,我必须在我的Sqlite DB中的表中添加一个字段。

以下是管理我的数据库的单个实例的文件:

DatabaseManager.java

public class DatabaseManager {
private AtomicInteger mOpenCounter = new AtomicInteger();

private static DatabaseManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
private SQLiteDatabase mDatabase;

public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
    if (instance == null) {
        instance = new DatabaseManager();
        mDatabaseHelper = helper;
    }
}

public static synchronized DatabaseManager getInstance() {
    if (instance == null) {
        throw new IllegalStateException(
                DatabaseManager.class.getSimpleName()
                        + " is not initialized, call initializeInstance(..) method first.");
    }

    return instance;
}

public synchronized SQLiteDatabase openDatabase() {
    if (mOpenCounter.incrementAndGet() == 1) {
        // Opening new database
        mDatabase = mDatabaseHelper.getWritableDatabase();
    }
    return mDatabase;
}

public synchronized void closeDatabase() {
    if (mOpenCounter.decrementAndGet() == 0) {
        // Closing database
        mDatabase.close();

    }
}

然后,主Db文件是:

public class PdvHandler extends SQLiteOpenHelper {
private static final String TAG = "com.spmkt.mobile";

// All Static variables
// Database Version
public static final int DATABASE_VERSION = 2;

// Database Name
public static final String DATABASE_NAME = "mydb.db";
....

public void dropAndCreateMetrics() {
    SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
    db.execSQL("DROP TABLE IF EXISTS " + MetricsHandler.TABLE_METRICS);
    db.execSQL(MetricsHandler.CREATE_TABLE_METRICS);
    DatabaseManager.getInstance().closeDatabase();
}

}

然后,我想在alerta表中添加一列:

AlertaHandler.java

public class AlertaHandler extends SQLiteOpenHelper {

public AlertaHandler(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, factory, version);
    DatabaseManager.initializeInstance(this);

}

public AlertaHandler(Context context) {
    super(context, PdvHandler.DATABASE_NAME, null,
            PdvHandler.DATABASE_VERSION);
    DatabaseManager.initializeInstance(this);

}

SQLiteDatabase db;

public static final String TABLE_ALERTAS = "alertas";

private static final String ALERTA_ID = "id";
private static final String ALERTA_CAPTURA_ID = "captura_id";
private static final String ALERTA_MENSAJE = "mensaje";
private static final String ALERTA_URGENT = "urgent";  // This is the column to add
private static final String ALERTA_SYNC = "sincronizado";

// private static final String ADD_URGENT_COLUMN =
// "ALTER TABLE "+TABLE_ALERTAS+" ADD COLUMN "+ +" ";

public static String CREATE_ALERTA = "CREATE TABLE " + TABLE_ALERTAS + "("
        + ALERTA_ID + " INTEGER  " + "PRIMARY KEY AUTOINCREMENT,"
        + ALERTA_CAPTURA_ID + " INTEGER," + ALERTA_URGENT
        + " INTEGER DEFAULT 0 NOT NULL, " + ALERTA_MENSAJE + " TEXT" + ", "
        + ALERTA_SYNC + " INTEGER )";

public static String DROP_ALERTA = "DROP TABLE IF EXISTS '" + TABLE_ALERTAS+"'";

public ArrayList<Mensaje> getUnSincronizedMessage() {

    ArrayList<Mensaje> lMensajes = new ArrayList<Mensaje>();
    // Select All Query
    Mensaje message;
    String messageQuery = "SELECT  * FROM " + TABLE_ALERTAS + " WHERE "
            + ALERTA_SYNC + "= 0";

    SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
    Cursor cursor = db.rawQuery(messageQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            message = new Mensaje();
            message.setId(cursor.getInt(cursor.getColumnIndex(ALERTA_ID)));
            message.setCapturaId(cursor.getInt(cursor
                    .getColumnIndex(ALERTA_CAPTURA_ID)));
            message.setMessage(cursor.getString(cursor
                    .getColumnIndex(ALERTA_MENSAJE)));
            int urgent = cursor
                    .getInt(cursor.getColumnIndex(ALERTA_URGENT));
            message.setUrgent(urgent == 0 ? false : true);
            message.setSincronizado(cursor.getInt(cursor
                    .getColumnIndex(ALERTA_SYNC)));

            lMensajes.add(message);

        } while (cursor.moveToNext());
    }
    DatabaseManager.getInstance().closeDatabase();
    return lMensajes;
}

public void addMessage(Mensaje m) {
    SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
    ContentValues values = new ContentValues();
    values.put(ALERTA_CAPTURA_ID, m.getCapturaId());
    values.put(ALERTA_MENSAJE, m.getMessage());
    values.put(ALERTA_URGENT, m.isUrgent() ? 1 : 0);
    values.put(ALERTA_SYNC, m.getSincronizado());

    // Inserting Row
    db.insert(TABLE_ALERTAS, null, values);
    DatabaseManager.getInstance().closeDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

public boolean existsMensaje(Mensaje m) {
    SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
    String sql = "SELECT COUNT(*) FROM " + TABLE_ALERTAS + " WHERE "
            + ALERTA_ID + "=" + m.getId();
    Cursor mCount = db.rawQuery(sql, null);
    mCount.moveToFirst();
    int count = mCount.getInt(0);
    mCount.close();
    DatabaseManager.getInstance().closeDatabase();
    if (count == 0)
        return false;
    else
        return true;
}

public void updateMessage(Mensaje m) {
    SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
    ContentValues values = new ContentValues();
    values.put(ALERTA_ID, m.getId());
    values.put(ALERTA_MENSAJE, m.getMessage());
    values.put(ALERTA_SYNC, m.getSincronizado());
    values.put(ALERTA_URGENT, m.isUrgent());
    values.put(ALERTA_CAPTURA_ID, m.getCapturaId());

    // updating row
    db.update(TABLE_ALERTAS, values, ALERTA_ID + " = ?",
            new String[] { String.valueOf(m.getId()) });
    DatabaseManager.getInstance().closeDatabase();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    int upgradeTo = oldVersion + 1;
    while (upgradeTo <= newVersion) {
        switch (upgradeTo) {
        case 2:
            try{
                db.execSQL(DROP_ALERTA);
                db.execSQL(CREATE_ALERTA);                  
                Log.e(TAG,DROP_ALERTA);
                Log.e(TAG,CREATE_ALERTA);
            }catch (Exception e) {
                Crashlytics.logException(e);
            }
            break;
        }
        upgradeTo++;
    }
}

我读到onUpgrade只会在getWritableDatabase运行时运行,但我不太明白发生了什么......

我应该在PdvHandler中更改我的表,因为它是定义数据库版本的文件吗? 我应该改变每个处理程序文件中的表吗? (我有1个处理程序x table = 10个处理程序)

我有点失落! 任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

  

我应该在PdvHandler中更改我的表,因为它是定义数据库版本的文件吗?我应该改变每个处理程序文件中的表吗? (我有1个处理程序x table = 10个处理程序)

每个数据库文件应该只有一个SQLiteOpenHelper

当您使用提供给onUpgrade()构造函数的参数请求的数据库模式的版本大于存储在数据库文件中的模式版本时,将调用

SQLiteOpenHelper。如果数据库文件已由一个处理同一数据库文件的sqlite帮助程序升级到您请求的版本,则不会在另一个帮助程序上调用onUpgrade()

此外,您不应该在onCreate()onUpgrade()中捕获例外情况。如果出现问题,则应该在方法之外抛出异常。

另请参阅:When is SQLiteOpenHelper onCreate() / onUpgrade() run?