1

I have an app that allows the user to save some chosen rows from a temporary table. The user is able to name the new table.

I am successfully creating a table using the name the user has input, and putting all the chosen rows from the temporary table into the new table.

However, if the table name they enter already exists, I want to notify them via Toast and have them choose another name. I am still learning sqlite - is there a way to do this?

In my head I am using some sort of if statement to check if the table exists, and then executing code, however half of it is in sqlite and half is in java. I'm not sure the correct way to do this. Any suggestions are greatly appreciated!

private void createTable() {
    dbHandler.getWritableDatabase().execSQL("CREATE TABLE IF NOT EXISTS " + favoriteName + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT , exercise TEXT , bodypart TEXT , equip TEXT );");
    dbHandler.getWritableDatabase().execSQL("INSERT INTO " + favoriteName + " SELECT * FROM randomlypicked");
SillyFidget
  • 197
  • 3
  • 16
  • You mean the code to check if a table exists in SQL ? [Like this](http://stackoverflow.com/questions/167576/check-if-table-exists-in-sql-server) ? – UDKOX May 18 '16 at 02:55
  • Kind of. In that answer, between BEGIN and END, I'm assuming you would be doing things with the database. In my case, if the table exists, I want to do nothing with the database, and also Toast the user to let them know the name has already been used. Is this possible using the format from the question you are referencing? – SillyFidget May 18 '16 at 03:05
  • Just ommit that part, take the code til BEGIN. Also, you could also try a read on the table. When the user wants a table called "name", try to read a value from "name" table with id = 1 and check the result. Maybe try to raise some exceptions... There could be many ways. – UDKOX May 18 '16 at 03:18

1 Answers1

2

Try

Cursor cursor = dbHandler.getReadableDatabase().rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName +"'", null);
if(cursor!=null) {
    if(cursor.getCount()>0) { //table already exists
        //show toast
        cursor.close();
        return;
    }
    cursor.close();
}
//create table and insert normally
Linh
  • 57,942
  • 23
  • 262
  • 279