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 ???
答案 0 :(得分:2)
那是因为在没有收到任何行的情况下,总是返回非空值 - 甚至(并且SQL不会抛出Exception
)
你最好将你的if重新编码为
if(mCursor.getCount() > 0) {
答案 1 :(得分:0)
rawQuery()将返回一个Cursor对象,否则它将抛出一个 例外。它永远不会返回null。
请尝试使用此
if(mCursor.moveToFirst())
{
}
else
{
}
答案 2 :(得分:0)
您需要更改
if (mCursor != null)
到
if (mCursor != null && mCursor.moveToFirst())
这是因为游标可以为空,即您的查询已成功执行,但所选行的数量为0。