У меня есть этот проект, в котором я получаю в качестве активов некоторые URL / конечные точки / API.Я хочу взять значение («id») строки, найденной в каждом объекте массива JSON («result») первого API, и использовать его в качестве параметра тела для другого вызова API.
IУ меня есть один API (Получить все точки), в котором я передаю один токен в теле и получаю объект JSON с массивом результатов (эти результаты являются некоторыми точками).Все хорошо.Вот в чем проблема: для моего следующего API (Получить данные о месте) мне нужно пройти по каждому объекту (месту) в массиве «result» из предыдущего ответа API и получить его значение «id».Затем я буду использовать этот идентификатор в качестве основного параметра API Get spot details, поэтому при нажатии на элемент из списка точек откроется новое действие с подробной информацией о месте.
Я попытался поместить идентификатор в ArrayList, сделать его статическим и т. Д., Но при попытке передать идентификатор в качестве параметра мне выдается код ошибки 500.
//Get all spots result with the array in which I have to get each "id" value
{
"result": [
{
"id": "0dEGTxlKxh",
"name": "27-Waam",
"country": "India",
"whenToGo": "APRIL",
"isFavorite": true
},
{
"id": "s7uMTLEM6g",
"name": "2nd Bay",
"country": "Morocco",
"whenToGo": "AUGUST",
"isFavorite": true
}, ...
}
//The id (taken from the prvious list of spots) that I need to put in the body of Get spot details POST request
{
"spotId": "DqeOFHedSe"
}
//Example of result by Get spot details API with the id of the clicked spot in the list
{
"result": {
"id": "DqeOFHedSe",
"name": "Pocitas Beach",
"longitude": -81.08,
"latitude": -4.11,
"windProbability": 87,
"country": "Ecuador",
"whenToGo": "OCTOBER",
"isFavorite": true
}
}
//Request details using volley for the clicked spot
try {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest requestDetails = new StringRequest(Request.Method.POST, GET_SPOT_DETAILS,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject result = new JSONObject(response);
SpotInfo.name = result.getString("name");
SpotInfo.country = result.getString("country");
/*SpotInfo.latitude = result.getDouble("latitude");
SpotInfo.longitude = result.getDouble("longitude");
SpotInfo.windPbb = result.getDouble("windProbability");*/
SpotInfo.whenToGo = result.getString("whenToGo");
} catch (JSONException e) {
Log.d(TAG, "Error when parsing all details in JSON.", e);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "OnErrorResponse", error);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spotId", idArray.get(position)); //I think here is the problem
return params;
}
};
queue.add(requestDetails);
startActivity(new Intent(MainActivity.this, SpotInfo.class));
}
});
} catch(
Exception e) {
Log.e("OnItemClick", "OnItemClick error.", e);
}
//Iterating through the spots provided by Get allspots request
private static ArrayList<KitesurfingSpot> getAllSpotsFromJsonResult(String spotJSON) {
if(TextUtils.isEmpty(spotJSON))
return null;
ArrayList<KitesurfingSpot> spots = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(spotJSON);
JSONArray resultsArray = baseJsonResponse.getJSONArray("result");
for(int i=0; i < resultsArray.length(); i++) {
JSONObject spot = resultsArray.getJSONObject(i);
idStrings.add(spot.getString("id")); //Here I get the id
String name = spot.getString("name");
String country = spot.getString("country");
KitesurfingSpot kitesurfingSpot = new KitesurfingSpot(name, country, R.drawable.star_off);
spots.add(kitesurfingSpot);
}
} catch (JSONException e) {
Log.e(TAG, "Problem parsing the kitesurfing spot JSON result.", e);
}
return spots;
}