Networking and API Calls in Android – Retrofit & Volley - Textnotes

Networking and API Calls in Android – Retrofit & Volley


Learn how to make network requests in Android using Retrofit and Volley. Understand how to handle JSON data and make HTTP requests efficiently in Android apps.

Networking and API Calls

In Android, making network calls to communicate with web APIs is a common requirement. Networking is crucial for most apps, whether you're fetching data from a server, submitting form data, or working with remote resources. There are various libraries available for handling network calls in Android, but Retrofit and Volley are the most commonly used ones.

In this tutorial, we will explore how to make network requests using Retrofit and Volley, two popular libraries for handling HTTP calls in Android.

i) Retrofit for API Integration

Retrofit is a type-safe HTTP client for Android and Java, developed by Square. It simplifies the process of making HTTP requests and parsing the response into Java objects. Retrofit supports various data formats such as JSON, XML, and protocol buffers, but JSON is the most commonly used format in Android apps.

Steps to Use Retrofit

  1. Add Dependencies:

To get started with Retrofit, first, add the necessary dependencies to your build.gradle file:


implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
  1. Create a Model Class (POJO):

Create a class to represent the JSON structure you want to parse. For example, if you're fetching user details, you can define a User model class.


public class User {
private String name;
private String email;
private String phone;

// Getters and Setters
}
  1. Define an API Interface:

Create an interface that defines the API endpoints and their HTTP methods. Retrofit uses annotations to define the HTTP method (GET, POST, PUT, DELETE) and the URL.


public interface ApiService {
@GET("users/{id}")
Call<User> getUser(@Path("id") int userId);
}
  1. Set Up Retrofit Instance:

Create a Retrofit instance and configure it to use a converter (like Gson) to parse JSON responses into Java objects.


Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();

ApiService apiService = retrofit.create(ApiService.class);
  1. Make a Network Request:

Call the defined API method and handle the response using enqueue() for asynchronous requests or execute() for synchronous requests.


Call<User> call = apiService.getUser(1);

call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
User user = response.body();
// Handle the response
}
}

@Override
public void onFailure(Call<User> call, Throwable t) {
// Handle failure
}
});

ii) Volley for API Integration

Volley is another library for making network requests, developed by Google. It is primarily used for image loading and simple network operations, but it also supports JSON parsing and HTTP requests.

Steps to Use Volley

  1. Add Dependencies:

Add the Volley dependency to your build.gradle file:


implementation 'com.android.volley:volley:1.2.1'
  1. Set Up RequestQueue:

Volley uses a RequestQueue to manage network requests. Initialize it in your Application or Activity class.


RequestQueue requestQueue = Volley.newRequestQueue(this);
  1. Make a Network Request:

You can make various types of network requests using Volley, including StringRequest, JsonObjectRequest, and JsonArrayRequest. Here's an example of making a GET request with JsonObjectRequest:


String url = "https://api.example.com/users/1";

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String name = response.getString("name");
String email = response.getString("email");
// Handle the response
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});

requestQueue.add(jsonObjectRequest);
  1. Post Data Using Volley:

You can send data to the server using POST requests. Here's an example of sending a JSON object in a POST request:


String url = "https://api.example.com/users";

JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("name", "John Doe");
jsonBody.put("email", "john@example.com");
} catch (JSONException e) {
e.printStackTrace();
}

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Handle response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});

requestQueue.add(jsonObjectRequest);

iii) Handling JSON Data in Android

Both Retrofit and Volley work well with JSON data, as JSON is a popular data format for APIs. In both libraries, JSON data is automatically parsed into Java objects. Here’s how JSON handling is done with Retrofit and Volley:

  1. With Retrofit, JSON parsing is done automatically using a Converter Factory (usually Gson). When you create the Retrofit instance, you add GsonConverterFactory.create() to handle the conversion from JSON to Java objects.
  2. With Volley, you can manually parse the JSON response using JSONObject or JSONArray. Volley does not provide automatic parsing like Retrofit, so you need to parse the response inside the onResponse() callback.

iv) Making HTTP Requests – Handling Errors

Both Retrofit and Volley provide ways to handle errors in network requests:

  1. Retrofit: Errors are handled through the onFailure() callback for network issues and onResponse() for response codes like 404, 500, etc. Retrofit provides a rich set of error responses using the Response.errorBody() and Response.code() methods.
  2. Volley: Volley provides the onErrorResponse() callback to handle errors like timeouts, server issues, or connectivity problems. You can also use VolleyError to get the error message or status code.

v) Conclusion

In this tutorial, we learned how to use Retrofit and Volley for making network requests in Android. Retrofit simplifies API integration with automatic data parsing and a cleaner API design, making it a preferred choice for most Android developers. Volley, on the other hand, is lightweight and useful for handling simpler requests and image loading.

By mastering these tools, you can make robust and efficient API calls in your Android applications, handling both synchronous and asynchronous requests. You can also efficiently work with JSON data, making network calls a breeze.