onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
bitmapFrontIC = (Bitmap) data.getExtras().get("data");
frontICImageView.setImageBitmap(bitmapFrontIC);
}else if(requestCode == REQUEST_CAPTURE_BACKIC && resultCode == RESULT_OK){
bitmapBackIC = (Bitmap) data.getExtras().get("data");
backICImageView.setImageBitmap(bitmapBackIC);
}
}
submitbuttonOnClick:
public void submitOnClick(View view){
Log.d("Submit clicked", "Submit Clicked");
if(icNumber.getText().toString().length() > 0 && bitmapFrontIC != null && bitmapBackIC != null){
uploadBitmap(bitmapFrontIC,bitmapBackIC);
}else{
Toast.makeText(getApplicationContext(), "Please fill up all the fields", Toast.LENGTH_SHORT).show();
}
}
GetFileDataFromDrawable:
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
uploadBitMap:
private void uploadBitmap(final Bitmap bitmapFrontIC, final Bitmap bitmapBackIC) {
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.API_URL + "/users/upload-ic",
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
loading.dismiss();
try {
JSONObject obj = new JSONObject(new String(response.data));
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
String errorResponse = new String(networkResponse.data);
try {
JSONObject errorObject = new JSONObject(errorResponse);
if(errorObject.has("error")){
Toast.makeText(ICVerificationActivity.this, errorObject.getString("message"),
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Print Error!
Log.d("JSON ERROR", errorResponse);
}
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("icno", icNumber.getText().toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "multipart/form-data");
headers.put("Authorization", "Bearer " + "abcd");
return headers;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imageName = System.currentTimeMillis();
params.put("icFront", new DataPart("FrontIC_" + imageName + ".png", getFileDataFromDrawable(bitmapFrontIC)));
params.put("icBack", new DataPart("BackIC_"+imageName + ".png", getFileDataFromDrawable(bitmapBackIC)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
loading.show();
}
I am trying to call the POST request by inputting three items to the body:
a) text
b) camera_image1
c) camera_image2
I am able to display the captured image from camera in the imageview which means the bitmap is working. However, when I want to upload to the server, the server returns that the images are empty. Am I doing it wrongly?
Related
I have written the code for capturing the image from the camera and send to the server. But sometimes it works sometimes its not with the error volley timeout error. And almost all the cases when I am using JIO network which used IPv6 IP( I don't know what is affecting this) its not working.
I am capturing the image and convert into base64 and sending to the POST to the PHP server.
To start the camera :
btn_cam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
captureImage();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_REQUEST_CODE);
} catch (Exception e){
e.printStackTrace();
}
}
});
After capturing the image :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}
Then sending the encoded string to the APACHE server :
btn_submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
_house_no = house_number.getText().toString();
_state = state.getText().toString();
_streetName = locality.getText().toString();
_city = city.getText().toString();
_postalCode = postcode.getText().toString();
_state = state.getText().toString();
_district = district.getText().toString();
_tahsil = "0";
final ProgressDialog loading = ProgressDialog.show(MainActivity.this, "", "Please wait...", false, false);
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = ServerLinks.SUBMIT;
JSONObject jObj = new JSONObject();
jObj.put("userID",userID);
jObj.put("house",_house_no);
jObj.put("street",_streetName);
jObj.put("city",_city);
jObj.put("post_code",_postalCode);
jObj.put("state",_state);
jObj.put("district",_district);
jObj.put("lat",lat);
jObj.put("long",longi);
jObj.put("image",encoded);
final String requestBody = jObj.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("FINAL_SUBMIT_RESPONSE", response.toString());
loading.dismiss();
try {
JSONObject object = new JSONObject(response);
int response_code = object.getInt("code");
String message = object.getString("Message");
if (response_code == 400) {
Snackbar.make(rootLinearLayout, message, Snackbar.LENGTH_SHORT).show();
house_number.setText("");
} else {
Snackbar.make(rootLinearLayout, message, Snackbar.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
VolleyLog.d("RESULT_ERROR", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Something Went Wrong!! Please submit it again", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
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 Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("x-api-key", OAuth);
return params;
}
};
stringRequest.setShouldCache(false);
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}`
Can you please help me how should I increase the efficiency of my form with the image. Thank You in advance
Inside my code I have done this like that :
HttpClient httpclient;
httpclient = HttpClientSingalTon.getHttpClienttest();
HttpPost httpPostRequest = new HttpPost(URL);
// Try This
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(yourimagefile, "image/jpeg");
mpEntity.addPart("file", cbFile);
httpPostRequest.setEntity(mpEntity);
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
FileUpload fileUpload = new FileUpload(getApplicationContext());
filePath = fileUpload.getPath(picUri);
image_preview1.setImageURI(picUri);
}
}
}
can anyone help me to upload multiple images using volley android
Create RestApiMultiPartRequests.class
private class RestApiMultiPartRequests<T> extends Request<T> {
private final Map<String, String> mStringParts;
private final Map<String, File> mFileParts;
private MultipartEntityBuilder mBuilder;
private final Response.Listener<T> mListener;
public RestApiMultiPartRequests(String url,
Map<String, String> stringParts,
Map<String, File> fileParts,
Response.Listener<T> listener,
Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener = listener;
mStringParts = stringParts;
mFileParts = fileParts;
buildMultipartEntity();
}
private void buildMultipartEntity() {
if (mBuilder != null) {
mBuilder = null;
}
mBuilder = MultipartEntityBuilder.create();
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setBoundary("_____" + Long.toString(System.currentTimeMillis()) + "_____");
mBuilder.setCharset(Consts.UTF_8);
if (mStringParts != null) {
for (Map.Entry<String, String> entry : mStringParts.entrySet()) {
mBuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", Charset.forName("UTF-8")));
}
}
Log.e("Size", "Size: " + mFileParts.size());
for (Map.Entry<String, File> entry : mFileParts.entrySet()) {
ContentType imageContentType = ContentType.create("image/*");//MULTIPART_FORM_DATA;
Log.d("", "Key " + entry.getKey());
Log.d("", "Value " + entry.getValue());
Log.d("", "Name " + entry.getValue().getName());
//"userfile"
mBuilder.addBinaryBody(entry.getKey(), entry.getValue(), imageContentType, entry.getValue().getName());
}
}
#Override
public String getBodyContentType() {
return mBuilder.build().getContentType().getValue();
}
#Override
public byte[] getBody() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
e.printStackTrace();
}
return bos.toByteArray();
}
public HttpEntity getEntity() {
return mBuilder.build();
}
#SuppressWarnings("unchecked")
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return (Response<T>) Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
and upload image using this method
/**
* Upload image
*/
private void UploadImage() {
RestApiMultiPartRequests<String> restApiMultiPartRequest =
new RestApiMultiPartRequests<String>(url, hashMap, fileparts, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(LOG_TAG, "URL " + url + "\n Response : " + response);
if (iRestApiListener != null) {
setparsing(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No
// connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user
// credentials.
// For ClientError, 400 & 401, Errors happening on
// client side when sending api request.
// In this case you can check how client is forming the
// api and debug accordingly.
// For ServerError 5xx, you can do retry or handle
// accordingly.
int errorCode;
if (error instanceof NetworkError) {
errorCode = NETWORK_ERROR;
Log.i(LOG_TAG, "NetworkError" + error);
} else if (error instanceof ServerError) {
errorCode = SERVER_ERROR;
Log.i(LOG_TAG, "ServerError" + error);
} else if (error instanceof AuthFailureError) {
errorCode = AUTH_FAILURE_ERROR;
Log.i(LOG_TAG, "AuthFailureError" + error);
} else if (error instanceof ParseError) {
errorCode = PARSE_ERROR;
Log.i(LOG_TAG, "ParseError" + error);
} else if (error instanceof NoConnectionError) {
errorCode = NO_CONNECTION_ERROR;
Log.i(LOG_TAG, "NoConnectionError" + error);
} else if (error instanceof TimeoutError) {
errorCode = TIME_OUT_ERROR;
Log.i(LOG_TAG, "TimeoutError" + error);
} else {
errorCode = UNKNOWN_ERROR;
Log.i(LOG_TAG, "TimeoutError" + error);
}
//Log.i(LOG_TAG,"StatusCode" + error.networkResponse.statusCode);
if (iRestApiListener != null) {
iRestApiListener.onCallFinish();
try {
iRestApiListener.onError(new JSONArray());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
if (StringUtils.isNotEmpty(AppClass.preferences.getValueFromPreferance(Preferences.TOKEN))) {
params.put("Authorization", AppClass.preferences.getValueFromPreferance(Preferences.TOKEN));
}
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
restApiMultiPartRequest.setRetryPolicy(new DefaultRetryPolicy(0, 1, 2));//10000
AppClass.mVolleyInstance.addToRequestQueue(restApiMultiPartRequest);
}
here fileparts is HashMap<String,File> so you can create hash map like this and add multiple file in to it and this single request can upload your multiple image file to server
I'm facing a issue in uploading image more than 2 MB.
Kindly please help me with this problem. This error
java.net.SocketException:Broken pipe
Displayed in a Toast.
This is code for getting image in Base64 format and uploading on server.
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte [] b=baos.toByteArray();
String encodedImage= null;
try{
System.gc();
encodedImage= Base64.encodeToString(b, Base64.DEFAULT);
}catch(Exception e){
e.printStackTrace();
}catch(OutOfMemoryError e){
baos=new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG,50, baos);
b=baos.toByteArray();
encodedImage=Base64.encodeToString(b, Base64.DEFAULT);
Log.e("EWN", "Out of memory error catched");
}
return encodedImage;
}
private void uploadImage(){
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(getActivity(), "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.UPLOADIMAGE_URL+"/user",
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
System.out.println("Response :" + s);
JSONObject jsonObject = new JSONObject(s);
Preferences.setUserImageUrl(getActivity(), jsonObject.getString("image_name"));
// MainActivity mains = new MainActivity();
// Picasso.with(mains).load(finalImageUrl).placeholder(R.drawable.profile_image).into(mains.profile_image);
// mains.updateimage(jsonObject.getString("image_name"));
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getActivity(), s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
if (volleyError.getMessage()==null){
Toast.makeText(getActivity(), "Image not uploaded Please check your internet ", Toast.LENGTH_SHORT).show();
}else {
//Showing toast
Toast.makeText(getActivity(), volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("image", image);
System.out.println("image : " + image);
params.put("id", Preferences.getUserId(getActivity()));
System.out.println("ID : "+Preferences.getUserId(getActivity()));
return checkParams(params);
}
//returning parameters
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(stringRequest);
//AppController.getInstance().addToRequestQueue(stringRequest);
}
private Map<String, String> checkParams(Map<String, String> map) {
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
if (pairs.getValue() == null) {
map.put(pairs.getKey(), "image");
map.put(pairs.getKey(), "id");
}
}
return map;
}
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
//Setting the Bitmap to ImageView
userImage.setImageBitmap(bitmap);
uploadImage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It's my code..
I'm trying to send a base64 encoded string to a server over volley but its not sending properly. When i use httpbin this is the response
"args": {},
I/System.out: "data": "",
I/System.out: "files": {},
I/System.out: "form": { "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmN...(image base64)
I/System.out: },
where the image data is in the form. However i need it in data.
public static String rawOutput = "dadsdas";
private Button buttonChoose;
private Button buttonUpload;
public String image;
private ImageView imageView;
private Button postText;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="https://httpbin.org/post";
private String KEY_IMAGE = "Content-Type";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_image);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
postText = (Button) findViewById(R.id.postText);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
System.out.println(imageBytes);
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() throws JSONException {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
// JSONObject jsonBody = new JSONObject();
// jsonBody.put(getStringImage(bitmap), "");
//final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
System.out.println(s);
Toast.makeText(PostImage.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
String json = null;
NetworkResponse response = volleyError.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode){
case 400:
json = new String(response.data);
if(json != null) System.out.println(json);
System.out.println(json.getClass().getSimpleName());
break;
}
//Additional cases
}
Toast.makeText(PostImage.this, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}){
// #Override
// public String getBodyContentType() {
// return "text/plain; charset=utf-8";
// }
// #Override
// public byte[] getBody() {
// byte[] body = new byte[0];
// try {
// body = ("/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVz.......(image data here)");
//
//} catch (UnsupportedEncodingException exception) {
// Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
//return null;
//}
return httpPostBody.getBytes();
}
// #Override
// public String getBody() throws AuthFailureError {
// image = getStringImage(bitmap);
// System.out.printf(image);
// String params= "";
// params= image;
// return params;
//
// }
// #Override
// protected Map<String, String> getParams() throws AuthFailureError {
// image = getStringImage(bitmap);
// System.out.printf(image);
// Map<String,String> params = new Hashtable<String, String>();
// params.put("", image);
// return params;
// }
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
System.out.println(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
}
if(v == buttonUpload){
try {
uploadImage();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void postText(View v) {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://api.getquesto.com:8080/upload";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Text:", "A leaf is an organ of a vascular plant and is the principal lateral appendage of the stem.[1] The leaves and stem together form the shoot.[2] Leaves are collectively referred to as foliage, as in \"autumn foliage.\"[3][4]\n" +
"\n" +
"\n" +
"Diagram of a simple leaf.\n" +
"Apex Midvein (Primary vein) Secondary vein. Lamina. Leaf margin Petiole Bud Stem\n" +
"Although leaves can be seen in many different textures and sizes, typically a leaf is a thin, dorsiventrally flattened organ, borne above ground and specialized for photosynthesis. In most leaves, the primary photosynthetic tissue, the (palisade mesophyll), is located on the upper side of the blade or lamina of the leaf[1] but in some species, including the mature foliage of Eucalyptus,[5] palisade mesophyll is present on both sides and the leaves are said to be isobilateral. Most leaves have distinctive upper (adaxial) and lower (abaxial) surfaces that differ in colour, hairiness, the number of stomata (pores that intake and output gases), epicuticular wax amount and structure and other features.\n" +
"\n" +
"Broad, flat leaves with complex venation are known as megaphylls and the species that bear them, the majority, as broad-leaved or megaphyllous plants. In others, such as the clubmosses, with different evolutionary origins, the leaves are simple, with only a single vein and are known as microphylls.[6]\n" +
"\n" +
"Some leaves, such as bulb scales are not above ground, and in many aquatic species the leaves are submerged in water. Succulent plants often have thick juicy leaves, but some leaves are without major photosynthetic function and may be dead at maturity, as in some cataphylls, and spines). Furthermore, several kinds of leaf-like structures found in vascular plants are not totally homologous with them. Examples include flattened plant stems called phylloclades and cladodes, and flattened leaf stems called phyllodes which differ from leaves both in their structure and origin.[4][7] Many structures of non-vascular plants, such as the phyllids of mosses and liverworts and even of some foliose lichens, which are not plants at all (in the sense of being members of the kingdom Plantae), look and function much like leaves.");
final String mRequestBody = jsonBody.toString();
String json = null;
StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
Toast.makeText(PostImage.this, response , Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#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
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type","text/plain");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
does anyone know how to make it send through data?
I am trying to update a profile with an image and other details using Volley.
I have to convert the image file and send it to the url as parameter.
I also have to parse all the other details to update the profile.
How can I update the profile image?
url = "http://192.168.1.30:1021/mobileapi/profile_update.html?&user_id="+user+"&firstname="+First.getText().toString()+
"&lastname="+last.getText().toString()+"&secondaryemail="+sEmail.getText().toString()+
"&phonemobile="+mob.getText().toString()+"&aboutus="+work.getText().toString()+"&phonework="+phone.getText().toString()+
"&skypeid="+skypeid.getText().toString()+"&gender="+gender+"&smtp_password="+mpass.getText().toString()+"&image="+fos;
url=url.trim().replaceAll("\\s+","");
System.out.println("url" + url);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
pDialog.dismiss();
queue = Volley.newRequestQueue(getActivity());
request = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
System.out.println("updaa" + response.toString());
JSONObject update = response.getJSONObject(0);
int httpcode = Integer.parseInt(update.getString("status"));
if (httpcode == 200) {
String mess = update.getString("message");
Toast.makeText(getActivity(), mess, Toast.LENGTH_LONG).show();
int userid = Integer.parseInt(update.getString("user_id"));
String fname = update.getString("firstname");
String lname = update.getString("lastname");
String mail = update.getString("email");
String smail=update.getString("secondary_email");
/* String ph= String.valueOf(Integer.parseInt(update.getString("phone_work")));
String phone= String.valueOf(Integer.parseInt(update.getString("phone_mobile")));*/
String skype_id = update.getString("skype_id");
String user_title = update.getString("user_title");
String imgUrl = update.getString("image");
editor.putString("name", fname);
editor.putString("userid", String.valueOf(userid));
editor.putString("lname",lname);
editor.putString("mail",mail);
editor.putString("skype",skype_id);
editor.putString("image",imgUrl);
// editor.putString("phone", String.valueOf(ph));
editor.putString("work",user_title);
editor.putString("smail",smail);
// editor.putString("phone", String.valueOf(phone));
editor.commit();
} else {
JSONObject typ = response.getJSONObject(0);
String message = typ.getString("message");
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("result" + error.getLocalizedMessage()+"__"+error.getMessage());
Log.e("Volley", "Error");
}
}){
};
queue.add(request);
}
}
});
return view;
}
private void opengallery() {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == PICK_IMAGE_REQUEST && intent != null && intent.getData() != null) {
Uri uri = intent.getData();
try {
/*Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));*/
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
Log.d("TAG", String.valueOf(bitmap));
Bpro.setImageBitmap(bitmap);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(uri + ".png");
file = new File(extStorageDirectory, uri + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + uri);
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fos);
/* fos = new FileOutputStream(f);
fos.write(bitmapdata);*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSON response
[{
"smtp_password":"abdul",
"status":"200",
"user_type":"2",
"skype_id":"skype",
"emp_id":"N0418",
"phone_work":"9864545454",
"image":"http:\/\/192.168.1.30:1021\/uploads\/Nandha\/profile_image\/180_200\/45571.png",
"lastname":"Rahman",
"firstname":"Abdul",
"user_title":"android",
"message":"Profile has been updated successfully",
"email":"4dZR9RLF#gmail.com",
"gender":"1",
"user_id":"45571",
"secondary_email":"abdul#gmail.com",
"phone_mobile":"9892545454"
}]
use this code ..it works for me .Its sends multipart images.
private void saveProfileDetails() {
// loading or check internet connection or something...
// ... then
String url = "http://51.76.27.90:8080/post/new/";
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
System.out.println("statuscode is " + response.statusCode);
}
}, 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("username", "a#a.com");
params.put("category", "product");
params.put("type", "product");
params.put("title", "i am done ");
params.put("content", "contentssssssssssssssssssssssss");
params.put("location", "Bangalore");
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("imageC", new DataPart("file_avatar.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), colorImage.getDrawable()), "image/jpeg"));
params.put("imageBW", new DataPart("file_cover.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), blackAndWhiteImage.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
and this is your VollySingleton function
/**
* Created by snehasish on 29/7/16.
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
/**
* Singleton volley to populate request into single queue.
*/
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
/**
* Private constructor, only initialization from getInstance.
*
* #param context parent context
*/
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruBitmapCache(mCtx);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
/**
* Singleton construct design pattern.
*
* #param context parent context
* #return single instance of VolleySingleton
*/
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
/**
* Get current request queue.
*
* #return RequestQueue
*/
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
/**
* Add new request depend on type like string, json object, json array request.
*
* #param req new request
* #param <T> request type
*/
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
/**
* Get image loader.
*
* #return ImageLoader
*/
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
if it helps pls make this answer as right!