Reputation: 1232
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:
Upvotes: 2
Views: 4927
Reputation: 8598
If NullPointerException happens - as you say - on line:
dbs.execSQL("DROP TABLE IF EXISTS " + Table_Name);
then most likely your dbs is not initialized. Initialize it before using with:
dbs = getWritableDatabase();
Also, check if Table_Name is not null too.
Upvotes: 2
Reputation: 4001
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();
}
Upvotes: 2