Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Networking Basics


Finally, create the PhotoGalleryFragment class. Retain the fragment, inflate the layout you just
created, and initialize a member variable referencing the RecyclerView.


Listing 25.2  Some skeleton code (PhotoGalleryFragment.java)


public class PhotoGalleryFragment extends Fragment {


private RecyclerView mPhotoRecyclerView;


public static PhotoGalleryFragment newInstance() {
return new PhotoGalleryFragment();
}


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


@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));


return v;
}
}


(Wondering why you are retaining the fragment? Hold that thought – we will explain later in the
chapter, in the section called Cleaning Up AsyncTasks.)


Fire up PhotoGallery to make sure everything is wired up correctly before moving on. If all is well,
you will be the proud owner of a blank screen.


Networking Basics


You are going to have one class handle the networking in PhotoGallery. Create a new Java class and,
since you will be connecting to Flickr, name this class FlickrFetchr.


FlickrFetchr will start off small with only two methods: getUrlBytes(String) and
getUrlString(String). The getUrlBytes(String) method fetches raw data from a URL and
returns it as an array of bytes. The getUrlString(String) method converts the result from
getUrlBytes(String) to a String.

Free download pdf