cursor.getstring不能与字符串变量相等

3lxsmp7m  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(250)

我打算比较cursor.getstring(1)==pname,但代码总是不正确地进行比较。我在做任何我想做的事情,但都无法让它起作用。代码如下所示:

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

除此问题外,此代码工作正常。游标将获取2列索引的字段,但cursor.getstring(1)与==pname的比较不正确。请帮帮我,伙计们。

ia2d9nvy

ia2d9nvy1#

您不应该使用==来比较字符串,是否可以尝试以下方法:

if(cursor.getString(1).equals(pName)) {
    i = true;
    getNewId = cursor.getInt(0);
}
wfsdck30

wfsdck302#

在java中,字符串是对象。它们可能是相似的,但是当你通过 == 运算符,然后检查这两个对象是否完全相同。相反,您需要比较对象是否相似,如中所示

if(cursor.getString(1).equals(pName)) {

相关问题