How to make separate class for volley library and call all method of volley from another activity and get response?

前端 未结 5 1491
不知归路
不知归路 2020-12-01 06:42

how to create a separate class in which define all about volley and in another activity we directly pass URL,CONTEXT and Get Response...

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 07:26

    JsonParserVolley.java

    (A separate class where we will get the response)

    public class JsonParserVolley {
    
    final String contentType = "application/json; charset=utf-8";
    String JsonURL = "Your URL";
    Context context;
    RequestQueue requestQueue;
    String jsonresponse;
    
    private Map header;
    
    public JsonParserVolley(Context context) {
        this.context = context;
        requestQueue = Volley.newRequestQueue(context);
        header = new HashMap<>();
    
    }
    
    public void addHeader(String key, String value) {
        header.put(key, value);
    }
    
    public void executeRequest(int method, final VolleyCallback callback) {
    
        StringRequest stringRequest = new StringRequest(method, JsonURL, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                jsonresponse = response;
                Log.e("RES", " res::" + jsonresponse);
                callback.getResponse(jsonresponse);
    
    
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        }) {
            @Override
            public Map getHeaders() throws AuthFailureError {
    
                return header;
            }
        }
        ;
        requestQueue.add(stringRequest);
    
    }
    
    public interface VolleyCallback
    {
        public void getResponse(String response);
    }
    

    }

    MainActivity.java (Code Snippet written in onCreate method)

    final JsonParserVolley jsonParserVolley = new JsonParserVolley(this);
        jsonParserVolley.addHeader("Authorization", "Your value");
        jsonParserVolley.executeRequest(Request.Method.GET, new JsonParserVolley.VolleyCallback() {
    
            @Override
            public void getResponse(String response) {
    
                jObject=response;
                Log.d("VOLLEY","RES"+jObject);
    
                parser();
            }
        }
        );
    

    parser() is the method where the json response obtained is used to bind with the components of the activity.

提交回复
热议问题