Setting cookies in Volley does not work - android

This is the code i use:
if (toEditText.getText().toString().length() > 0) {
getName = toEditText.getText().toString().substring(0, toEditText.getText().toString().length() - 1) + "";
StringBuffer sb = new StringBuffer();
sb.append(Constants.SERVER_IP);
sb.append("/api/groups.json");
String url = sb.toString();
LogService.log(TAG, "download url: " + url);
JSONObject juser = new JSONObject();
JSONArray userIds = new JSONArray();
for (int i = 0; i < user_ids.size(); i++) {
userIds.put(user_ids.get(i));
}
try {
juser.put("group_name", getName);
juser.put("owner_id", UserCredentialsPersistence.getUserId(context));
juser.put("user_ids", userIds);
juser.put("group_type", null);
juser.put("name_protected", true);
LogService.log(TAG, "JSON: " + juser.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, juser, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "%%%%%Response:" + response.toString());
int group_id = 0;
group_name = "";
if (response != null) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject userObj2 = (JSONObject) response.get("group");
group_id = userObj2.getInt("id");
group_name = userObj2.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
LogService.log(TAG, "id: " + group_id);
LogService.log(TAG, "name: " + group_name);
getName = "";
toEditText.setText("");
GroupAndConversationManager.getInstance(context).addNewConversation(group_id, group_name);
hideSearchFild();
int curr_group_id = UserCredentialsPersistence.getCurrentGroupId(context);
changeGroup(curr_group_id, group_id);
showGroupToast(group_name);
setVideoPlayback();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, error.getMessage());
}
}) {
#Override
public HashMap<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
StringBuilder builder = new StringBuilder();
builder.append(UserCredentialsPersistence.restoreCookie(context));
params.put("Cookie", builder.toString());
return params;
}
};
mRequestQueue.add(jr);
}
Now, Logcat gives me back this line:
07-12 11:21:53.702: I/VideoPlayerFragment(27428): java.io.IOException: No authentication challenges found
I have also tried to override getHeaders, instead of getParams(), but i get an error, so the webservice does not work correctly. This is from where I've got the ideea to override getParams/getHeaders: How to set custom header in Volley Request
Could anyone explain to me what I'm doing wrong?

using this override resolved it:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", UserCredentialsPersistence.restoreCookie(context).toString());
return headers;
}

Related

Using Log for Volley Post Method

