Android Bundle与String的比较

时间:2012-07-17 13:16:45

标签: java android if-statement bundle

当我从bundle获取数据时,'if'控件永远不会工作,请帮助我..我需要在'if'块中比较bundle的数据,因为我必须根据数据更改textview。

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("...");
    }
}

4 个答案:

答案 0 :(得分:2)

使用等于而不是 == 来比较字符串:

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

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

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

答案 1 :(得分:2)

您可以使用

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

答案 2 :(得分:0)

您无法通过==比较字符串,因为这只会检查对象标识,而具有相同内容的两个字符串(例如A)可能是单独的对象。请改用equals()

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

请注意比较中的不同顺序。如果NullPointerExceptions应为空,则会阻止get

Here is a good explanation for this.

答案 3 :(得分:-1)

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("...");
    }
  }
}