首页 > 解决方案 > 比较字符串和对象属性

问题描述

我正在尝试使用 .equals() 将字符串与对象属性进行比较,但即使条件为真,条件也会失败。我尝试使用 trim() 摆脱尾随空格,但仍然失败。

这是我的代码:

if (status) {
        inventoryList = allInventory.getInventory();
        assert assetId != null;
        for (Inventory inventory : inventoryList) {
            if (assetId.trim().equals(inventory.getProductCode().trim())) {

                //get the current quantity that exists

                new_quantity.setValue(0);

                new_quantity.setMaxValue(inventory.getQuantity());
                inventoryId = inventory.getId();
                return;

            } else {
                // new_quantity.setVisibility(View.GONE);
                decrement.setEnabled(false);
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setTitle("Product not found ");
                // prevent cancel of AlertDialog on click of back button and outside touch
                alert.setCancelable(false);
                alert.setMessage("Product is not in inventory. Do you want to continue scanning?");

                alert.setNegativeButton("No", (dialog, which) -> {
                            onBackPressed();
                            dialog.dismiss();
                        }
                );
                alert.setPositiveButton("Yes", (dialog, which) -> {
                    Intent scanAsset = new Intent(this, ScanActivity.class);
                    scanAsset.putExtra("building", building);
                    scanAsset.putExtra("room", room);
                    scanAsset.putExtra("department", depart);
                    scanAsset.putExtra("TAG", "E");
                    startActivity(scanAsset);
                    dialog.dismiss();
                });
                AlertDialog dialog = alert.create();
                dialog.show();
            }

        }

标签: javaandroidstringobjectcomparison

解决方案


我想指出 oracle 文档,其中说:

将此字符串与指定对象进行比较。当且仅当参数不为 null 并且是表示与此对象相同的字符序列的 String 对象时,结果才为真。

在此处输入图像描述


推荐阅读