Is it possible to create a database table name from user input. All of the tutorials I have seen have had the table name pre-created before the app is actually ran. Ideally, I would like to pass a String to the onCreate method (that is called to first create the DB table) and use that string as the table name. Is this possible?
3 Answers
I don't use this to create the first table, but here is what I use to create new tables. The first table is mostly empty and I remove it from my listview list of tables. loc is the string I pass in. I'm in the process of switching it to a ContentProvider though
public long addTable(String loc) {
// TODO Auto-generated method stub
ourDatabase.execSQL("CREATE TABLE IF NOT EXISTS " + loc + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_2TBL
+ " TEXT NOT NULL, " + KEY_ONE + " TEXT NOT NULL, "
+ KEY_TWO + " TEXT NOT NULL);");
ContentValues cv = new ContentValues();
cv.put(KEY_2TBL, loc);
return ourDatabase.insert(loc, null, cv);
}
Comments
You will not be able to use onCreate()method to create a second table.Because it is called only when the Database is created & You will not be able to insert any String As Argument. You Can create a new method to do this.
the Method may look something like this,
public void AddDesiredTable(String TableNmae){
/*At first you will need a Database object.Lets create it.*/
SQLiteDatabase ourDatabase=this.getWritableDatabase();
/*then call 'execSQL()' on it. Don't forget about using TableName Variable as tablename.*/
ourDatabase.execSQL("CREATE TABLE IF NOT EXISTS " + TableNmae+ " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_2TBL
+ " TEXT NOT NULL, " + KEY_ONE + " TEXT NOT NULL, "
+ KEY_TWO + " TEXT NOT NULL);")
}