I want to pass data using volley API to server. The parameters be like :
Request:
{
"user_id" : 6,
"package_name": "Personal Package",
"care_type" : ["help in shopping", "Personal care"],
"care_delivered" : "as day care",
"gender" : "F",
"experience" : "4,0",
"skills":"very helpful , caring, etc",
"start_date" : "2018-09-12",
"price": "200-700, day",
"description": "test"
}
In this care_type is an array type. I have done code to send data but each time I am getting error i.e.
onErrorResponse: Error: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
My Code for API is :
private void createPackageApi() {
String tag_json_obj = "json_obj_req";
String url = Constants.CREATE_PACKAGE;
pBar.setVisibility(View.VISIBLE);
Activity activity = getActivity();
if (activity != null && isAdded()) {
sessionManager = new SessionManager(activity);
}
final HashMap<String, String> packageDetail = sessionManager.getPackageDetail();
JSONArray jsonArray;
try {
jsonArray = new JSONArray(required_support_need);
strArr = new String[jsonArray.length()];
Log.e("tag", "package" + required_support_need + " " + strArr);
for (int i = 0; i < jsonArray.length(); i++) {
strArr[i] = "\"" + jsonArray.getString(i) + "\"";
Log.e("TAG", "getInitializedID:String " + strArr[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
final HashMap<String, String> registrationDetail = sessionManager.getSeekerRegistrationDetail();
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id", "2");
params.put("package_name", edtPackageNames.getText().toString());
params.put("care_type", Arrays.toString(strArr));
params.put("care_delivered", edtCarePackages.getText().toString());
params.put("gender", edtPreferredGender.getText().toString());
params.put("experience", edtPackageNames.getText().toString());
params.put("skills", edtEssentialSkills.getText().toString());
params.put("start_date", packageDetail.get("start_date"));
params.put("price", edtPackageValue.getText().toString());
params.put("description", edtPackageDescription.getText().toString());
Log.e("TAG", "seekerPackage: " + params);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("package_detail_response", response.toString());
Gson gson = new Gson();
try {
if (response.has("success")) {
CreatePackage createPackage;
createPackage = gson.fromJson(response.toString(), CreatePackage.class);
String status = createPackage.getSuccess();
if (status.equals("success")) {
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(getActivity(), R.string.package_created, Toast.LENGTH_LONG).show();
}
}
pBar.setVisibility(View.GONE);
} else {
ResponseError responseError;
responseError = gson.fromJson(response.toString(), ResponseError.class);
String msg = responseError.getMessage();
Log.e("TAG", "msg " + msg);
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pBar.setVisibility(View.GONE);
VolleyLog.e("Error: " + error.getMessage());
// handle error
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=UTF-8");
headers.put("Authorization", "Bearer " + registrationDetail.get("api_token"));
return headers;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
I have tried to send array in parameters but I am not getting success. Please tell me how to send array in single parameter in volley library.
To post array use below code
JSONArray care_type = new JSONArray();
for(int i=0; i < yourarray.length(); i++) {
care_type.put(yourarray[i]); // create array and add items into that
}
params.put("care_type",care_type.toString());
Add your array in JSONArray and sent it to with the key name
JSONArray dataObject = new JSONArray(filterListing);
paramObject.put("data",dataObject);
Use :
HashMap<String ,String> params=new HashMap<String, String>();
for(int i=1;i<=parms.size;i++){
params.put("params_"+i, arr[i]);
}
Use JJSONArray to send Values .
JSONArray jsonObject=new JSONArray();
for(int i=1;i<=size;i++)
{
arr[i]="userId_"+i+"_"+"ans_"+i;
jsonObject.put("params_"+i,arr[i]);
}
HashMap<String ,String> params=new HashMap<String, String>();
params.put("params",jsonObject.toString());
TO send all values on server side get params and convert to JSON object and iterate to get all values
Related
I have an API link to send post request for creating the order,
I tried to set Request in this way.
I want to send POST request same as request to send in my image (Postman).
I want to create order from cart using cartID and index of the cart, how to send please help me out from this.
Thank You :
public void postCreateOrderByCustomer(ArrayList<CartItem> cartItems) {
String token = sharedPreferences.getString(Constant.token, null);
String endPoint = "https://prettyyou.in/cake/pos/api/customers/create-order?token=" + token;
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Map<String, String> payloadParams = new HashMap<String, String>();
for (int i = 0; i < cartItems.size(); i++) {
payloadParams.put("cart[" + i
+ "][id]", cartItems.get(i).getId());
}
Log.d(TAG, "postCreateOrderByCustomer: " + jsonObject);
System.out.println("endPointCartGet" + " " + endPoint.toString());
jsonObject = new JSONObject(payloadParams);
Log.d(TAG, "postCreateOrderByCustomer: " + jsonObject);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, endPoint, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "onResponseCustomer: " + response);
if (response.getBoolean("status")) {
Constant.orderId = response.getString("order_id");
Intent intent = new Intent(DeliveryDetailsActivity.this, PaymentDetailsActivity.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return payloadParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return super.getHeaders();
}
};
RequestQueue queue = Volley.newRequestQueue(DeliveryDetailsActivity.this);
queue.add(jsonObjectRequest);
}
You can also use Stringrequest and object request or Jsonobject requst
i have some json output like this
{
"message": "success",
"battery": "AHAJAJ1DH13T0021",
"data": {
"id": 6,
"userId": 3,
"shopId": 1,
"transactionStatus": "PENDING",
"expiredAt": "2019-01-04T03:01:18.878Z",
"updatedAt": "2019-01-04T02:01:18.916Z",
"createdAt": "2019-01-04T02:01:18.916Z",
"paymentId": null,
"batteryNo": null
},
"shopData": {
"id": 1,
"name": "test1",
"tel": "555",
"address": "cikarang",
"description": "showroom",
"latitude": "-6.307923199999999",
"longitude": "107.17208499999992",
"open_time": "10.00",
"battery_available": 16,
"battery_booked": 1,
"status": 1,
"createdAt": "2018-12-28T03:59:55.156Z",
"updatedAt": "2019-01-04T02:01:18.940Z"
}
}
and i implement using volley like this
StringRequest request = new StringRequest(Request.Method.POST, ApiService.ORDER_BATTERY, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
BookBattery bookBattery = new BookBattery();
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.has("success")) {
JSONObject object = jsonObject.getJSONObject("battery");
String data = object.getString("");
JSONArray jsonArray = jsonObject.getJSONArray("data");
} else {
Log.e("Your Array Response", "Data Null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("token", TokenUser);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("shopId", String.valueOf(shopId));
//params.put("Pass", PassWord);
return params;
}
};
AppController.getInstance().addToRequestQueue(request, tag_json_obj);
but not working, please help thanks a lot
Use http://jsonviewer.stack.hu/ [To see json data structure]
braces {} its an JSONObject
brackets [] its an JSONArray
public void parseJson() {
try {
JSONObject jsonObject = new JSONObject(jsonParsing);
boolean isSuccess = jsonObject.getString("message").contains("success");
if (isSuccess) {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
String userId = jsonObject.getString("userId");
JSONObject jsonObjectShopData = jsonObject.getJSONObject("shopData");
String name = jsonObject.getString("tel");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You are not getting JSONArray anywhere, your response object has multiple JSONObject
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.has("success")) {
JSONObject object = jsonObject.getJSONObject("battery");
JSONOnject jsonObject2= jsonObject .getJSONObject("data");// here you need to change.
String batteryNo=jsonObject2.getJSONObject("batteryNo");
JSONOnject jsonObject3= jsonObject1.getJSONObject("shopData");
String address=jsonObject2.getJSONObject("address");
} else {
Log.e("Your Array Response", "Data Null");
}
You can use some lib for Volley (e.g. VolleyEx), together with Gson, to parse the JSON Object to a Map in Java.
i.e. using GsonObjectRequest instead of StringRequest
developer.android.com has the code, but there are also libs doing that for you.
example HERE
Try this
StringRequest request = new StringRequest(Request.Method.POST, ApiService.ORDER_BATTERY, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
BookBattery bookBattery = new BookBattery();
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("message");
if (message.equalsIgnoreCase("success")) {
String battery = jsonObject.getString("battery");
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONObject shopDataObject = jsonObject.getJSONObject("shopData");
int dataId = dataObject.getInt("id");
int dataUserId = dataObject.getInt("userId");
int dataShopId = dataObject.getInt("shopId");
} else {
Log.e("Your Array Response", "Data Null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("token", TokenUser);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("shopId", String.valueOf(shopId));
//params.put("Pass", PassWord);
return params;
}
};
AppController.getInstance().addToRequestQueue(request, tag_json_obj);
here i only parse "id", "userId" & "shopId" from dataObject. Rest can be parse in similar way.
Before do it I will suggest you please read about the json Array and Json Object.
Here the solution.
HashMap<String, String> params = new HashMap<String, String>();
params.put("your json parameter name", json parameter value);
// params.put("device_id", deviceID);
Log.d("response11", String.valueOf(params));
String Url ="your server url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Url,
new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG + "JO", String.valueOf(response));
try {
String msgObject = response.getString("message");
Log.d("response","msgObject");
}catch (JSONException e){
String jsonExp = e.getMessage();
Log.d(TAG + "JE", jsonExp);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String volleyErr = error.getMessage();
Log.d(TAG + "VE", volleyErr);
}
});
requestQueue.add(jsonObjectRequest);
this sufficient for print you server response. check response in logcat.
i am using volley library for post data over api...in here the Content-Type is "application/json" ....
how can i implement this type of json data :
URL: Base_URL + dorequisition
{
"submitted_by_employee_id": 1,
"name": "Technolive SF for TC",
"bags_thana_wise": [
{
"tiger": "10000",
"extreme": "5000",
"opc": "3000",
"three_rings": "4000",
"buffalo_head": "2000",
},
],
"free_bag": "500",
"landing_price": "450",
"transport_cost_ex_factory_rate": "450",
"amount_taka": "four hundred fifty",
"bank_name": "IFIC Bank Limited",
"delivery_point": "Banani",
"upto_today": "450",
"bag_type": "swing",
"remark": "Good Cement",
"token": "2cbf1cefb6fe93673565ed2a0b2fd1a1"
}
api implementation sample :
public void APIRetailVisitInfo() {
for (int i = 0; i < retailVisitInfoList.size(); i++) {
System.out.println("token id:::" + token + " :::"+employee_id);
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("submitted_by_employee_id", employee_id);
jsonParams.put("retailer_name", retailVisitInfoList.get(i).getRetails_name());
jsonParams.put("retailer_phone", retailVisitInfoList.get(i).getRetailer_contact_no());
jsonParams.put("retailer_address", retailVisitInfoList.get(i).getRetails_address());
jsonParams.put("remarks", retailVisitInfoList.get(i).getRemarks());
jsonParams.put("token", token);
JsonObjectRequest myRequest = new JsonObjectRequest(
Request.Method.POST,
"http://technolive.co/retailvisitinfo",
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
code = response.getString("code");
//token = response.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
if (code.equals("200")) {
System.out.println("APICompetetorBasedOnMArketPrice:::" + code + " :::");
}
// System.out.println("token:::" + token+" :::");*/
// verificationSuccess(response);
System.out.println("APICompetetorBasedOnMArketPrice:::" + response + " :::");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// verificationFailed(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String auth = token;
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
// headers.put("Authorization", auth);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(RetailVisitInfoActivity.this);
requestQueue.add(myRequest);
// MyApplication.getInstance().addToRequestQueue(myRequest, "tag");
}
}
can anyone help me please........
It is rather simple. First let's start with bags_thana_wise. bags_thana_wise is a JSONArray. It contains one object. So lets create the object.
JSONObject json1 = new JSONObject();
json1.put("tiger","10000";
json1.put("extreme","5000";
and so on..Now put this json object into an array
JSONArray jsonArray = new JSONArray();
jsonArray.put(json1);
Now just add this array and other values to another json object
JSONObject finalObject = new JSONObject();
finalObject.put("submitted_by_employee_id","1");
finalObject.put("name","Technolive SF for TC");
//put the jsonArray
finalObject.put("bags_thana_wise",jsonArray);
finalObject.put("free_bag","500");
.
.
.
finalObject.put("token","2cbf1cefb6fe93673565ed2a0b2fd1a1");
Now make the following volley request
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
myURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Handle response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PopupActivity.this,"Can not reach server",Toast.LENGTH_LONG).show();
}
}){
#Override
public String getBodyContentType(){
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
try {
return finalObject == null ? null: finalObject.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(RetailVisitInfoActivity.this);
requestQueue.add(jsonRequest);
i have created HashMap and JsonArrayRequest object as follows. Response is successfully retrieved but HashMap object url_maps size is zero.I want to use for loop in url_maps.
HashMap<String,String> url_maps = new HashMap<String, String>();
// Creating volley request obj for Banner
JsonArrayRequest bannerReq = new JsonArrayRequest(bannerUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(msg, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
url_maps.put("static key", "static value );
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(msg, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bannerReq);
maybe you can change:
url_maps.put("static key", "static value );
to:
url_maps.put(obj.getString("static key"),obj.getString("static value"));
Try this.
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : "+jObject);
System.out.println("map : "+map);
}
I have a big problem with volley request sequence and making json array out of first request response for second request.
this is the code :
JSONObject imageAddedResponse = new JSONObject();
JSONArray imagesAddedResponse = new JSONArray();
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
first request post to CMS and get some information for images posted and then I need to add those information to next post to make entity based on response I got back from first post request.
int totalSuccesfulImagePost = 0; //this variable increment when each succesful response from multipart-request
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages.getJSONObject(0));
totalSuccesfulImagePost++; //here we increase the count
postRequest(token); //call this method and check wheather all the image uploaded or not
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
}
//make this as seperate method and call when all multipart-request call succesful
public void postRequest(String token){
if(totalSuccesfulImagePost != mImages.size()) {
//this means not all the images posted yet, hence return the method
return;
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();.getJSONObject(0)
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
updated your code. Hope this may help you.
I've created new method for JsonObjectRequest with the name postRequest();
totalSuccesfulImagePost variable holds the no. of succesfull response for image upload
new method postRequest() calls at each multipart-request response
postRequest() methods check if not all response process yet than skip the 2nd api call
Also see how fb do this batch request https://developers.facebook.com/docs/android/graph/ -> Batch Reqest
Note -
Ive increment the variable totalSuccesfulImagePost and handle in each response, although you need to Response.ErrorListener()
Although you can go with the ThreadPoolExecutor option where each thread is created to handle each multipart-request upload and after all thread execution , call the method postRequest()
Work-around using ThreadPoolExecutor
a) Create ThreadPoolExecutor & initialize min/max pool size
b) Asign each mulitpart-request to upload image to each thread
c) Add all thread (contain image upload multipart-request) to ThreadPoolExecutor
d) Execute pool
e) call postRequest() method when ThreadPoolExecutor is empty i.e. this means all the thread execution is done and ready to call postRequest()
it is possible using Priority Of each Request.
private Priority priority = Priority.HIGH;
StringRequest strReq = new StringRequest(Method.GET,
Const.URL_STRING_REQ, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
#Override
public Priority getPriority() {
return priority;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);