Creating table dynamically (On Button Click) In Android

久未见 提交于 2019-12-12 09:10:25

问题


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:


回答1:


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();
    }



回答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.



来源:https://stackoverflow.com/questions/22068518/creating-table-dynamically-on-button-click-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!