开发者

Not able to create a database once It was deleted

I am doing a database programming and it was working fine. But after I called db.deleteTitle(1); I am not able to create my database again. c.moveToFirst() is always returning null.

delButton.setOnClickListener(new OnClickListener(){
    @Override
     public void onClick(View v) {
     db.deleteTitle(1);}});

then another function is there to add data ini database

private void saveDataInDB()
{
    try
    {
         db.open();      
             db.insertInDb
            (
                name.getText().toString(), mobileNumber.getText().toString()                    
            );              

          Cursor c = db.getTitle(1);
          if (c.moveToFirst())        
                DisplayToast(c);
           else
           {
                Toast.makeText(this, "No title found", **I should not get this :(**
                        Toast.LENGTH_LONG).show();
           }

            db.close();
    }开发者_StackOverflow社区
    catch (Exception e)
    {
        Log.e("Save Error", e.toString());
        e.printStackTrace();
    }
}

I don't know why this time it is failing though it was working well before. Please guide. Thanks, Shaista


You can either delete your database manually by using the adb tool or you can bump your database version number (assuming your code is like the Notepad app) which will run the database creation code again the next time you open it.

--EDIT - Database helper code -

    private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS random_table");
        onCreate(db);
    }
}

This is the database helper class I use. Same stuff as you see in the Android Notepad tutorial. Increment the DATABASE_VERSION number (say from 1 to 2) if your table structure changes. onUpgrade will be called and will remove the old version and then run onCreate again to create the new table/tables.


If you are deleting the database, you need to recreate it before you can access it. You must re-run the database create statements, otherwise as far as your application knows, that database does not exist anymore.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