无法创建数据库android

时间:2014-01-17 11:04:16

标签: java android sql

我创建了一个从SQLiteOpenHelper扩展的DatabaseHandler类。我在另一个项目中使用了相同的类,它工作得很好,但是当我将它导入到当前项目的目录中时,它无法正常工作。它甚至没有创建数据库。以下是创建数据库和表的方法。

private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "mydatabase.db";

// Contacts table name
private static final String TABLE_WORDS = "words";
private static final String TABLE_SETS = "sets";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_WORD = "word";
private static final String KEY_DEFINITION = "definition";
private static final String KEY_WORDS_SET_ID = "wordssetid";

private static final String KEY_SET_NAME = "setname";
private static final String KEY_SET_ID = "setid";



public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {

    String createWordTable = 
            "CREATE TABLE IF NOT EXISTS " + TABLE_WORDS+ "("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_WORD + " TEXT,"
            + KEY_DEFINITION + " TEXT," 
            + KEY_WORDS_SET_ID+" INTEGER) ";
    String createSetTable = 
            "CREATE TABLE "+TABLE_SETS+"("
            +KEY_SET_ID+ " INTEGER PRIMARY KEY, " 
            +KEY_SET_NAME+ " TEXT) ";
    db.execSQL(createWordTable );
    db.execSQL(createSetTable);
    db.close();
}

在Activity类中创建和使用对象

private DatabaseHandler dbHandler;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_browse_sets);
    //...
    //...
            //...
    dbHandler = new DatabaseHandler (this);

}

我在另一个项目中做了同样的事情,但现在它做得很好。是什么原因?

1 个答案:

答案 0 :(得分:0)

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    SQLiteDatabase db=this.getWritableDatabase();
    onCreate(db);
}

如果不起作用:

在DatabaseHandler类上创建此方法

public void createDB()
{
    SQLiteDatabase db= this.getWritableDatabase();
    onCreate(db);
}

在你的Activity类

DatabaseHandler dbHandler=new DatabseHandler(this);
dbHandler.createDB();