2

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

10
  • can you provide the LogCat Error Commented Feb 27, 2014 at 12:28
  • added logcat to the main thread ^^ Commented Feb 27, 2014 at 12:31
  • line 62 : dbs.execSQL("DROP TABLE IF EXISTS " + Table_Name); Commented Feb 27, 2014 at 12:35
  • 1
    Did you initialize dbs anywhere? It's not in the code provided... Commented Feb 27, 2014 at 12:39
  • Nope, that led to the problem. Now it works. Commented Feb 27, 2014 at 12:48

2 Answers 2

2

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();
    }
Sign up to request clarification or add additional context in comments.

4 Comments

I used dbs(global variable) to to create the table and db(local) to insert data in the table. However, changing db to dbs, didn't help and results in the same error.
@Priyabrata try Log.i and find till which step does it executes.. Will be easier to help you out
It executes the first line and crashes. i.e DROP TABLE IF EXISTS line
do u have this code dbs = this.getWritableDatabase();
2

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.

1 Comment

Spot on!! That Worked!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.