user2905687
user2905687

Reputation: 13

App crashes when start

My android app crashes when I start here is the code I have tried it on an different device and it compiles fine

public class MyActivity extends Activity {
    int userAns;
    int ran1;
    int ran2;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ran1 =(int)(Math.random()*50+1);
        ran2 =(int)(Math.random()*50+1);
        TextView number1 = (TextView) findViewById(R.id.textView);
        number1.setText(ran1);
        TextView number2 = (TextView) findViewById(R.id.textView3);
        number2.setText(ran2);
        ans =ran1+ran2;

    }
   public void sendMessage(View view){
       String userAnsS = ((EditText)findViewById(R.id.editText)).getText().toString();
       userAns= Integer.parseInt(userAnsS);
       if (userAns == ran1 + ran2) {
           return;
       }

Upvotes: 1

Views: 141

Answers (4)

jyomin
jyomin

Reputation: 1967

The ans variable is not declared as int type i.e int ans=ran1+ran2

The setText method of the textview uses the string as a variable and therefore use the following number1.setText(string.valueOf(ran1)); number2.setText(string.valueOf(ran2));

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

Try this

number1.setText(""+ran1);
number2.setText(""+ran2); 

Or use

number1.setText(String.valueOf(ran1));
number2.setText(String.valueOf(ran2));

In your case

public final void setText (int resid)

// looks for a resource with the id mentioned
// if resource not found you get resource not found exception

What you want

public final void setText (CharSequence text)

 // Sets the string value of the TextView. 
 //ran1 and ran 2 is of type int so use String.valueOf(intvalue)

Upvotes: 3

Jitender Dev
Jitender Dev

Reputation: 6925

See android developers website for setText usage

You need

setText(CharSequence text)
Sets the string value of the TextView.

The setText method accepts CharacterSequence

And Strings are CharSequences, so you can just use Strings with setText Method.

So you can use both number1.setText(String.valueOf(ran1)); or number1.setText(""+ran1);

Upvotes: 0

Devrim
Devrim

Reputation: 15533

Use strings when setting texts to TextView number2.setText(String.valueOf(ran2));

Upvotes: 0

Related Questions