If you want to upload array of object using Retrofit then follow the steps. It will work 100%.
In my case I have 2 params one is userId and second is location_data. In second params I have to pass array of objects.
@FormUrlEncoded
@POST("api/send_array_data")
Call<StartResponseModal> postData(@Field("user_id") String user_id,
@Field("location_data") String
jsonObject);
then in your MainActivity.class / Fragments.
ArrayList<JSONObject> obj_arr; // define this at top level.
try {
JSONArray jsonArray = new JSONArray();
obj_arr = new ArrayList<>();
// LocationData is model class.
for (LocationData cart : arrayList) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("latitude", cart.getLatitude());
jsonObject.put("longitude", cart.getLongitude());
jsonObject.put("address", cart.getAddress());
jsonObject.put("battery", cart.getBattery());
jsonObject.put("is_gps_on", cart.getIs_gps_on());
jsonObject.put("is_internet_on",
cart.getIs_internet_on());
jsonObject.put("type", cart.getType());
jsonObject.put("date_time", cart.getDate_time());
jsonArray.put(jsonObject);
obj_arr.add(jsonObject);
}
Log.e("JSONArray", String.valueOf(jsonArray));
} catch (JSONException jse) {
jse.printStackTrace();
}
String user_id = SharedPreferenceUtils.getString(getActivity(),
Const.USER_ID);
RetrofitAPI retrofitAPI =
APIClient.getRetrofitInstance().create(RetrofitAPI.class);
Call<StartResponseModal> call =
retrofitAPI.postData(user_id,obj_arr.toString());
call.enqueue(new Callback<StartResponseModal>() {
@Override
public void onResponse(Call<StartResponseModal> call,
Response<StartResponseModal> response) {
// Handle success
if (response.isSuccessful() &&
response.body().getErrorCode().equals("0")) {
// Process the response here
Log.e("Hello Room data send","Success");
deleteItemsFromDatabase();
} else {
// Handle API error
Log.e("Hello Room data send","failed else");
}
}
@Override
public void onFailure(Call<StartResponseModal> call, Throwable t) {
// Handle failure
Log.e("Hello Room send","failure");
}
});