Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App with Java Basic Android Programming Choosing a Random Fact

Sai Krishna Katkam
PLUS
Sai Krishna Katkam
Courses Plus Student 1,946 Points

I've used "for"loop instead of "Random"class to iterate over the String array, I only see last element of array on click

//

   View.OnClickListener listener = new View.OnClickListener() {

        String[] fact = {"Leonardo da Vinci could write with one hand and draw with the other at the same time.",
                "A traffic jam lasted lasted for more than 10 days, with cars only moving 0.6 miles a day.",
                "There are over 200 corpses on Mount Everest and they are used as way points for climbers.",
                "Russia didn't consider beer to be alcohol until 2011. It was previously classified as a soft drink.",
                "Two-thirds of the people on Earth have never seen snow.", "A hummingbird weighs less than a penny.",
                "The average person walks the equivalent of three times around the world in a lifetime.",
                "It would take over 1,000 years to watch every video on YouTube.",
                "A cockroach can live several weeks with its head cut off."};

        @Override
        public void onClick(View v) {
            for (int i = 0; i < fact.length; i++) {
                funFact.setText(fact[i]);
            }
        }
    };
    showFunFactBtn.setOnClickListener(listener);
}

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Yes, this is the behavior we would expect. Every time you click the button the for loop runs from start to finish, each time changing the fact until the last fact is the one displayed. It might be setting the text each iteration, but it's only going to display the very last one. These operations happen very quickly.

Let's put it this way. In the example he uses the Random class to choose one index from the facts array and display one fact. Your code chooses all indexes and all facts and sets it very quickly in succession. You need a way to select one fact per click instead of selecting all facts per click.

Hope this makes sense! :sparkles:

Try incrementing I by 1only when the button is pressed then getting the string at facts[I]. That should achieve the result you're expecting.