简体   繁体   中英

Generating random number stops application

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM