android sqlite CREATE TABLE IF NOT EXISTS

johnsonjp34 picture johnsonjp34 · Feb 17, 2014 · Viewed 46.1k times · Source

Having a little problem with creating new tables. When I use the CREATE TABLE command my new tables form as they should, but when I exit the activity the app crashes and I get a TABLE ALREADY EXISTS in the logcat. If I use CREATE TABLE IF NOT EXISTS the new table isn't formed but just adds my new rows of data to a previous table and it doesn't crash. What is wrong with this? I would like to add the table without it giving me the already exists and I would like it to add without it adding rows to a different table.

SqliteHelper Class:

public class MySQLiteHelper extends SQLiteOpenHelper {


public static final String TABLE_NAME = MainActivity.NameName;

public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
public static final String COLUMN_LAT = "lat";
public static final String COLUMN_LONG = "long";
public static final String COLUMN_RADI = "radi";
private static final String DATABASE_NAME = "spraylogs.db";
private static final int DATABASE_VERSION = 1;



public static final String NEWTABLE = "CREATE TABLE  "
         + TABLE_COMMENTS + "(" + COLUMN_ID
          + " integer primary key autoincrement, " + COLUMN_COMMENT
          + " text not null," + COLUMN_LAT+ ","  + COLUMN_LONG + "," + COLUMN_RADI +  ");";

public static final String SaveIt = "CREATE TABLE IF NOT EXISTS "
         + TABLE_COMMENTS + "(" + COLUMN_ID
          + " integer primary key autoincrement, " + COLUMN_COMMENT
          + " text not null," + COLUMN_LAT+ ","  + COLUMN_LONG + "," + COLUMN_RADI +  ");";



 MySQLiteHelper(Context context) {
  super(context, context.getExternalFilesDir(null).getAbsolutePath() + "/" + DATABASE_NAME, null, DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase database) {
}

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

onCreate(db);
 } 

} 

Answer

Gabe Sechan picture Gabe Sechan · Feb 17, 2014

That's how it's supposed to work. CREATE TABLE will throw an exception if the table already exists. CREATE TABLE IF NOT EXISTS will create the table if it doesn't exist, or ignore the command if it does. If you want it to delete the old table, use DELETE TABLE IF EXISTS before CREATE TABLE. If you want to change the schema, use ALTER TABLE, not CREATE TABLE.