Updating Imageview after image upload to server in android - android

I am developing an app in which I am changing profile pic and send it server to store.But my problem is as soon as I after updating image and go back from the activity and come again to the same activity, the old image will be there replacing my new one which i have send to server.That is image saved in server in not getting in the ImageView.I am using Multipart Request to send image to server.If any one knows the solution please let me know that,I will be very gratefull.
private class SendGroupPicToServer extends AsyncTask<File, Integer, String> {
#Override
protected String doInBackground(File... params) {
System.out.println("inside do in background " + grp_id + " "
+ userid);
final File imagefile = params[0];
RequestQueue requestQueue = MySingleton.getInstance(
GroupProfile.this).getRequestQueue();
Map<String, String> arguments = new HashMap<String, String>();
arguments.put("group_id", grp_id);
arguments.put("user_id", userid);
MultipartRequest multipartRequest = new MultipartRequest(
updateGroupPicUrl, arguments,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response from Abey "
+ response);
try {
ResponseClass rDetails = (new Gson()).fromJson(
response, ResponseClass.class);
if (rDetails.Result.equals("Success")) {
profile.postInvalidate();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(GroupProfile.this, error.toString(),
Toast.LENGTH_SHORT).show();
System.out.println("Upload Image response is "
+ error.toString());
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
}
}
}, imagefile, "IMAGE");
requestQueue.add(multipartRequest);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println("Image updation is " + result);
}
}

Related

Device ID is not going to the heasers

Im working on Registration using volley liabray.I want to send Device ID in header but it going null here is my code snippit.
Log.d("TAG", "Details:" + response);
String strMessage = response.optString("message");
String strDevice = response.optString("deviceID");
CryptoHandler cryptoHandler = new CryptoHandler();
String decryptMessage = cryptoHandler.decrypt(strMessage);
String decryptDevice = cryptoHandler.decrypt(strDevice);
Log.d("TAG","Decrypted Response:"+decryptMessage +decryptDevice);
// responseTV.setText("String Response : " + response.toString());
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// responseTV.setText(error.getMessage());
// Toast.makeText(RegisterActivity.this, "Error"+error, Toast.LENGTH_LONG).show();
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
Toast.makeText(getApplicationContext(),
"Oops. Timeout error!",
Toast.LENGTH_LONG).show();
}
}
//This is for Headers If You Needed
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("DeviceId", ID);
return headers;
}
};
requestQueue.add(jsonObjectRequest);

Upload multiple images using Android Volley

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

Getting wrong response in volley

