Home > Mobile >  Why can't I create second table?
Why can't I create second table?

Time:10-09

My question is related to enter image description here

i.e. the database has been created and the tables have been created.

Running the App again then exactly the same.

The following is the amended TheOneAndOnlyDBHelper to introduce the 3rd table:-

class TheOneAndOnlyDBHelper extends SQLiteOpenHelper {

    /* Note 2 table names */
    private static final String EMPLOYEE_TABLE = "employee";
    private static final String EXPENSE_TABLE = "expense";
    private static final String ANOTHER_TABLE = "another"; /* ADDED for version 2 */

    TheOneAndOnlyDBHelper(Context context) {
        super(context,Constants.DB_NAME,null,Constants.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        String query="CREATE TABLE " EMPLOYEE_TABLE " (" Constants.id " INTEGER PRIMARY KEY," Constants.firstName " TEXT, " Constants.lastName " TEXT," Constants.address " TEXT,"  
                Constants.contactNumber " INTEGER," Constants.jobStatus " TEXT," Constants.monthlyIncome " INTEGER)";
        sqLiteDatabase.execSQL(query);
        query="CREATE TABLE " EXPENSE_TABLE " (" Constants.id " INTEGER PRIMARY KEY," Constants.productName " TEXT, " Constants.productPrice " TEXT," Constants.productVersion " TEXT,"  
                Constants.productPurchaseDate " TEXT," Constants.productPurchaseTime " TEXT," Constants.productSerial " TEXT," Constants.quantityOfProduct " TEXT)";
        sqLiteDatabase.execSQL(query);

        /* NEEDED for new installs of the App which is now at Version 2 */
        query = "CREATE TABLE IF NOT EXISTS "   ANOTHER_TABLE   "("   Constants.id   " INTEGER PRIMARY KEY,"   Constants.other   " TEXT );";
        sqLiteDatabase.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        /* ADDED for Version 2 */
        if (i==1 && i1==2) {
            String query = "CREATE TABLE IF NOT EXISTS "   ANOTHER_TABLE   "("   Constants.id   " INTEGER PRIMARY KEY,"   Constants.other   " TEXT );";
            sqLiteDatabase.execSQL(query);
        }
    }
}

Noting that the version is increased from 1 to 2 as per:-

class Constants {
   public static final int DB_VERSION = 2; /* CHANGED FROM 1 to 2 */
   ....

When the App is rerun then as the version has been changed from 1 to 2, then the onUpgrade method is invoked and the 3rd table created as per:-

enter image description here

If the App is uninstalled and then rerun (as if a new person has installed the new version of the App) then as the table is now created in the onCreate method all three tables are created (same screen shot).

  • Related