Using AsyncTask to Run on a Background Thread

The next step is to call and test the networking code you just added. However, you cannot simply call FlickrFetchr.getUrlString(String) directly in PhotoGalleryFragment. Instead, you need to create a background thread and run your code there.

The easiest way to work with a background thread is with a utility class called AsyncTask, which creates a background thread for you and runs the code in the doInBackground(…) method on that thread.

In PhotoGalleryFragment.java, add a new inner class called FetchItemsTask at the bottom of PhotoGalleryFragment. Override AsyncTask.doInBackground(…) to get data from a website and log it.

Listing 25.5  Writing an AsyncTask, part I (PhotoGalleryFragment.java)

public class PhotoGalleryFragment extends Fragment {

    private static final String TAG = "PhotoGalleryFragment";

    private RecyclerView mPhotoRecyclerView;
    ...
    private class FetchItemsTask extends AsyncTask<Void,Void,Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                String result = new FlickrFetchr()
                        .getUrlString("https://www.bignerdranch.com");
                Log.i(TAG, "Fetched contents of URL: " + result);
            } catch (IOException ioe) {
                Log.e(TAG, "Failed to fetch URL: ", ioe);
            }
            return null;
        }
    }
}

Now, in PhotoGalleryFragment.onCreate(…), call execute() on a new instance of FetchItemsTask.

Listing 25.6  Writing an AsyncTask, part II (PhotoGalleryFragment.java)

public class PhotoGalleryFragment extends Fragment {

    private static final String TAG = "PhotoGalleryFragment";

    private RecyclerView mPhotoRecyclerView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        new FetchItemsTask().execute();
    }
    ...
}

The call to execute() will start your AsyncTask, which will then fire up its background thread and call doInBackground(…). Run your code and you should see the amazing Big Nerd Ranch home page HTML pop up in Logcat, as shown in Figure 25.5.

Figure 25.5  Big Nerd Ranch HTML in Logcat

Screenshot shows LogCat for Android App.  The Big Nerd Ranch HTML in Logcat is shown.

Finding your log statements within the Logcat window can be tricky. It helps to search for something specific. In this case, enter PhotoGalleryFragment into the Logcat search box, as shown.

Now that you have created a background thread and run some networking code on it, let’s take a closer look at threads in Android.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.119.148