-1

I am creating a randomly generated string in android studio and im having trouble converting it to the textview with the click of a button. I need to call this string from my OnClick function for the button, and I need to know the correct parameters to use in order to do so.

Here is the string code:

String randomString( int len ){
    StringBuilder sb = new StringBuilder( len );
    for( int i = 0; i < len; i++ )
        sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
    txt.setText(sb); //attempt to push to text, but need to somehow call this in a function from a button
    return sb.toString();
}

Thanks to anyone who can help! Just trying to call that String that is made (randomstring) from a function by the press of my button.

Ian McCleary
  • 809
  • 1
  • 7
  • 14
  • Check out these StackOverflow answer - [Android Button Click](http://stackoverflow.com/questions/10231309/android-button-onclick) or [Android: how to handle button click](http://stackoverflow.com/questions/14782901/android-how-to-handle-button-click) – Tigger Mar 09 '16 at 03:42
  • What is AB here? And what it contains?? Its a string variable I know but what you trying to do is not specified sorry – Vikrant Kashyap Mar 09 '16 at 03:44
  • Are you searching for how to call a method which returns strings ? – Shree Krishna Mar 09 '16 at 03:51

3 Answers3

2

First, properly initialize the TextView like so:

TextView tvSample = (TextView) findViewById(<ID of View here>);

Then onClick of a button just call your method and pass the value accordingly:

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvSample.setText(randomString(10));
            }
        });

Just remove the txt.setText(sb); line in your randomString(). Hope this helps.

AL.
  • 35,361
  • 10
  • 135
  • 270
  • Thank you so much! I realized that I did not pass an integer through random string which was giving me the errors. Thanks! – Ian McCleary Mar 10 '16 at 05:11
1
    String randomString (int len){
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++)
            sb.append(AB.charAt(rnd.nextInt(AB.length())));

        return sb.toString();
    }

    btn.setOnClickListner(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txt.setText(randomString(len));
        }
    }
ErShani
  • 392
  • 1
  • 9
1

You have to set on click listener on button like

   txtBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tvSample.setText(randomString(10));
            txt.setText(sb.toString()); 
        }
    });
Ajay Pandya
  • 2,397
  • 4
  • 30
  • 64