So far, i was using Volley but after going through the Robospice library, and it's advantages over other network libraries, i started using it in my current project.
It working fine, but since it's lifecycle is tied to the activity not fragments, i implemented the same in fragment like this.
public class MainActivityFragment extends Fragment {
private SpiceManager spiceManager = new SpiceManager(JacksonSpringAndroidSpiceService.class);
private static final String KEY_LAST_REQUEST_CACHE_KEY = "lastRequestCacheKey";
private String lastRequestCacheKey;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
performRequest(mSort);
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (!TextUtils.isEmpty(lastRequestCacheKey)) {
outState.putString(KEY_LAST_REQUEST_CACHE_KEY, lastRequestCacheKey);
}
super.onSaveInstanceState(outState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_LAST_REQUEST_CACHE_KEY)) {
lastRequestCacheKey = savedInstanceState.getString(KEY_LAST_REQUEST_CACHE_KEY);
spiceManager.addListenerIfPending(MovieDataResult.class, lastRequestCacheKey,
new ListMovieRequestDataListener(movieImageAdapter, getActivity(),progressDialog));
spiceManager.getFromCache(MovieDataResult.class, lastRequestCacheKey, DurationInMillis.ONE_MINUTE,
new ListMovieRequestDataListener(movieImageAdapter, getActivity(),progressDialog));
}
super.onActivityCreated(savedInstanceState);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
spiceManager.start(getActivity());
}
@Override
public void onStop() {
super.onStop();
if (spiceManager.isStarted()) {
spiceManager.shouldStop();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mSort = Utility.getPreferredSorting(getActivity());
setUpProgressDialog();
}
private void performRequest(String mSort) {
MovieDataRequest movieDataRequest = new MovieDataRequest(apiKey,mSort);
lastRequestCacheKey = movieDataRequest.createCacheKey();
spiceManager.execute(movieDataRequest, lastRequestCacheKey,
DurationInMillis.ONE_MINUTE, new ListMovieRequestDataListener(movieImageAdapter, getActivity(),progressDialog));
}
}
This works fine, i was wondering, if it follows the lifecycle. As, i am starting spicemanager onAttach() and stopping onStop() and onRestoreInstance() getting the cached data.
Basically, this is how it works here-->
- spicemanager starts when fragment is attached
- then .execute() is called for network request
- spicemanager is destroyed onStop()
Also, is it a good approach to have a spicemanager for each activity?