-3

I intend to compare cursor.getString(1) == pName, but the code always does the comparison improperly. I was doing anything that came into my mind, but could not make it work. The code is like this :

public Cursor addProduct(int id, String pName, int pPrice) {
    int getNewId = 0;
    Cursor cursor = viewProduct();
    if(cursor.getCount() == 0) {
        insertIntoProduct(id, pName, pPrice);
    } else {
        boolean i = false;
        cursor.moveToFirst();
        while(cursor.moveToNext()) {
            if(cursor.getString(1) == pName) {
                i = true;
                getNewId = cursor.getInt(0);
            }
        }
        if(i == true) {
            updateIntoProduct(getNewId, pName, pPrice);
        }
        else {
            insertIntoProduct(id, pName, pPrice);
        }
    }
    return cursor;
}

This code works properly except this problem. The cursor will get field of 2 column index, but cursor.getString(1) isn't comparing properly with == pName.

General Grievance
  • 4,555
  • 31
  • 31
  • 45

2 Answers2

1

You shouldn't use == to compare Strings, can you try the following instead:

if(cursor.getString(1).equals(pName)) {
    i = true;
    getNewId = cursor.getInt(0);
}
tobo1987
  • 26
  • 4
0

In Java, Strings are objects. They might be similar, but when you compare them via the == operator, then you are checking whether the two are the exact very same object. Instead of this, you need to compare whether the objects are similar, as in

if(cursor.getString(1).equals(pName)) {
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175