0

我写了一个方法,可以让你在数据库中添加一个“单词”。一旦我调用 addWord() 方法,它会在尝试 database.insert() 时引发 Null 指针异常。

public class DatabaseControl {

// columns for table
public static final String KEY_ROWID = "_id";
public static final String KEY_SYNID = "synsetID";
public static final String KEY_WORD = "synsetID";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_POPULARITY = "popularity";

// table name
public static final String DATABASE_TABLE = "wordnet"; // Name of the Database

private Context context;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;

public DatabaseControl(Context context){
    this.context = context;
}

public DatabaseControl open() throws SQLiteException {
    dbHelper = new DatabaseHelper(context);
    database = dbHelper.getWritableDatabase();
    return this;
}

public void close(){
    dbHelper.close();
}

public long addWord (String synId, String word, String description, int popularity) {
    ContentValues setUpVals = createContentValues(synId, word, description, popularity);
    // SEEMS TO THROW NULL POINTER EXCEPTION
    return database.insert(DATABASE_TABLE, null , setUpVals); 
}

我在这里调用这个方法:

private void populateDatabase(){
    try {
         long rowId = 0;
         rowId = dbControl.addWord("testSyn","","",1); // Add a row to the database for test
    } 
    catch (SQLiteException e){
      e.printStackTrace();
    }

不太明白为什么会抛出这个错误,而且我不完全理解 insert() 中的第二个参数,所以据我所知可能是这样:/

4

1 回答 1

0

试试这种方式:

private void populateDatabase()
{    
    try {
        long rowId = 0;         
        rowId = dbControl.addWord("testSyn",null,null,1); 
    } 
    catch (SQLiteException e){
        e.printStackTrace();
    }
于 2012-12-23T08:25:07.773 回答