I have had a problem with my bdd in android, apparently everything is due to how I have structured the part ofonUpgrade
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CAJAS);
onCreate(db);
}
On some occasions the entire table is deleted, how could I do so that this never happens and avoid losing information that really needs to be saved.
Full code of my Database class
public class BasedeDatos_AgroMovil extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "agromovil.db";
public static final String TABLE_CAJAS = "cajas";
//constructor
public BasedeDatos_AgroMovil(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String TABLA_CAJAS = "CREATE TABLE " + TABLE_CAJAS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_FECHA + " TEXT," +
COLUMN_RANCHO + " TEXT," +
COLUMN_SECTOR + " TEXT," +
COLUMN_TRABAJADOR + " TEXT)";
db.execSQL(TABLA_CAJAS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CAJAS);
onCreate(db);
}
}
The method
onUpgrade
is executed when you change the version of the database, that is, when you update it and you are forced to upload its version number (DATABASE_VERSION), either because you add or remove fields in the tables or whatever. In this case, you are deleting the database every time you update its version.Meanwhile, the method
onCreate
is executed when the database is created.Thus, what you have to do in case you want to update it and change its version number is:
onUpgrade
If what you want is to do nothing, then you should not change the version. If you want to do something else and change the version number, but not delete it, you should remove the
Drop Table
, which does is delete it whenever it exists.Set to update only when the new version is greater than the current version
This applies to classes that extend SQLiteOpenHelper when an application update is performed, the onUpgrade() method is called , this is where it is validated if the version is new (application versionCode), in your case the implementation of this method is doing a DROP of the table:
Depending on your application there are tables that when updating can be removed and created again, in other cases this data is required to persist, if you require the same data simply do not call the elimination and creation of the table: