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

Android database select query isn't working (Null Pointer error) [duplicate]

提问人:Alaa 提问时间:3/22/2019 最后编辑:Taslim OseniAlaa 更新时间:3/22/2019 访问量:48

问:

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
java android sqlite nullpointerexception

评论

0赞 ronginat 3/22/2019
我相信你的方法返回nullgetNoteByID
0赞 forpas 3/22/2019
当表中不存在 id 时,该方法将返回 。因此,在调用之前,请检查对象是否要避免 NPE。getNoteByID()nullgetTitle()Notenull

答:

0赞 Urvish Jani 3/22/2019 #1

也试试这个

游标 res = db.rawQuery(“select * from ”+TABLE_NAME+“ where ID = ” + id,null); 如果上述解决方案不起作用,那么也试试这个

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

评论

0赞 Alaa 3/23/2019
你是对的,getID 方法为 ListView public 中的每个项目返回 0 值 void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent=new Intent(getApplicationContext(),UpdateNote.class);备注 current_note=(Note)parent.getItemAtPosition(position);intent.putExtra(“id”,current_note.getId());startActivity(意向);