how to create a separate class in which define all about volley and in another activity we directly pass URL,CONTEXT and Get Response...
Create Listeners(since they are interface they can't be instantiated but they can be instantied as an anonymous class that implement interface) inside the activity or fragment. And Pass this instances as parameters to the Request.(StringRequest, JsonObjectRequest, or ImageRequest).
public class MainActivity extends Activity {
private static final String URI = "";
// This is like BroadcastReceiver instantiation
private Listener listenerResponse = new Listener() {
@Override
public void onResponse(JSONObject arg0) {
// Do what you want with response
}
};
private ErrorListener listenerError = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
// Do what you want with error
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Next, create a class that has request and pass this listeners to this class' request method , that's all. I don't explain this part this is same as creating a request object in any tutorials.But you can customize this class as you wish. You can create singleton RequestQueue
to check priority, or set body http body parameters to this methods as paremeters.
public class NetworkHandler {
public static void requestJSON(Context context, String url, Listener listenerResponse, ErrorListener listenerError) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError);
Volley.newRequestQueue(context).add(jsonRequest);
}
}