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

Posted

技术标签:

【中文标题】Android数据库选择查询不起作用(空指针错误)[重复]【英文标题】:Android database select query isn't working (Null Pointer error) [duplicate] 【发布时间】:2019-08-13 09:23:57 【问题描述】:
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

【问题讨论】:

我相信你的getNoteByID方法返回null 当id在表中不存在时,方法getNoteByID()返回null。所以在调用getTitle() 之前检查Note 对象是否为null 以避免NPE。 【参考方案1】:

也试试这个

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

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

【讨论】:

你是对的,getID 方法为 ListView 中的每个项目返回 0 值 public 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());开始活动(意图);

以上是关于Android数据库选择查询不起作用(空指针错误)[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Android 仅加载缓存不起作用。离线显示 WebView

为什么@Autowired不起作用,返回空指针值

Spring 注入 MessageDrivenBean 不起作用 - 空指针 - jboss eap 7

从向量到空指针的memcpy(反之亦然)不起作用

findElement 在 Android 上的 Appium 中不起作用

odbc_execute 参数不起作用(空警告)