Jessada Chooduang
Jessada Chooduang

Reputation: 25

"else" not working

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();
    }
}

when I click a button. if database has a information (!mCursor.equals(null)or(mCursor != null), it random and show dialog. But if database don't has information ... "else" not working.

I don't know when database don't has information, "mCursor" equal null???

Upvotes: 0

Views: 124

Answers (3)

Jaiprakash Soni
Jaiprakash Soni

Reputation: 4112

You need to change

if (mCursor != null)

to

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

This is because cursor can be empty i.e. your query was executed successfully but number of selected rows is 0.

Upvotes: 0

Jan
Jan

Reputation: 13858

That's because there's always a non null value returned - even in the case where you receive no rows (and the SQL doesn't throw an Exception)

You' be better of to recode your if to

if(mCursor.getCount() > 0) {

Upvotes: 2

Ravi
Ravi

Reputation: 35549

rawQuery() will either return a Cursor object or it will throw an exception. It will never return null.

instead try with this

if(mCursor.moveToFirst())
{

}
else
{

}

Upvotes: 0

Related Questions