Reputation: 589
I am trying to generate a random number on clicking the Button
and print the value in EditText
I made it with this code
public class Board_Play1 extends Activity {
int d;
Random random = new Random();
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.board_play1);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d=random.nextInt(6)+1;
EditText diceno = (EditText) findViewById(R.id.editText1);
diceno.setText(d);
}
});
}
But on running application after clicking the button it pops up an error saying Unfortunately, your app has stopped
. Cant understand why it is so. Can anyone explain what the mistake is?
Upvotes: 0
Views: 82
Reputation: 93872
You need to call the setText
method that accepts a CharSequence
as argument.
Currently you're calling setText(int resid)
which will try to find the correct resource with the id specified, so I guess your program is throwing a ResourceNotFoundException
.
So do:
diceno.setText(String.valueOf(d));
This will convert your int
to String
.
Also move the EditText diceno = (EditText) findViewById(R.id.editText1);
before the onClick
method. There is no need to retrieve it on each onClick
event, just once suffice.
Finally in future, don't forget to post the stacktrace with your question.
Upvotes: 2