Peter James
Peter James

Reputation: 352

Android do while loop

Hi This my second question here. I have the following table

|-----|-------|------|------|
|._id.|..INFO.|.DONE.|.LAST.|
|..1..|...A...|...N..|......|
|..2..|...B...|...Y..|..L...|<--- cursor.moveToPosition((int)_id-1);
|..3..|...C...|...Y..|......|
|..4..|...D...|...Y..|......|
|..5..|...E...|...N..|......|
|..6..|...F...|...N..|......|
|-----|-------|------|------|

I use the code:

cursor = db.query(TABLE_NAME, new String[]{INFO,DONE,LAST},null,null,null,null,null);
cursor.moveToPosition((int)_id-1);
String Yval = cursor.getString(cursor.getColumnIndex(DONE));
do
{
    cursor.moveToNext();
    Yval= cursor.getString(cursor.getColumnIndex(DONE));
}
while (Yval=="Y");
s = Yval;

I initially point the cursor to the LAST row I accessed, then I make a loop to go through the values in the DONE column, not stopping if there are Y's in the row of the column. When an N appears in the loop, the loop should stop. But it doesn't work. Yval never equals "Y". So the cursor does one 'moveToNext' and then exits the loop, because it doesn't read Yval as a "Y". (I also changed everything to integers. 1 for N, and 0 for Y, but it still didn't work) So what am I doing wrong here?

Upvotes: 6

Views: 38427

Answers (2)

Simon Dorociak
Simon Dorociak

Reputation: 33505

So you have to use equals() method if you want to compare Strings

while (Yval.equals("Y"));

You should know that:

  • == tests for reference equality.
  • equals tests for value equality.

So you want to test if Yval String has Y value so you have to use equals() method.

You approach doesn't work bacause:

String data = "lorem";
data == "lorem" ==> FALSE
data.equals("lorem") == TRUE


Also make sure that your Cursor has valid row so you need to add to condition also cursor.moveToNext() so

cursor.moveToNext() && (Yval.equals("Y")

also you need to treat cursor.moveToPosition((int)_id-1) so add it to condition.

Upvotes: 6

Sam
Sam

Reputation: 86948

I recommend changing a few things:

if(cursor.moveToPosition((int) _id - 1)) {
    int doneIndex = cursor.getColumnIndex(DONE);
    String Yval;
    do {
        Yval = cursor.getString(doneIndex);
    } while(Yval.equals("Y") && cursor.moveToNext());
}
  • You should check if a row exists at position _id - 1 since the SQLite _id is a unique id, not the position of a row in a Cursor.
  • You only need to fetch the index of the DONE column once, simply store it in a local variable.
  • As deceiver mentioned, String are tested with equals() and similar methods.
  • You need consider what happens if all of the rows are "DONE", then you must stop trying to read the Cursor before an out of bounds exception is thrown.

Upvotes: 3

Related Questions