I am using Post Method to send data to server and the data includes strings and images values images value are send through multipart now i am getting some error to reslove i want to post all my data in Log to see where the data is not able to send can any one help me out to use log for all the paremeters values include image string values in log
Post Method Sample
private void new_processing() {
String URL = "Url";
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
Log.d("response", new String(response.data));
rQueue.getCache().clear();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
if (action_taken == "Sample Taken " ||action_taken.equals("Sample Taken ")) {
JSONObject json2 = new JSONObject();
try {
json2.put("sampletype", product_type);
json2.put("samplecode", sample_code);
} catch (JSONException e) {
e.printStackTrace();
}
JsonArray sample_obj = new JsonArray();
sample_obj.add(String.valueOf(json2));
params.put("Raid_Sample", sample_obj.toString());
params.put("Raid_Action", null);
} else if (action_taken.equals("Sale Stoped") || action_taken.equals("Licence Cancelled") ||action_taken == ("Licence Cancelled") || action_taken.equals("Licence Suspended")) {
JSONObject json2 = new JSONObject();
try {
json2.put("actiontype", action_taken);
json2.put("actiondate", lic_date);
json2.put("letterno", lic_letter);
json2.put("copyno", lic_copy);
} catch (JSONException e) {
e.printStackTrace();
}
params.put("Raid_Action", String.valueOf(json2));
params.put("letterfile", image_letter);
Log.i("action_object", String.valueOf(json2));
}
params.put("AuthID", AuthId);
params.put("producttype", product_type);
/* params.put("raidother", raid_type_other);
params.put("violationother", voilation_other);*/
params.put("dateofraid", raid_date);
params.put("locationname", location_name);
params.put("locationaddress", location_address);
JSONArray array;
array = new JSONArray();
for (int i = 0; i < movieList1.size(); i++) {
JSONObject movieObject = new JSONObject();
try {
movieObject.put("name", movieList1.get(i).getName());
movieObject.put("designation", movieList1.get(i).getDesignation());
movieObject.put("postingplace", movieList1.get(i).getPostingplace());
array.put(movieObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
memberlist = String.valueOf(array);
Log.i("arraylist", memberlist.toString());
params.put("Raid_Team", memberlist);
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
params.put("picurl1", new DataPart(imagename + ".jpge", getFileDataFromDrawable(bitmap)));
return params;
}
};
volleyMultipartRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rQueue = Volley.newRequestQueue(ScrollingActivity.this);
rQueue.add(volleyMultipartRequest);
}

How to pass multiple information array and a image array to server?

I have an array which is contain image quantity for image and another is image size array which is contain image size, also an image array. I'm trying to send them to server but i failed every time. I'm trying many example but nothing was worked for me. Is there any other way to do this ? Please give me some hints or link.
how to send array of params using volley in android
public void uploadMultipleImage(String url, final List<SelectedImageModel> selectedImageModels)
{
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
responseListener.onResultSuccess(resultResponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String result = new String(networkResponse.data);
responseListener.onResultSuccess(result);
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>(selectedImageModels.size());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("size["+i+"]",selectedImageModels.get(i).getPhotoSize());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("quantity["+i+"]",selectedImageModels.get(i).getPhotoQuantity());
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer "+requiredInfo.getAccessToken());
headers.put("Accept", "application/json");
headers.put("Content-Type", "x-www-form-urlencoded");
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>(selectedImageModels.size());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("image["+i+"]",new DataPart("imageName",UserProfile.getFileDataFromDrawable(selectedImageModels.get(i).getPhoto())));
return params;
}
};
requestQueue.add(multipartRequest);
}
Every time i'm getting com.android.volley.server error 500 this error
Make a method for send array of params.
private String makeJsonObjectParams() {
//In mediaData,I am sending image to AWS and I will get the download link and I
// am storing the downloadurl in downloadurl arrayslist.
JSONArray mediaData = new JSONArray();
try {
if(img1 != 1) {
JSONObject temp = new JSONObject();
temp.put("file", download_url.get(0));
temp.put("type", "signature");
mediaData.put(temp);
}
if(img2 != 1){
JSONObject temp1 = new JSONObject();
temp1.put("file", download_url.get(1));
temp1.put("type", "id proof");
mediaData.put(temp1);
}
} catch (JSONException e) {
e.printStackTrace();
}
//for sending normal details like text
JSONObject updateDetails = new JSONObject();
try {
updateDetails.put("status", 2);
updateDetails.put("userId", sharedPreferences.getString("user_ID",""));
updateDetails.put("deviceToken", splash_screen.android_id);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonVerificationDetails = new JSONObject();
try {
jsonVerificationDetails.put("type", verificatin_type);
jsonVerificationDetails.put("durationOfStay", durationOfStay.getText().toString());
jsonVerificationDetails.put("media", mediaData);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("verificationDetails", jsonVerificationDetails);
jsonBody.put("updateDetails", updateDetails);
} catch (JSONException e) {
e.printStackTrace();
}
final String mRequestBody = jsonBody.toString();
return mRequestBody;
}
}
Through the below code send the code to server.
void submitData(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
final String mRequestBody = makeJsonObjectParams();
StringRequest stringRequest = new StringRequest(Request.Method.POST, completedTaskUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//do whatever you want
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
// return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
return super.parseNetworkResponse(response);
}
};
requestQueue=Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
} catch (Exception e) {//JSONException e
e.printStackTrace();
}
}

How to set object to VolleyRequest(POST Request) in this type of API?

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

How to send array in params in volley in android

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

need first volley request response to make json object for second request

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);

Categories

Resources