菜鸟求助---android开发---查询数据库的时候出现了空指针错误

liang705203544 2012-09-10 03:28:05
查询数据库,获得数据,放入一个User的Bean中,我确定Bean里面有值,因为用StringvalueOf()函数取里面的值的时候可以得到要的数,但是直接用里面的值的时候就报空指针错误。
//查询数据库
user=new User();
DBHelper dbhelper=new DBHelper(this);
SQLiteDatabase db=dbhelper.getReadableDatabase();
Cursor cursor=db.query("persons",
new String[]{"birthday","name","luck_number","sex","id"},
null, null, null, null, null);
cursor.moveToFirst();

user.setBirthday(cursor.getInt(cursor.getColumnIndex("birthday")));
user.setName(cursor.getString(cursor.getColumnIndex("name")));
user.setLuck_number(cursor.getInt(cursor.getColumnIndex("luck_number")));
user.setSex(cursor.getInt(cursor.getColumnIndex("sex")));
user.setId(cursor.getInt(cursor.getColumnIndex("id")));
cursor.close();

EditText luck_color=( EditText)findViewById(R.id.luck_color);

luck_color.setText(String.valueOf(user.getBirthday()));

// 这样使用就会有空指针错误 luck_color.setText(user.getBirthday());
//还有, 这个 语句也有空指针错误 :int luck_number=user.getLuck_number();
...全文
285 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
独领风骚的猫 2012-09-10
  • 打赏
  • 举报
回复
luck_color.setText(user.getBirthday());

luck_color.setText(String.valueOf(user.getBirthday()));
这两句按说没什么区别,就是一个字符串的转换!!user.getBirthday() 返回神马类型??
CodeCxz 2012-09-10
  • 打赏
  • 举报
回复
如果数据库不存在,当然查不出来东西了
lgxing 2012-09-10
  • 打赏
  • 举报
回复
看情况是user.getBirthday()返回空了
查这个方法就行了
  • 打赏
  • 举报
回复
cursor.moveToFirst();这句之前最好加上cursor是否为空的判断,实践证明和文档中的说明不一致……
jeffreysha 2012-09-10
  • 打赏
  • 举报
回复



cursor.moveToFirst();


最好多点判断语句,这样出现查找不到的情况也可以避免。

while(cursor!=null){
cursor.moveToFirst();
//这句可以看到底查找到没有,count可以看到共查找到几条数据。
if(cursor.getCount!=0){
}
else{

}
}



还有 如果查找的是中文字符,读取中文字符的时候可能因为编码问题导致读取不到。。

贴一段以前读中文字符的代码

int number22=cur4.getColumnIndex(KEY_AREA);
byte bytes[]=cur4.getBlob(number22);


try {
//将其转化为gb2312编码方式
str6= new String (bytes,"gb2312").trim();
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
qinjuning 2012-09-10
  • 打赏
  • 举报
回复
有异常就看看Log提示的什么异常类型,多少行 。根据你的描述,很难去判断。
coderandroid 2012-09-10
  • 打赏
  • 举报
回复
数据库,本身就是空的?

80,349

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