Search code examples
androidsqlitesqliteopenhelper

How to stop deleting the database when doing a create table statement with SQLiteOpenHelper


I have a database that I created in SQLite in the assets directory. When I install the app in the Android emulator if the table doesn't exist it creates 1 particular table but when it does that it deletes the rest of the tables. What I want to do is that when it creates a table the other tables should remain in the database not deleted. I am not sure what is wrong or where I am droping the whole database.

This is my SQLiteHelper:

public class YAOMySQLiteHelper extends SQLiteOpenHelper {
  ...
  private static final String DATABASE_NAME = "YAOMasterDB.db";
  private static final int DATABASE_VERSION = 1;

  public YAOMySQLiteHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  private static final String DATABASE_CREATE_2 =
      "Create Table " + TABLE_DECK_LIST+ " AS SELECT SUBSTR(Name,11) AS DECK_LIST FROM sqlite_master WHERE type='table' AND Name like 'Deck Name %'";
      //  " SELECT SUBSTR(Name,11) AS DECK_LIST FROM sqlite_master WHERE type='table' AND Name like 'Deck Name %'; ";

  public static final String DROP_DECK_LIST_TABLE =
      "DROP TABLE IF EXISTS " + TABLE_DECK_LIST;

  @Override
  public void onCreate(SQLiteDatabase database) {
      database.execSQL(DROP_DECK_LIST_TABLE);
      database.execSQL(DATABASE_CREATE_2);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      Log.w(YAOMySQLiteHelper.class.getName(),
          "Upgrading database from version " + oldVersion + " to "
          + newVersion + ", which will destroy all old data");
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_DECK_LIST);

      onCreate(db);
  }
}

Solution

  • The SQLiteOpenHelper class is designed to allow your app to create the database with SQL statements in the onCreate on onUpdate methods.

    This database file gets created in your app's data directory. Nothing gets deleted; you app just never accesses the database file in the assets folder.

    To use the database from the assets folder, you have to copy it from there. The easiest way to do this is to use a class such as SQLiteAssetHelper.