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 Blog Reader Android App Getting Data from the Web Getting JSON Data from an HTTP Request

Alyne Francis
Alyne Francis
7,686 Points

1. Getting JSON data back on button click?

I’m trying to modify this exercise to have similar functionality as the Fun Facts app.

    //Execute get data
    if(isNetworkAvailable()) {
        mProgressBar.setVisibility(View.VISIBLE);
        final GetJSONDataTask getJSONDataTask = new GetJSONDataTask();

        //Add on click listener!
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getJSONDataTask.execute();
            }
        };
        refreshButton.setOnClickListener(listener);
    }
    else {
        Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
    }

Each time a button is clicked, I want make another request for data and display the new content. The API returns a random piece of text and a random image each time. Right now I’m able to display the first piece of text + image that is returned, but I can’t get that to execute multiple times.

I did a little digging and I guess I can’t run an async task more than once. What’s the most elegant solution here? Do I stop the task on my button click and restart it? Or is there a better another solution?

1 Answer

Ratik Sharma
Ratik Sharma
32,885 Points

The way I would do it is call the AsyncTask once and save the data returned into String arrays or maybe an object I define. Later on, I'd randomise locally (using the Random class) and use the data I saved earlier. It's best practice to call the AsyncTask to get that data while the user sees a splash screen when launching the app as recurring calls to the task can cause performance issues. So, don't call the task each time the button is pressed. This is the approach I would use.

As for your issue where only one image/text pair is shown, I have to see some code to help with that. Cheers! :)