How to Fetch and Parse JSON data from API in Android Studio using Volley (2021)

How to Fetch and Parse JSON data from API in Android Studio using Volley (2021)



Introduction : 

In this article we are going to learn how to fetch data from API and parse it. We are going to use Volley in our API parsing.

  • Firstly we need to implement 2 dependencies in our build.gradle.

    implementation 'com.android.volley:volley:1.1.1'
    implementation 'org.jsoup:jsoup:1.13.1'


  • Now we have to build our StringRequest.
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Res : ",response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
});

  • Here we have two things, our response listener and our error listener. Error listener is used to catch the error message we are getting from the server in case of the server not found or wrong API,etc. We usually use Logs to see these errors.

  • Now if you have basic knowledge of data structures the you will be aware of queue. We are using similar things here, we'll put our request in Queue to be executed let's see how


RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);



  • By adding request in queue we are done with data fetching.
  • It's time for data parsing, so if our required data in JSON is present in "{" type of brackets then they'll be parsed using the JSONObject and if they are present in our "[" then they'll be parsed using JSONArray.

{
    "page": 1,
    "per_page": 6,
    "total": 12,
    "total_pages": 2,
    "data": [
        {
            "id": 1,
            "email": "[email protected]",
            "first_name": "George",
            "last_name": "Bluth",
            "avatar": "https://reqres.in/img/faces/1-image.jpg"
        },
        {
            "id": 2,
            "email": "[email protected]",
            "first_name": "Janet",
            "last_name": "Weaver",
            "avatar": "https://reqres.in/img/faces/2-image.jpg"
        },
        {
            "id": 3,
            "email": "[email protected]",
            "first_name": "Emma",
            "last_name": "Wong",
            "avatar": "https://reqres.in/img/faces/3-image.jpg"
        },
        {
            "id": 4,
            "email": "[email protected]",
            "first_name": "Eve",
            "last_name": "Holt",
            "avatar": "https://reqres.in/img/faces/4-image.jpg"
        },
        {
            "id": 5,
            "email": "[email protected]",
            "first_name": "Charles",
            "last_name": "Morris",
            "avatar": "https://reqres.in/img/faces/5-image.jpg"
        },
        {
            "id": 6,
            "email": "[email protected]",
            "first_name": "Tracey",
            "last_name": "Ramos",
            "avatar": "https://reqres.in/img/faces/6-image.jpg"
        }
    ],
    "support": {
        "url": "https://reqres.in/#support-heading",
        "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
    }
}


  • As we are going to set first name and email they are present in JSONObject > JSONArray. So, whenever we try to parse a data in out response listener then we'll be using try catch blocks because if we get the wrong keyword then our app will crash so in order to save our app from crashing we'll use try catch.
  • We'll parse our data according to our data type for example, our "first name" and "email" is in string type so we'll parse it in String but if we want to parse "id" then we'll use integer for receiving such data.

try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray.length()>0){
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String name = jsonObject1.getString("first_name");
String email = jsonObject1.getString("email");
dataList.add(new Model(name,email));
}
Adapter adapter = new Adapter(dataList,MainActivity.this);
myRv.setLayoutManager(new LinearLayoutManager(MainActivity.this,RecyclerView.VERTICAL,false));
myRv.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
}

  • This is our try catch block inside our response listener.
  • We'll use a for loop for accessing data inside a array. Once we received our data in a local variable then we have to add it in our array list and set our adapter.



Note : 

  • If you want to pass some parameters while hitting an API in volley then we have getParams() function for this here is an example below.

StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Res : ",response);

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String>params=new HashMap<>();
params.put("sample params","data");
return params;
}
};

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

  • Here in "sample params" we can send our parameters using our Hashmaps
  • If  you want to send authentication headers then we have getHeaders() function. Here is the example below.

StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Res : ",response);

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
}){
@Override
public Map<String, String> getHeaders() {
String username ="[email protected]";
String password = "dani3173";
String auth =new String(username + ":" + password);
byte[] data = auth.getBytes();
String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization",base64);
headers.put("accept-language","EN");
headers.put("Content-type","application/json");
headers.put("Accept","application/json");
return headers;
}
};

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
  • That's all for the API parsing, feel free to write suggestions and doubts in comment section.


Post a Comment

0 Comments