1

I need help with using an if statement in java, here is my code :

if(ans==1)
{

txtans.setText("This is a Prime Number");

}
else
{
txtans.setText("This is NOT a Prime Number");
}

if I remove the setText methods in both statements my program works, but when I leave them there and the program finds ans, then it quits, I'm wondering whats wrong with the statements? or is it not possible to use the setText method within if statements..if so how do I overcome this? What I want to do is print a string to the TextView layout when the ans = 1, any suggestions?

David
  • 39
  • 1
  • 5

4 Answers4

1

Yes, you can run txtans.setText() in an if statement just as well as you could run it if it wasn't in an if statement. You likely just don't have txtans initialised properly.

A quick google search brought up this as a way to print text to a textview.

Community
  • 1
  • 1
Leif Andersen
  • 21,580
  • 20
  • 67
  • 100
  • 1
    yeah I forgot to initialise txtans, I included `txta = (TextView)findViewById(R.id.txta);` and now it works :D – David Oct 31 '11 at 07:45
1

Check your code, this erros usually comes when use findViewById() method in a wrong view.

In the activity you use like this findViewById(), maybe you need to call yourView.findViewById();

(If you post your class we can help you with more detailed answear.)

kameny
  • 2,372
  • 4
  • 30
  • 40
0

txtans might be NULL and you are trying to access a member of a NULL object.

durron597
  • 31,968
  • 17
  • 99
  • 158
shobhit
  • 89
  • 2
  • 8
0

Also note that it is not allowed to call methods from Views from another Thread which created them. But a LogCat output including the Error will enlight us for shure :)

Rafael T
  • 15,401
  • 15
  • 83
  • 144