Priyabrata Priyabrata - 28 days ago 10
Android Question

Creating table dynamically (On Button Click) In Android

I am writing an application and it needs tables to be created dynamically.
I've written the following code :

public void CreateDynamicTables(String Table_Name, String Contact_ID, String Display_Name){
dbs.execSQL("DROP TABLE IF EXISTS " + Table_Name);
String query = "CREATE TABLE " + Table_Name + "(" + CID + " TEXT PRIMARY KEY, " + DName + " TEXT);";
dbs.execSQL(query);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(CID, Contact_ID);
cv.put(DName, Display_Name);
db.insert(Table_Name, null, cv);
db.close();
}


But it crashes the application. Cannot find whats wrong with it.

Logcat:

Logcat

Answer

At some places you were using db at some places dbs

Try this code

public void CreateDynamicTables(String Table_Name, String Contact_ID, String Display_Name)       
{

       dbs = this.getWritableDatabase();
        dbs.execSQL("DROP TABLE IF EXISTS " + Table_Name);
        String query = "CREATE TABLE " + Table_Name + "(" + CID + " TEXT PRIMARY KEY, " + DName + " TEXT);";
        dbs.execSQL(query);
        dbs = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(CID, Contact_ID);
        cv.put(DName, Display_Name);
        dbs.insert(Table_Name, null, cv);
        dbs.close();
    }