首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“否则”不起作用

问“否则”不起作用
EN

Stack Overflow用户
提问于 2016-01-19 05:39:01
回答 3查看 120关注 0票数 0
代码语言:javascript
复制
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?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-01-19 05:44:52

你需要改变

if (mCursor != null)

到

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

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

票数 0
EN

Stack Overflow用户

发布于 2016-01-19 05:43:21

这是因为始终有一个非空值返回的--即使在没有接收到行的情况下(而且Exception不会抛出)

你最好把你的

代码语言:javascript
复制
if(mCursor.getCount() > 0) {
票数 2
EN

Stack Overflow用户

发布于 2016-01-19 05:42:56

rawQuery()将返回一个游标对象,或者它会抛出一个异常。它永远不会返回null。

而是试着用这个

代码语言:javascript
复制
if(mCursor.moveToFirst())
{

}
else
{

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34869214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档