简体   繁体   中英

Android Bundle Comparison with String

The 'if' controls never work when I get datas from bundle, please help me.. I need comparison for bundle's data in 'if' block because I have to change textview according to data.

result = getIntent().getExtras();
String get = result.getString("secilen");

if(number == 0) {
    imgView.setImageResource( R.drawable.tas );

    //txtV.setText(get);

    if (get == "A"){ // if even "A" come never read if block
        txtV.setText("...");
    }

    if (get == "B"){
        txtV.setText("...");
    }

    if (get == "C") {
        txtV.setText("...");
    }
}

use equals instead of == for compare strings as:

if (get.equals("A")){ 
    txtV.setText("...");
}

if (get.equals("B")){
    txtV.setText("...");
}

if (get.equals("C")) {
    txtV.setText("...");
}

您可以使用

if (get.equals("A")) { //my code ...

You cannot compare strings via == , because that will only check for object identity, while two strings with the same content (eg A ) might be separate objects. Use equals() instead:

if ("A".equals(get)) {
        txtV.setText("...");
}

Note the different order in the comparison. That prevents NullPointerExceptions if get should be null.

Here is a good explanation for this.

result = getIntent().getExtras();
if(result!=null){
    String get = result.getString("secilen");
    if(number == 0){
    imgView.setImageResource( R.drawable.tas );


    if (get.equals("A"))
        txtV.setText("...");
    }

    else if (get.equals("B")){
        txtV.setText("...");
    }

    else if (get.equals("C")) {
        txtV.setText("...");
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM