0

I have an array with 5 elements, I want to display a random item from this list every time the user clicks the button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView textview = (TextView) findViewById(R.id.textView);
    final List<String> list = new ArrayList<>();

    list.add("item 1");
    list.add("item 2");
    list.add("item 3");
    list.add("item 4");
    list.add("item 5");

I tried this:

    final Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            Random random = new Random();
            int index = random.nextInt(list.size());
            textview.setText(getString(index));

        }
    });

But I got an error on click:

FATAL EXCEPTION: main
                                                             Process: activfy.activfy, PID: 18639
                                                             android.content.res.Resources$NotFoundException: String resource ID #0x72
                                                                 at android.content.res.Resources.getText(Resources.java:250)
                                                                 at android.content.res.Resources.getString(Resources.java:336)
                                                                 at android.content.Context.getString(Context.java:345)
                                                                 at activfy.activfy.MainActivity$1.onClick(MainActivity.java:159)

1 Answer 1

1

Error in line textview.setText(getString(index)); replace it with textview.setText(list.get(index));

Sign up to request clarification or add additional context in comments.

2 Comments

oh I forgot that index is an integer. Thank you.
Welcome, If it helps, you can accept it as an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.