Jack M.
Jack M.

Reputation: 51

Using volley on android, where to declare the queue using fragments?

I'm working on my first android app so I'm still getting familiar with the correct usage of the context, views and using fragments.

Currently my application has one activity and several fragments and I want to use volley to retrieve and send data from/to a php web service I set up on xampp. My doubt is, how should I set up the code for best practices?

I did as recommended here https://developer.android.com/training/volley and created a singleton in a separate class, I'll need to do a few request on each fragment so I'll have to use the method to get the queue in each fragment and add every new request, but I don't know where to create the queue (main activity? any fragment?) in order to not have context or other issues.

I've looked around but didn't find anything specific and their problems were solved in a line of code without getting into the implementation, asides of a person recommending to create a parentVolleyFragment extends Fragment, declaring the queue there and then make my fragments extend parentVolleyFragment to get the queue, like this:

public class parentVolleyFragment extends Fragment{
    private VolleySingleton volley;
    protected RequestQueue fRequestQueue;
}

Would that be a good practice or is there a better way?

Upvotes: 2

Views: 272

Answers (1)

Having followed the instructions here https://developer.android.com/training/volley, you may then access the Request Queue in any of your fragments this way

VolleySingleton.getInstance(getActivity().getApplicationContext()).getRequestQueue()

It's already a singleton. Volley also uses an inbuilt cache to address some activity/fragment life cycle issues just in case that's your worry.

Upvotes: -1

Related Questions