My java if statement doesn’t seem to work

I don't know why, but when I use zxing to get barcodes in my Android application, the format is returned as EAN_ 13 but my if staement decides that it is not, and then displays ean in my toast notification_ 13. Any clues as to why it broke?

public void onActivityResult(int requestCode,int resultCode,Intent intent) {
    IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode,resultCode,intent);
    if (scanResult != null) {
        if (resultCode == 0){
            //If the user cancels the scan
            Toast.makeText(getApplicationContext(),"You cancelled the scan",3).show();
        }
        else{
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT").toString();
            if (format == "EAN_13"){
                //If the barcode scanned is of the correct type then pass the barcode into the search method to get the product details
                Toast.makeText(getApplicationContext(),"You scanned " + contents,3).show();
            }
            else{
                //If the barcode is not of the correct type then display a notification
                Toast.makeText(getApplicationContext(),contents+" "+format,3).show();
            }
        }
    }
}

Solution

In Java, you can't (well, shouldn't) use the = = operator to compare two strings You should use:

if (stringOne.equals(stringTwo)) { ... }

Or, in your case:

if ("EAN_13".equals(format)) { ... }

In Java, when using objects, the double equals operator compares two objects by reference equality If you have two strings:

String one = "Cat";
String two = "Cat";
boolean refEquals = (one == two); // false (usually.)
boolean objEquals = one.equals(two); // true

I say it is usually not true, because depending on how to create a string in the system, it can save memory by allowing two variables to point to the same block of memory However, the expectation that this approach will work is very bad

Note: when using the above strategy, you must ensure that the first string is not null, otherwise NullPointerException will be thrown If you can include external libraries in your project, I recommend using the Apache commons Lang library, which allows:

StringUtils.equals(stringOne,stringTwo);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>