Android数据库选择查询不起作用(空指针错误)

时间:2019-03-22 11:38:04

标签: java android sqlite nullpointerexception

public static final String dbName="notesDb";
public static final Integer DB_version=1;

public static final String key_id="id";
public static final String key_title="title";
public static final String key_subject="subject";

public static final String Table_notes="notes";

public DbNotes(Context context) {
    super(context, dbName, null, DB_version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String create_table="create table "+Table_notes+"("+key_id+" Integer primary key,"+key_title+"  varchar(30), "+key_subject+" varchar(50)) ";
    db.execSQL(create_table);
}

public Note getNoteByID(int id){
    SQLiteDatabase db=this.getReadableDatabase();
    String selectQuery="SELECT * FROM "+Table_notes+" WHERE id="+id;
    Cursor cursor=db.rawQuery(selectQuery,null);

    Note note=null;
    if (cursor.moveToFirst()){
        String title=cursor.getString(cursor.getColumnIndex(key_title));
        String subject=cursor.getString(cursor.getColumnIndex(key_subject));
        int id_item=cursor.getInt(cursor.getColumnIndex(key_id));
        note=new Note(title,subject,id_item);
    }
    return note;
}

logcat消息:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.ebda3.notes.Note.getTitle()' on a null object reference

1 个答案:

答案 0 :(得分:0)

也尝试

Cursor res = db.rawQuery(“ select * from” + TABLE_NAME +“其中ID =” + id,null); 如果上述解决方案不起作用,也可以尝试

一次卸载您的应用并重新安装,希望对您有帮助