1

So I the code that follows to set text view text to a string however when I run the app nothing shows in the text view, can anyone explain why?

code:

public void onItemSelected(AdapterView<?> parent, View view,
    int position, long id) {
    Object poem = parent.getItemAtPosition(position);
    if(poem.toString() == "Tam O Shanter"){
         selectedPoem.setText(getString(R.string.tamO));
    }
}
Jay Mayu
  • 17,023
  • 32
  • 114
  • 148
Thomas
  • 293
  • 1
  • 3
  • 15
  • 7
    `poem.toString() == "Tam O Shanter"` needs to be `"Tam O Shanter".equals(poem.toString())` (better yet use `equalsIgnoreCase()`) See if that helps, it's one problem anyways. – A--C Mar 15 '13 at 21:26

2 Answers2

4
if (poem.toString() == "Tam O Shanter"){
   selectedPoem.setText(getString(R.string.tamO));
}

This will always return false because you are comparing references not values. You have to use equals() method.

There is one golden rule: Every time you want to compare Strings, equals() will become your friend.

You need to do it like this:

if (poem.toString().equals("Tam O Shanter")) { // or equalsIgnoreCase()
   selectedPoem.setText(getString(R.string.tamO));
}
Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
2

I also rewrite also you code

String poem = (String)parent.getItemAtPosition(position);

You are suppose to equals instead of == to compare 2 string

  public void onItemSelected(AdapterView<?> parent, View view,
    int position, long id) {
    String poem = (String)parent.getItemAtPosition(position);
    if(poem.toString().equalsIgnoreCase("Tam O Shanter")){
         selectedPoem.setText(getString(R.string.tamO));
    }
  }
Festus Tamakloe
  • 11,231
  • 9
  • 53
  • 65