2

I am using Volley to make network calls in my application... For many screens ...(say fragments) I am making various requests like LoginRequest, FetchUsers Request, FetchExams Request..... and handling response and errors in each fragments.

What is the best approach I can use like.... 1. Subclass a request 2. Create an interface/callbacks 3. Get results/response or error response in my fragment...

This is how I am doing ....creating many such methods.....

 private void syncAllUsers() {
        progressDialog.setMessage("Loading Users...");

        StringRequest jsonProductCategoryFetchRequest = new StringRequest(Request.Method.POST, Config.SELECT_USERS,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        try {
                            if(Constants.DEBUG_MODE_ON)
                                Log.d(Constants.DEBUG_LOG, "RESPONSE for Teachers: "+response);

                            JSONObject result = new JSONObject(response);
                            boolean code = result.getBoolean("error");

                            if (!code) {
                                //Get the Users Json Array
                                JSONArray ja = result.getJSONArray("users");
                                if(ja != null) {
                                    db.deleteAllUsers();
                                    for (int i = 0; i < ja.length(); i++) {
                                        JSONObject jobj = ja.getJSONObject(i);
                                        User user = new User();
                                        user.setId(jobj.getInt(User.KEY_ID));
                                        user.setName(jobj.getString(User.KEY_NAME));
                                        user.setEmail(jobj.getString(User.KEY_EMAIL));
                                        user.setPhone(jobj.getString(User.KEY_PHONE));
                                        user.setGender(jobj.getString(User.KEY_GENDER));
                                        user.setUsername(jobj.getString(User.KEY_USERNAME));
                                        user.setPassword(jobj.getString(User.KEY_PASSWORD));
                                        user.setOrganization_id(jobj.getString(User.KEY_ORGANIZATION_ID));
                                        user.setDob(jobj.getString(User.KEY_DOB));
                                        user.setStatus(jobj.getString(User.KEY_STATUS));
                                        user.setApi_key(jobj.getString(User.KEY_API_KEY));
                                        user.setDate_created(jobj.getString(User.KEY_DATE_CREATED));
                                        user.setRole_id(jobj.getInt(User.KEY_ROLE_ID));

                                        //Delete local Teachers before updating
                                        db.createUser(user);

                                    } // for loop ends
                                }
                            }

                            //syncAllExams();
                            progressDialog.dismiss();
                            getActivity().finish();
                            startActivity(new Intent(getActivity(), MainActivity.class));

                        } catch (Exception e) {
                            Log.d(Constants.DEBUG_LOG, "Exception Syncing Users: " , e);
                            Toast.makeText(getActivity(),"Something went wrong while fetching users", Toast.LENGTH_SHORT).show();
                            progressDialog.dismiss();
                            getActivity().finish();
                            startActivity(new Intent(getActivity(), MainActivity.class));
                        }
                    }
                } , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(Constants.DEBUG_MODE_ON)
                    Log.d(Constants.DEBUG_LOG, "Error Response for Users : "+error.getCause()+""+error.toString());
                Toast.makeText(getActivity(), getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
                getActivity().finish();
                startActivity(new Intent(getActivity(), MainActivity.class));

            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                params.put(User.KEY_ORGANIZATION_ID, preferencesManager.getOrganizationID());
                params.put(User.KEY_API_KEY, preferencesManager.getApiKey());
                Log.d("Registration", "PARAMS : " + params.entrySet());
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> params = new HashMap<String, String>();
               // params.put("Content-Type", "application/json; charset=utf-8");
                params.put("Content-Type", "application/x-www-form-urlencoded");

                String auth = preferencesManager.getApiKey();
                params.put("Authorization", auth);
                return params;
            }
        };


        MyApplication.getInstance().addToReqQueue(jsonProductCategoryFetchRequest);
    }

I think there would be a clean way to perform this. Any suggestions.

Vishal Kumar
  • 4,419
  • 1
  • 25
  • 31

2 Answers2

1

I have been using this class for creating requests, it transforms your json into your object automaticaly with gson. Find example here: https://gist.github.com/ficusk/5474673

Vulovic Vukasin
  • 1,540
  • 2
  • 21
  • 30
  • Yes Vulovic... this is something I was looking for... still have some confusions.... How can I use this GsonRequest.... is this a user defined class or belong to volley. Also... can you plz elaborate a little on code separations.... how to avoid repeating codes ...while creating requests. – Vishal Kumar Feb 16 '16 at 08:49
  • I used below links to create all the classes I need for the handlers. Basically, you will have a class for each request you are sending. http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/ http://stackoverflow.com/questions/24873718/how-do-i-make-a-volley-jsonobject-request-with-a-custom-object-as-a-parameter http://benjii.me/2010/04/deserializing-json-in-android-using-gson/ – Vulovic Vukasin Feb 16 '16 at 08:52
1

Create Request Manager.. Which is only dealing with Requesting your web services. That Manager should also handle any network error and other errors which are not application layer.

Use this request manager from your Model classes where your business logic is. Send Request Parameter as JSON.. Also you can send your different listeners from to Request Manager So that when web service response comes it directly comes to you Model class and you can parse JSON response according to your needs.

This way parsing logic stays with Model class and Requesting logic stays with Request manager.. So in future if you change web service address you need to check only one place.. And if you change request and response parameter for webservice you dont need to change request manager and only Model class...

There might be some other ways..

public final class RequestManager {

private static final String ROOT_HOST = //Your Webservice Host Root.


private RequestQueue queue;

public RequestManager(final Context context) {
       queue = Volley.newRequestQueue(context);
}

//Internal Calling method .. Not exposed..
private void doRequest(final int method, final String url, final JSONObject jsonParam, final Response.Listener<JSONObject> listener,
                    final Response.ErrorListener errlsn) {

            JSONObjectRequest jsonObjectRequest = new SONObjectRequest(method, url, jsonParam, listener, errlsn);
            queue.add(jsonObjectRequest);
}

public void doLogin(final User user, final Response.Listener<JSONObject> listener, final Response.ErrorListener errlsn)
                    throws Exception {
            // Make login request JSON here
            if (user == null || listener == null || errlsn == null) {
                    //throw Exception
            }
            final JSONObject jsonObj = new JSONObject();
            //Convert user object to JSON Object
            doRequest(Request.Method.GET, LOGIN_URL, jsonObj, listener, errlsn);

     }
}
ValayPatel
  • 1,094
  • 12
  • 15