javaandroidandroid-cursorgetstring

cursor.getString can't equal with string variable


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.


Solution

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