【问题标题】:"else" not working“其他”不起作用
【发布时间】:2016-04-24 11:29:59
【问题描述】:
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???

【问题讨论】:

  • 它总是正确的,因为应该返回一个条目......
  • 在没有记录时调试游标值并相应修改您的 if 语句
  • 尝试用if(mCursor == null) 代替esle
  • 嗨,您的查询总是返回一个值。不是吗?

标签: java android sqlite if-statement


【解决方案1】:

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

你最好重新编码你的 if to

if(mCursor.getCount() > 0) {

【讨论】:

    【解决方案2】:

    你需要改变

    if (mCursor != null)

    if (mCursor != null && mCursor.moveToFirst())

    这是因为光标可以为空,即您的查询已成功执行,但所选行数为 0。

    【讨论】:

      【解决方案3】:

      rawQuery() 要么返回一个 Cursor 对象,要么抛出一个 例外。它永远不会返回 null。

      试试这个

      if(mCursor.moveToFirst())
      {
      
      }
      else
      {
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-07
        • 1970-01-01
        • 2019-11-03
        相关资源
        最近更新 更多