20

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

Bajirao Shinde
  • 1,356
  • 1
  • 18
  • 26
Kalpesh Kumawat
  • 369
  • 1
  • 3
  • 8

5 Answers5

38

First create callback interface to get result in Activity

public interface IResult {
    public void notifySuccess(String requestType,JSONObject response);
    public void notifyError(String requestType,VolleyError error);
}

Create a separate class with volley function to response the result through interface to activity

public class VolleyService {

    IResult mResultCallback = null;
    Context mContext;

    VolleyService(IResult resultCallback, Context context){
        mResultCallback = resultCallback;
        mContext = context;
    }


    public void postDataVolley(final String requestType, String url,JSONObject sendObj){
        try {
            RequestQueue queue = Volley.newRequestQueue(mContext);

            JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if(mResultCallback != null)
                        mResultCallback.notifySuccess(requestType,response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(mResultCallback != null)
                        mResultCallback.notifyError(requestType,error);
                }
            });

            queue.add(jsonObj);

        }catch(Exception e){

        }
    }

    public void getDataVolley(final String requestType, String url){
        try {
            RequestQueue queue = Volley.newRequestQueue(mContext);

            JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if(mResultCallback != null)
                        mResultCallback.notifySuccess(requestType, response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(mResultCallback != null)
                        mResultCallback.notifyError(requestType, error);
                }
            });

            queue.add(jsonObj);

        }catch(Exception e){

        }
    }
} 

Then initialize callback interface into main activity

    mResultCallback = new IResult() {
        @Override
        public void notifySuccess(String requestType,JSONObject response) {
            Log.d(TAG, "Volley requester " + requestType);
            Log.d(TAG, "Volley JSON post" + response);
        }

        @Override
        public void notifyError(String requestType,VolleyError error) {
            Log.d(TAG, "Volley requester " + requestType);
            Log.d(TAG, "Volley JSON post" + "That didn't work!");
        }
    };

Now create object of VolleyService class and pass it context and callback interface

mVolleyService = new VolleyService(mResultCallback,this);

Now call the Volley method for post or get data also pass requestType which is to identify the service requester when getting result back into main activity

    mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
    JSONObject sendObj = null;

    try {
        sendObj = new JSONObject("{'Test':'Test'}");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);

Final MainActivity

public class MainActivity extends AppCompatActivity {
    private String TAG = "MainActivity";
    IResult mResultCallback = null;
    VolleyService mVolleyService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initVolleyCallback();
        mVolleyService = new VolleyService(mResultCallback,this);
        mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
        JSONObject sendObj = null;

        try {
            sendObj = new JSONObject("{'Test':'Test'}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
    }

    void initVolleyCallback(){
        mResultCallback = new IResult() {
            @Override
            public void notifySuccess(String requestType,JSONObject response) {
                Log.d(TAG, "Volley requester " + requestType);
                Log.d(TAG, "Volley JSON post" + response);
            }

            @Override
            public void notifyError(String requestType,VolleyError error) {
                Log.d(TAG, "Volley requester " + requestType);
                Log.d(TAG, "Volley JSON post" + "That didn't work!");
            }
        };
    }

}

Find the whole project at following link

https://github.com/PatilRohit/VolleyCallback

Rohit Patil
  • 1,068
  • 8
  • 9
  • 1
    How i can call more than one Api in single Activity ? – Kalpesh Kumawat Feb 27 '16 at 08:00
  • Awesome..Thanks :) – Sumit Jha Dec 20 '16 at 09:11
  • thanks, i have to add null param. JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener() – cristianego May 10 '17 at 02:55
  • is work..but how to add the param when post data using this method?Can u give me a hint? – ken Jul 05 '17 at 09:51
  • The get call iis work..But the post call doesnt,so how to add the param when post data using this method?Can u give me a hint? – ken Jul 05 '17 at 10:44
  • you need to pass only URL and JSON Object which you want to send like mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj); and first parameter is to identify callback – Rohit Patil Jul 07 '17 at 07:10
  • Thanks for this amazing solution. i think it is observation pattern ! isn't it? – Mohammad Aug 09 '17 at 16:28
  • in this solution you will create a `RequestQueue` on each call to the `get` and `post` functions, while in the documentation it tells "If your application makes constant use of the network, it's probably most efficient to set up a single instance of RequestQueue that will last the lifetime of your app".....source: https://developer.android.com/training/volley/requestqueue.html – codeKiller Sep 05 '17 at 09:17
  • In PHP, the POST parameters are not catched with $_POST or $_REQUEST. You need to use $request = file_get_contents('php://input'); – sariDon Jul 12 '20 at 13:33
3

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<String, String> 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<String>() {
        @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<String, String> 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.

hetsgandhi
  • 726
  • 3
  • 9
  • 25
2

you actually missed one parameter in the above VolleyService class. You needed to include, it is,... JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null,new Response.Listener() { /..../ } null is the parameter should be included else it gives error

Chinmai KH
  • 39
  • 1
  • 4
  • Thanks for suggestion.. but don’t worry about that super class constructor automatically do it for null object request so no need to pass and also you can’t!!! – Rohit Patil Mar 03 '17 at 09:40
0

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<JSONObject> listenerResponse = new Listener<JSONObject>() {

    @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<JSONObject> listenerResponse,  ErrorListener listenerError) {

    JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError);

    Volley.newRequestQueue(context).add(jsonRequest);
}

}

Thracian
  • 43,021
  • 16
  • 133
  • 222
0
public class VolleyService {

    IResult mResultCallback = null;
    Context mContext;

    VolleyService(IResult resultCallback, Context context)
    {
        mResultCallback = resultCallback;
        mContext = context;
    }

    //--Post-Api---
    public void postDataVolley(String url,final Map<String,String> param){
        try {
            StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if(mResultCallback != null)
                        mResultCallback.notifySuccessPost(response);
                }
            },  new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(mResultCallback != null)
                        mResultCallback.notifyError(error);
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    return param;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Content-Type", "application/x-www-form-urlencoded");
                    return params;
                }
            };
            AppController.getInstance(mContext).addToRequestQueue(sr);

        }catch(Exception e){

        }
    }
    //==Patch-Api==
    public void patchDataVolley(String url,final HashMap<String,Object> param)
    {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.PATCH, url, new JSONObject(param),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if(mResultCallback != null)
                            mResultCallback.notifySuccessPatch(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if(mResultCallback != null)
                            mResultCallback.notifyError(error);
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                return headers;
            }
        };
        AppController.getInstance(mContext).addToRequestQueue(request);
    }
}

public interface IResult {
    void notifySuccessPost(String response);

    void notifySuccessPatch(JSONObject jsonObject);

    void notifyError(VolleyError error);

}
Pankaj Kharche
  • 1,329
  • 4
  • 15
  • 37