This is my Java code:
public void imageUpload(final Context context, final String imagePath) {
final String requestBody;
JSONObject jsonUser = null;
JSONObject jsonAddress = null;
JSONObject jsonDriver = null;
JSONObject jsonImage = null;
String URL = SIGN_UP;
final String ConvertImage;
jsonUser = new JSONObject();
try {
jsonUser.put("first_name", "ABC");
jsonUser.put("last_name", "XYZ");
jsonUser.put("email", "yash#gmail.com");
jsonUser.put("phone", "9999900000");
jsonUser.put("password", "Yash#123");
jsonAddress = new JSONObject();
jsonAddress.put("address", "MUMBAI");
jsonAddress.put("city", "MUMBAI");
jsonAddress.put("state", "MH");
jsonAddress.put("zip", "369852");
jsonDriver = new JSONObject();
jsonDriver.put("middle_name", "GG");
jsonDriver.put("vehicle_type", "CAR");
jsonDriver.put("car_plate_number", "123456");
jsonDriver.put("car_brand", "BMW");
jsonDriver.put("making_year", "2011");
jsonDriver.put("date_of_birth", "2019-06-01");
jsonDriver.put("license_number", "12346579");
jsonDriver.put("license_state", "MH");
jsonDriver.put("social_security_number", "123456");
JSONObject jsonObjectFinal = new JSONObject();
jsonObjectFinal.put("user", jsonUser);
jsonObjectFinal.put("address", jsonAddress);
jsonObjectFinal.put("driver", jsonDriver);
} catch (JSONException e) {
e.printStackTrace();
}
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
/*params.put("user", jsonUser + "");
params.put("address", jsonAddress + "");
params.put("driver", jsonDriver + "");
Log.d("Param", "" + params + "***");*/
return params;
}
};
smr.addFile("license_image", imagePath);
smr.addMultipartParam("user", "text/plain", jsonUser + "");
smr.addMultipartParam("address", "text/plain", jsonAddress + "");
smr.addMultipartParam("driver", "text/plain", jsonDriver + "");
Log.d("Param", "" + smr.getMultipartParams() + "***");
MySingleton.getInstance(context).addToRequestQueue(smr);
}
The server shows:
data:->
[Object: null prototype] {
address:
'{"address":"SURAT","city":"SURAT","state":"GUJARAT","zip":"369852"}',
driver:
'{"middle_name":"GG","vehicle_type":"CAR","car_plate_number":"123456","car_brand":"BMW","making_year":"2011","date_of_birth":"2019-06-01","license_number":"12346579","license_state":"MH","social_security_number":"123456"}',
user:
'{"first_name":"YASH","last_name":"PANCHAL","email":"yash#gmail.com","phone":"8460277210","password":"Yash#123"}' }
files:-> [ { fieldname: 'license_image',
originalname: '1559197608373.jpg',
encoding: 'binary',
mimetype: 'application/octet-stream',
destination: 'C:\\Users\\Admin\\AppData\\Local\\Temp',
filename: 'license_image-m6i0vcx0-1559197611770.octet-stream',
path:
'C:\\Users\\Admin\\AppData\\Local\\Temp\\license_image-m6i0vcx0-1559197611770.octet-stream',
size: 53156 } ]
The files are sent perfectly but the JSON object is parsed as String, I want to send data like:
{
user:{
'first_name': 'yash',
'last_name': 'panchal'
},
address:{
...
},
driver:{
...
},
licence_image: [file]
}
In Android I have to pass request in JSON object or array including files.
If I try to parse the image via bitmap, the server returns undefined and if I try with pas as String it's working fine but when passing JSON data as above it results in sending object data as a single String.
Have a look at this multipart request with parameter's to a particular server and parsing its response as json :
private void saveProfileAccount() {
// loading or check internet connection or something...
// ... then
String url = "http://www.angga-ari.com/api/something/awesome";
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject result = new JSONObject(resultResponse);
String status = result.getString("status");
String message = result.getString("message");
if (status.equals(Constant.REQUEST_SUCCESS)) {
// tell everybody you have succed upload image and post strings
Log.i("Messsage", message);
} else {
Log.i("Unexpected", message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("api_token", "gh659gjhvdyudo973823tt9gvjf7i6ric75r76");
params.put("name", mNameInput.getText().toString());
params.put("location", mLocationInput.getText().toString());
params.put("about", mAvatarInput.getText().toString());
params.put("contact", mContactInput.getText().toString());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg"));
params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
Related
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);
}
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();
}
}
String url_save = "http://13.210.238.81:8080/freelance-api/gig/addGig";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject obj=new JSONObject();
try {
obj.put("categoryId",categoryId);
obj.put("gigDescription",edt_describeProject.getText().toString());
obj.put("revision",edt_revision.getText().toString());
obj.put("gigRate",edt_rate.getText().toString());
obj.put("expectedDuration",expected_delivery.getSelectedItem().toString());
obj.put("gigTitle",edt_uniqueTitle.getText().toString());
obj.put("subCategoryId",sub_Category);
JSONArray array=new JSONArray();
JSONObject objp=new JSONObject();
objp.put("skillId",id);
objp.put("skillTitle",edt_skills.getQuery().toString());
array.put(objp);
obj.put("gigSkills",array);
} catch (JSONException e) {
e.printStackTrace();
}
final String requestBody = obj.toString();
Toast.makeText(getApplicationContext(), "params-"+obj, Toast.LENGTH_LONG).show();
Log.d("params", ""+obj);
/*final Map<String, String> params = new HashMap<String, String>();
params.put("categoryId", categoryId);
params.put("gigDescription",edt_describeProject.getText().toString());
params.put("skillTitle",edt_skills.getQuery().toString());
params.put("skillId",id);
params.put("gigTitle",edt_uniqueTitle.getText().toString());
params.put("subCategoryId",sub_Category);
params.put("expectedDuration",expected_delivery.getSelectedItem().toString());
params.put("revision",edt_revision.getText().toString());
params.put("gigRate",edt_rate.getText().toString());
Toast.makeText(getApplicationContext(), "params-"+params, Toast.LENGTH_LONG).show();
Log.d("params", ""+params);*/
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url_save,new JSONObject(requestBody), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(),
"response-"+response, Toast.LENGTH_LONG).show();
Log.d("response",""+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
"error"+error.toString(), Toast.LENGTH_LONG).show();
Log.d("VolleyError","Volley"+error);
VolleyLog.d("JSONPost", "Error: " + error.getMessage());
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
Log.e("Status code", String.valueOf(networkResponse.data));
}
/*if (error.networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
Toast.makeText(getApplicationContext(),
"Failed to save. Please try again.", Toast.LENGTH_LONG).show();
}
}*/
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "applications/json");
headers.put("Authorization", "Bearer"+" "+sharedPreferenceConfig.ReadToken(getString(R.string.token_preference)));
return headers;
}
/*#Override
public byte[] getBody() {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}*/
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
requestQueue.add(jsonObjectRequest);
Json data is looks like below want to send data to the server Using JsonObjectRequest .
{
"categoryId":"3",
"gigDescription":"test",
"revision":"3",
"gigRate":"20",
"expectedDuration":"10",
"gigTitle":"test",
"subCategoryId":"10",
"gigSkills":
[
{
"skillId":"1",
"skillTitle":"Javaaa"
}
]
}
You can check status code of volly error like this. It will tell why you are getting com.android.volley.ClientError.
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 401:
//Session expired or token expired
break;
case 400:
break;
}
}
public void userLogin() {
try {
String URL = "http://influence360.in/orezmiapp/index.php/mobile/login";
System.out.println("Arun URL :- " + URL);
final JSONObject jsonBody = new JSONObject();
jsonBody.put("type", "2");
jsonBody.put("email", email);
jsonBody.put("password", password);
final String mRequestBody = jsonBody.toString();
Log.e("JSON String is :- ", " " + mRequestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("LOG_VOLLEY", response);
try {
Toast.makeText(activity, "loginactivity entered", Toast.LENGTH_LONG).show();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
Toast.makeText(activity, status, Toast.LENGTH_LONG).show();
if (status == 1000) {
JSONObject data = jsonBody.getJSONObject("data");
//sessionManager.setUserid(data.getString("Cust_id"));
// sessionManager.setBirthday(data.getString("Dob"));
sessionManager.setUserfirstname(data.getString("Cust_Name"));
startActivity(new Intent(LoginScreen.this, Profile.class));
finish();
} else {
Toast.makeText(activity, "Hello", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(activity, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#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);
Log.e("Response String : -", " " + responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
RequestQueue requestQueue = Volley.newRequestQueue(activity);
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new
DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
I got the error
value of type 200 org.json.Integer cant be converted into JSONObject. Please help me to solve this. I didnt get any solution regarding this. Thankyou in advance.Please help me out.I will be highly obliged if anybody give the solution.Thank you in advance. If anybody has the solution please give me that.
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);