I'm trying to do a written report on some code and I found one on Youtube. However, I don't understand how some of this loop works. I understand that it goes through every item in the list and fetches each value for each variable and that it then adds all values to a list which is presented in an XML view in Android studio. if someone could breakdown what is happening it would be greatly appreciated!
private void setupData() {
RequestQueue queue = Volley.newRequestQueue(this);
String url =" - hidden - ";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length() ; i++){
JSONObject jo = jsonArray.getJSONObject(i);
System.out.println(jo.toString());
Supplier supplier = new Supplier(String.valueOf(jo.getInt("id")), jo.getString("name"), jo.getString("url"), jo.getString("specialization"), jo.getString("country"), jo.getInt("rating"));
supplierList.add(supplier);
System.out.println(jsonArray.length());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
System.out.println("That didn't work!");
}
});
queue.add(request);
}
Though you can simply read about the JSONObject class and all other classes belonging to the package. But, let me put it what I understand with an example here. Here is the response json that is being received.
The code is trying to process this complete json. It starts with reading the "data" object into an array since it represents an array and then convert every object block in that array to a Supplier model class and then add it into SupplierList.