I am getting wrong response in volley while on the other hand postman getting correct response. Please help me where is the problem . Response i am getting from volley is "response= {"code":1020,"message":"Duplicate key not allowed","returnId":null}"
And in postman it is "{
"code": 1089,"message": "Activation Key sent in email, please activate your user/device","returnId": 438
}"
public void sendRegisterationReq("http://demo.innowi.com/v1/user/register",getJsonObject()) {
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, dataObj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(context, "" + response.toString(), Toast.LENGTH_SHORT).show();
System.out.println("response= " + response.toString());
System.out.println(TAG + ":" + dataObj.toString());
try {
if (response.getString("code").equals("1020")){
Intent intent = new Intent(RegisterDeviceActivity.this,ActivateDeviceActivity.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
String message = null;
if (volleyError instanceof NetworkError) {
message = "Network error!";
Log.d(TAG,message);
} else if (volleyError instanceof ServerError) {
message = "Server error!!";
Log.d(TAG,message);
} else if (volleyError instanceof AuthFailureError) {
message = "Auth failure error!";
Log.d(TAG,message);
} else if (volleyError instanceof ParseError) {
message = "Parsing error!";
Log.d(TAG,message);
} else if (volleyError instanceof NoConnectionError) {
message = "No connection error!";
Log.d(TAG,message);
} else if (volleyError instanceof TimeoutError) {
message = "timeout error !";
Log.d(TAG,message);
}
/*Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
System.out.println(TAG + ":Error: " + volleyError.getMessage());
System.out.println(TAG + ":" + volleyError.toString());*/
System.out.println(TAG + ":" + dataObj.toString());
}
}) {
/**
* Passing some request headers
* */
#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");
return headers;
}
};
jsonObjReq.setShouldCache(false);
jsonObjReq.setTag("myRequest");
// Adding request to request queue
queue.add(jsonObjReq);
}
public JSONObject getJsonObject(){
JSONObject object = new JSONObject();
try {
if (username!=null && password !=null) {
object.put("username", username.getText().toString());
object.put("password", password.getText().toString());
object.put("deviceMacAddress", "90:B6:86:0D:CE:4F");
}
else
{
Toast.makeText(this, "Email/password should not be empty", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
you are the data which is already exist in your database so says duplicate key try different one or try to send all fields valid and different.

google/volley App crashing when URL do not exist

So I've implemented google/volley in my apps. When i code the apps i accidentally mistyped the url address and the app just crash suddenly. So how can i avoid this kind of problem. Below are the code i've used.
String url_login = "http://10.0.2.2/test_sstem/public/login";
//Send Post data and retrieve server respond
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,"On Response "+response,Toast.LENGTH_LONG).show();
ValidateLogin(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
String jsonError = new String(networkResponse.data);
String message_response=null;
try {
JSONObject object = new JSONObject(jsonError);
message_response= object.getString("error");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(LoginActivity.this, "On Error " + message_response.toString(), Toast.LENGTH_LONG).show();
showProgress(false);
}
}
})
I know that it can be fixed by correcting the URL, but what if the URL are not alive and working how do we work around this problem.
I have used bellow method for volley which is work for me.. i have used wrong address but my app does not stop. Use bellow full method..
private void doLoginAction() {
pDialog.show();
String url_login = "http://10.0.2.2/test_sstem/public/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("ParentNode");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String key1 = jo.getString("key1");
String key2 = jo.getString("key2");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("uname", "era#gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
There can be number of reasons why your app crashes with incorrect url, one could be that the host is un resolvable, you can check the validity of a Url by using the following code:
URLUtil.isValidUrl(url)

JSONObject not response

How do I check if this text appears or not
{"cod":"404","message":"city not found"}
url : http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1
My try
public void btn_search(View view) {
CheckInternet checkInternet = new CheckInternet(MainActivity.this);
boolean ci = checkInternet.isconnecting();
if(ci)
{
EditText ed_Search = (EditText)findViewById(R.id.ed_Search);
if(ed_Search.getText().length() > 0)
{
String urlOpenWeatherMap = "http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1";
progressBar = (ProgressBar)findViewById(R.id.progressBar);
btn_search = (ImageView)findViewById(R.id.btn_search);
btn_search.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonobjectrequest = new JsonObjectRequest(Request.Method.GET, urlOpenWeatherMap, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String x = response.getString("message");
if(x.contains("404") || x.contains("city not found") )
{
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "welcome", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonobjectrequest);
}
else
{
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(MainActivity.this, "no Internet", Toast.LENGTH_SHORT).show();
}
}
I am trying to solve the problem 4 hours ago but no use
I think the problem here
String x = response.getString("message");
I need help please
You are getting json text in the response body, but the server is responding with 404 code which is an error, therefore the logic needs to be inside the overridden method:
#Override
public void onErrorResponse(VolleyError error) {
String body;
String statusCode = String.valueOf(error.networkResponse.statusCode);
if(statusCode == "400") {
// do your thing
}
// do something else
}
Json Might be look like
{"loginNodes":[{"message":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]}
Your code should be ..
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://api.openweathermap.org/data/2.5/weather",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("loginNodes");
pDialog.dismiss();
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String message= jo.getString("message");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
try {
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("q", "fddfgdfgdfgdfg");
params.put("units", "metric");
params.put("appid", "efb8013262db1b77b0431909b8b173e1");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Check response from GET OR Post.You can debug the error onErrorResponse
try {
if (error instanceof TimeoutError ) {
}else if(error instanceof NoConnectionError){
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
} catch (Exception e) {
}

Categories

Resources