java - "else"不工作

标签 java android sqlite if-statement

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),它会随机并显示对话框。但是如果数据库没有信息...“else”不起作用.

不知道什么时候数据库没有信息,“mCursor”等于null???

最佳答案

这是因为总是返回一个非空值 - 甚至在您没有收到任何行的情况下(并且 SQL 不会抛出异常)

你最好重新编码你的 if

if(mCursor.getCount() > 0) {

关于java - "else"不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34869214/

相关文章:

java - 无法在 Google App Engine 上发送电子邮件

java - 将 ArrayList 或数组转换为字符串数组

java - 当我按 x 时无法跳出循环

Android:蓝牙连接、套接字和线程

java - 刷新 RecyclerView 中的数据并保持其滚动位置将用户带到 Activity 的顶部

java - 错误:SSL peer shut down incorrectly

android - android studio 调试问题

.net - 如何连接到内存中的共享缓存数据库?

c++ - 如何调试 SQLite3 中的绑定(bind)参数?

php - 如何在 PDO 中加载 sqlite 扩展?