P. Zang P. Zang -4 years ago 162
Java Question

Retrieving string for if/else clause in android studio

I'm trying to get a qr code scanner going where it should redirect to different activities in dependancy on the code scanned but I'm having trouble getting the string from the result in the correct form.

@Override
public void handleResult(Result result) {
Log.w("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan results");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();

String id_helper = result.getText().toString();

if (id_helper == "1") {
startActivity(new Intent(this, Sample1.class));
} else if (id_helper == "2") {
startActivity(new Intent(this, Sample2.class));
} else {
startActivity(new Intent(this, Sample3.class));
}

Answer Source

You are comparing the string in wrong way, In Java you have to compare string using the equals method.

if ("1".equals(id_helper)) {
    // Open activity
}

Always put the known variable as on the left side of the condition to avoid NullPoinerExceptions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download