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

5

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...

Unipolar answered 25/2, 2016 at 13:3 Comment(0)
F
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

Furnishing answered 25/2, 2016 at 14:1 Comment(9)
How i can call more than one Api in single Activity ?Unipolar
Awesome..Thanks :)Befriend
thanks, i have to add null param. JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>()Merchant
is work..but how to add the param when post data using this method?Can u give me a hint?Fagan
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?Fagan
you need to pass only URL and JSON Object which you want to send like mVolleyService.postDataVolley("POSTCALL", "192.168.1.150/datatest/post/data", sendObj); and first parameter is to identify callbackFurnishing
Thanks for this amazing solution. i think it is observation pattern ! isn't it?Faulk
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: developer.android.com/training/volley/requestqueue.htmlJodhpur
In PHP, the POST parameters are not catched with $_POST or $_REQUEST. You need to use $request = file_get_contents('php://input');Reference
P
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.

Passant answered 17/6, 2017 at 9:56 Comment(0)
H
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

Holozoic answered 10/2, 2017 at 7:25 Comment(1)
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!!!Furnishing
U
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);
}

}

Upcast answered 22/1, 2017 at 8:5 Comment(0)
C
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);

}
Clean answered 23/1, 2018 at 13:3 Comment(1)
errror AppController.getInstance(mContext).addToRequestQueue(request);Encomiast

© 2022 - 2024 — McMap. All rights reserved.