At the moment i´m using mRequestQueue.cancelAll(getActivity()) at on stop method in a fragment but apparently when i move the phone from landscape to portrait it is still re
You should set the tag to an object, not a method.
By setting the tag to getActivity()
, you are asking Volley to use a dynamic method call on the main thread as a reference to the request which is happening on a background thread.
So when the background thread is trying to cancel the requests, the activity could already be dead.
Rather than using getActivity()
, use this
or some other object or string.
This is good practice for any Tag, and you should also beware of leaking your activity.
Solutions:
You could use the current object:
request.setTag(this);
or, the static class object
request.setTag(MyFragment.class);
or, as a constant in a separate class:
request.setTag(CustomTags.LIST_REQUESTS);
CustomTags.LIST_REQUESTS being the best in my opinion (less chance of leaking activity)
Something like this:
public class CustomTags
{
public static final String LIST_REQUESTS="CustomTags:LIST_REQUESTS";
}
Update
I just noticed I was making a mistake in tagging my requests in Volley (though the solutions I posted above are fine).
I still thought I would update here an important thing to keep in mind. Volley tags by identity not value.
Thus, it is important to keep in mind that a tag that is merely the same string value, and not the same object itself, will not be recognized as the same tag
.
It's similar to the difference between
String a1 = "A";
String a2 = "A";
a1 == a2; //evaluates to false
String a1 = "A";
String a2 = "A";
a1.equals(a2); // evaluates to true
Check this article. It uses Oto as the singleton Event bus. This way you can notify the volley queue when your Activity or Fragments get recreated. You can of course use a plain old Interface instead and listen on the changes. BUt Otto looks much less verbose and elegant as a unified solution.
http://andraskindler.com/blog/2013/eventbus-in-android-an-otto-example/
I've struggled with the memory leak for the longest time until I found I called stop() from the class 'RequestQueue'.
//Initialize the object
RequestQueue requestQueue =
Volley.newRequestQueue(getActivity().getApplicationContext());
//Release the object
requestQueue.stop();
requestQueue = null;
The class says it "Stops the cache and network dispatchers." Whatever that means...