0
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???

Jaiprakash Soni
  • 4,100
  • 5
  • 36
  • 67

3 Answers3

2

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) {
Jan
  • 13,738
  • 3
  • 30
  • 55
0

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
{

}
Ravi
  • 34,851
  • 21
  • 122
  • 183
0

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.

Jaiprakash Soni
  • 4,100
  • 5
  • 36
  • 67