public void randomFood (View view){
Cursor mCursor = database.rawQuery("SELECT name FROM member ORDER BY RANDOM() LIMIT 1", null);
if (mCursor != null) {
mCursor.moveToFirst();
String name = mCursor.getString(mCursor.getColumnIndex("name"));
Log.i("===============", name);
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("This is your dog name");
dialog.setCancelable(true);
dialog.setMessage(name);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
else{
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Wait!!");
dialog.setCancelable(true);
dialog.setMessage("Please add information");
dialog.setPositiveButton("Go", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Random.this, MainActivity.class);
startActivity(intent);
}
});
dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
}当我点击一个按钮。如果数据库有一个信息(!mCursor.equals(null)or(mCursor != null),它就随机显示对话框。但如果数据库没有信息..。“否则”不起作用。
我不知道数据库何时没有信息,"mCursor“等于null?
发布于 2016-01-19 05:44:52
你需要改变
if (mCursor != null)
到
if (mCursor != null && mCursor.moveToFirst())
这是因为游标可以是空的,即您的查询已成功执行,但所选行数为0。
发布于 2016-01-19 05:43:21
这是因为始终有一个非空值返回的--即使在没有接收到行的情况下(而且Exception不会抛出)
你最好把你的
if(mCursor.getCount() > 0) {发布于 2016-01-19 05:42:56
rawQuery()将返回一个游标对象,或者它会抛出一个异常。它永远不会返回null。
而是试着用这个
if(mCursor.moveToFirst())
{
}
else
{
}https://stackoverflow.com/questions/34869214
复制相似问题