From AsyncTask Back to the Main Thread
Now that you have the appropriate nuts and bolts in place for RecyclerView, add code to set up and
attach an adapter when appropriate.
Listing 25.16 Implementing setupAdapter() (PhotoGalleryFragment.java)
public class PhotoGalleryFragment extends Fragment {
private static final String TAG = "PhotoGalleryFragment";
private RecyclerView mPhotoRecyclerView;
private List
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
mPhotoRecyclerView = (RecyclerView) v.findViewById(R.id.photo_recycler_view);
mPhotoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
setupAdapter();
return v;
}
private void setupAdapter() {
if (isAdded()) {
mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
}
}
...
}
The setupAdapter() method you just added looks at the current model state, namely the List
of GalleryItems, and configures the adapter appropriately on your RecyclerView. You call
setupAdapter() in onCreateView(...) so that every time a new RecyclerView is created, it is
reconfigured with an appropriate adapter. You also want to call it every time your set of model objects
changes.
Notice that you check to see whether isAdded() is true before setting the adapter. This confirms that
the fragment has been attached to an activity, and in turn that getActivity() will not be null.
Remember that fragments can exist unattached to any activity. Before now, this possibility has not
come up because your method calls have been driven by callbacks from the framework. In this
scenario, if a fragment is receiving callbacks, then it definitely is attached to an activity. No activity, no
callbacks.
However, now that you are using an AsyncTask you are triggering some callbacks from a background
thread. Thus you cannot assume that the fragment is attached to an activity. You must check to make
sure that your fragment is still attached. If it is not, then operations that rely on that activity (like
creating your PhotoAdapter, which in turn creates a TextView using the hosting activity as the context)
will fail. This is why, in your code above, you check that isAdded() is true before setting the adapter.