How to isolate Volley API call. Hey folks, I am coming with another…
Hey folks, I am coming with another interesting blog and that is how to isolate API calls from the Activity. I have used Google’s Volley library for demonstration.

Benefits to isolate API calls from Activity.

1. Easy to maintain.

2. No code boilerplate.

3. Make API error handling easy.

How to structure the code:-

1. Create a different class to execute API calls. (NetworkController.java)

2. Create an interface to handle the API response. (APICallBackListener.java)

3. Make an API call from the Activity. (MainActivity.java)

First of all, create a different package called “APIService” and add NetworkController.java and APICallBackListener.java files.

Add the below code to your NetworkController.java file.

public class NetworkController {



private APICallBackListener mResultCallback = null;

private Context mContext;

private ProgressDialog progressDialog;

private String TAG = "API response";



public NetworkController(APICallBackListener resultCallback, Context context) {



mResultCallback = resultCallback;

mContext = context;

}





public void fetchPOSTAPIData(String url, final Map<String, String> params,boolean isShowProgressDialog) {



try {



if (isShowProgressDialog) {

initProgressDialog();

showProgressDialog();

}



RequestQueue queue = Volley.newRequestQueue(mContext);



StringRequest postRequest = new StringRequest(Request.Method.POST, url,

new Response.Listener<String>() {



@Override

public void onResponse(String response) {

// API response

Log.e(TAG, response);

if (mResultCallback != null) { mResultCallback.notifySuccess(response);

}

hideProgressDialog();

}

},

new Response.ErrorListener() {



@Override

public void onErrorResponse(VolleyError error) {

// error

Log.e(TAG, error.networkResponse.toString());

if (mResultCallback != null)

mResultCallback.notifyError(error);

hideProgressDialog();

}

}

) {



@Override

protected Map<String, String> getParams() {



return params;

}

};

queue.add(postRequest);



} catch (Exception e) {

e.printStackTrace();

}

}



public void fetchGETAPIData(String url, boolean isShowProgressDialog) {



try {



if (isShowProgressDialog) {

initProgressDialog();

showProgressDialog();

}



RequestQueue queue = Volley.newRequestQueue(mContext);



StringRequest stringRequest = new StringRequest(Request.Method.GET,url, new Response.Listener<String>() {



@Override

public void onResponse(String response) {



Log.e(TAG, response);

if (mResultCallback != null)

mResultCallback.notifySuccess(response);

hideProgressDialog();

}

}, new Response.ErrorListener() {



@Override

public void onErrorResponse(VolleyError error) {



Log.e(TAG,

error.networkResponse.toString());

if (mResultCallback != null)

mResultCallback.notifyError(error);

hideProgressDialog();

}

});

queue.add(stringRequest);

} catch (Exception e) {

e.printStackTrace();

}

}



private void initProgressDialog() {



progressDialog = new ProgressDialog(mContext);

progressDialog.setTitle("Fetching data");

progressDialog.setMessage("Please wait");

progressDialog.setCancelable(false);

}



private void showProgressDialog() {



if (progressDialog != null) {

if (!progressDialog.isShowing())

progressDialog.show();

} else

initProgressDialog();

}



private void hideProgressDialog() {



if (progressDialog != null) {

if (progressDialog.isShowing())

progressDialog.dismiss();

}

}

}

fetchGETAPIData() — This method is used to make GET API calls using Volley.

fetchPOSTAPIData() — This method is used to make POST API calls using volley. Pass parameters from the activity class.

Now, add the below code to your APICallBackListener.java file.

public interface APICallBackListener {



void notifySuccess(String response);



void notifyError(VolleyError error);

}

At last call API from the MainActivity.java file.

public class MainActivity extends AppCompatActivity { private Context context;

private Button btnSubmit;

APICallBackListener callBackListener;

NetworkController networkManager; @Override

protected void onCreate(Bundle savedInstanceState) {



super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

context = this;



initControls();

initCallBack();

} private void initCallBack() {



callBackListener = new APICallBackListener() {



@Override

public void notifySuccess(String response) {



Toast.makeText(context, "API call success", Toast.LENGTH_SHORT).show();

/*Add your stuff here */

}



@Override

public void notifyError(VolleyError error) {



Toast.makeText(context, "API call Failed", Toast.LENGTH_SHORT).show();

/*Add your stuff here */

}

};

} private void initControls() {



btnSubmit = findViewById(R.id.btnSubmit);

btnSubmit.setOnClickListener(new View.OnClickListener() {



@Override

public void onClick(View v) {



String url="https://randomuser.me/api/0.4/?randomapi";

networkManager.fetchGETAPIData(url, true);

}

});

}}

Now, how to make POST request:-

- Create a parameter list and pass it as an argument to the fetchPOSTAPIData() method.



public void onClick(View v) {



String url = "



Map<String, String> params = new HashMap<String, String>(); @Overridepublic void onClick(View v) {String url = " http://httpbin.org/post ";Map params = new HashMap ();

params.put("domain", "

networkManager.fetchPOSTAPIData(url, params, true);

} params.put("name", "XYZ");params.put("domain", " http://xyz.info ");networkManager.fetchPOSTAPIData(url, params, true);

Woah!!! we are done with the code. Now, run and test the application.

If you find worth reading this blog, don’t forget to clap 😉
['Maitri Varia']
['Mobile App Development', 'Android', 'Mobile Apps', 'Api Integration', 'Volley']