我插入数据库时​​的NullPointerException(android)

时间:2012-05-03 10:52:03

标签: android database insert

我有一些数据写入数据库(三个字符串); 我有一个私有类DBHelper扩展SQLiteOpenHelper 我有 dataBase = dbHelper.getWritableDatabase(); 当我执行dataBase.insert()时,我有一个nullPointerException。

我在debuger中检查了我的数据并且它们不等于null;

DBHelper:

private class DBHelper extends SQLiteOpenHelper { //for write and read data from DB

static final String GROUPPS = "groupps";
static final String IMPORTANCE = "importance";
static final String NAME_OF_TABLE = "Person";
static final String PERSON_KEY = "perskey";

    private static final String MY_QUERY = "CREATE TABLE " + NAME_OF_TABLE + " ( " +
            PERSON_KEY + " TEXT, " +
            GROUPPPS + " TEXT, " +
            IMPORTANCE + " TEXT);";

    public DBHelper(Context context) {
        // constructor of superclass
        super(context, "MyDBB", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("", "--- onCreate database ---");
        db.execSQL(MY_QUERY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

我在dataBase上写数据的方法:

 public void writeDataToDB(ArrayList<Person> arrayList) {

    contentValues = new ContentValues();
    dbHelper = new DBHelper(activity.getApplicationContext());
    dataBase = dbHelper.getWritableDatabase();


    for (int i = 0; i < arrayList.size(); i++) {

        contentValues.put(PERSON_KEY, arrayList.get(i).getKey());
        contentValues.put(GROUPPPS, arrayList.get(i).getGroup());
        contentValues.put(IMPORTANCE, String.valueOf(arrayList.get(i).isImportant()));

        Log.e("writeDataToDB", "Start inserting " + contentValues.toString());
        long rowID = dataBase.insert(NAME_OF_TABLE, null, contentValues);
        Log.e("writeDataToDB - ", "Value inserted, rowID = " + rowID);
        contentValues.clear();
    }

}

在我的方法中,我有例外: long rowID = dataBase.insert(NAME_OF_TABLE,null,contentValues);
并且rowID = -1表示 - 错误;

和我的LogCat:

Error inserting groupp=Withoutgroup importance=false perskey=0r2-2B43414D272B4D16
    android.database.sqlite.SQLiteException: table Persons has no column named groupp: , while compiling: INSERT INTO Persons(groupp,importance,perskey) VALUES (?,?,?)

2 个答案:

答案 0 :(得分:1)

“importance = false group = without group perskey = 0r114343434343434343434343434343434343434343434343”

你必须将没有组放在单引号中,如下所示:'Without group',否则SQLite会认为第二个单词是SQL查询的一部分。

答案 1 :(得分:1)

Group是一个关键字,因此如果您的表将此列为列名,则可能会出现问题。 见

group=Without group