I want to send base64 image string into Url using volley - java

I want to send base64 string of image to the server using volley library android studio. It works in postman and give me response perfecty as it is shown in this image as it is shown in this image
I try many times in the android studio but it always show me 500 code error and cant get the result any one help me.View postman response in image that i have attached with this post. I also attached my code with it.
This is image button click listener event :
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 22);
}
});
Now start activity for result code is here :
#Override
public void onActivityResult(int requestCode, final int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 22 && resultCode == RESULT_OK && data != null){
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContext().getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
profile_image.setImageBitmap(selectedImage);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded4 = Base64.encodeToString(byteArray, Base64.DEFAULT);
String encoded22 = "data:image/jpeg;base64,"+encoded4;
Toast.makeText(getContext(), encoded22, Toast.LENGTH_SHORT).show();
final ProgressDialog progress = new ProgressDialog(getContext());
progress.setTitle("Uploading Image");
progress.setMessage("Loading...");
progress.setCancelable(false);
progress.show();
RequestQueue queue = Volley.newRequestQueue(getContext());
final JSONObject jsonObject = new JSONObject();
jsonObject.put("base64image", encoded22);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, Utils.baseUrl +"/company/update-photo", jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progress.dismiss();
Toast.makeText(getContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progress.dismiss();
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Authorization", bear + idCheck);
return params;
}
};
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(
120000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonRequest);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), "Problem is here", Toast.LENGTH_SHORT).show();
}
}
}
But it always shows me this error
" BasicNetwork.performRequest: Unexpected response code 500 for URL "

Related

How to save an image using CircleImageView Android Studio

I wrote a program where a user can click a TextView (editPhoto) and select an image (profile picture) and display on the profile and also save it on my database with the rest of the profile details, but as soon as I leave the page the picture disappears from the CircleImageView although it's still saved on my database. I am able to save the rest of the users information on the profile like name, username, email etc using .setText() so how can I do the same with the CircleImageView for the profile picture? Thanks in advance
CODE:
private TextView editPhoto;
CircleImageView profilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
profilePic = findViewById(R.id.profilepic);
editPhoto = findViewById(R.id.txtEditPP);
editPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseFile();
}
});
}
private void chooseFile(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose Photo"),1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri filepath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filepath);
profilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
UploadPicture(getId, getStringImage(bitmap));
}
}
//UPLOAD PROFILE PICTURE
private void UploadPicture(final String id, final String photo) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPLOAD, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
Toast.makeText(EditProfile.this, "Photo Uploaded", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(EditProfile.this, "Error Uploading Image!", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EditProfile.this, "Error Uploading Image!", Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("ID", id);
params.put("photo", photo);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArr = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArr, Base64.DEFAULT);
return encodedImage;
}
In onResume can you reload imageView using bitmap object?
Also make bitmap object as class variable reloading image will work for you in this case.

how i can send and verify parameters from server using volley?

I try to send some parameters to the server to verify. but it doesn't include parameters in URL, I also debug and check the value of my URL but parameters are not there. so how I can do it,
the full URL is look like this "http://38.143.223.234/~wajih/foodaway/api/userlogin.php?email=a%40&device_type=Android&password=123456&device_id=af44077c-e8ec-4b0b-aadb-e322997af8de"
if I just include all values that I am sending to the server in url then it works well. but I want to send it through parameters method
public void login(){
String url = "http://38.143.223.234/~wajih/foodaway/api/userlogin.php?";
StringRequest stringRequest = new StringRequest( Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
Log.d( "response", response );
try {
//Boolean error =jsonObject.getBoolean("error");
//values[0] = values[0].replace("[", "").replace("]", "");
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("1"))
{
//activity.initializeOneSignal();
String user_response = jsonObject.getJSONObject("user_detail").toString();
manager.setLoginDetails(user_response);
OneSignal.setSubscription(true);
dialog.dismiss();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else if (jsonObject.getString("status").equals("0"))
{
dialog.dismiss();
Toast.makeText(LoginActivity.this,
jsonObject.getString("error"), Toast.LENGTH_LONG).show();
}
else {
// Error didn't get any response from server
dialog.dismiss();
Toast.makeText(LoginActivity.this, "Something went wrong!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
getWindow().clearFlags( WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE );
if (networkResponse != null) {
Log.e( "Status code", String.valueOf( networkResponse.statusCode ) );
Toast.makeText( LoginActivity.this, String.valueOf( networkResponse.statusCode ),
Toast.LENGTH_LONG ).show();
} else {
Toast.makeText( LoginActivity.this, error.toString(),
Toast.LENGTH_LONG ).show();
}
}
}){
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<>();
MyData.put("email", userEmail);
MyData.put("device_type","Android");
MyData.put("password", userPassword);
MyData.put("device_id",deviceId);
return MyData;
}
};
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy( socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT );
stringRequest.setRetryPolicy( policy );
AppController.getInstance().addToRequestQueue( stringRequest);
}

OutOfMemoryError Bitmap to Base64 string

I have an error in Android, can someone help me?
my Activity code :
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
Connect.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},CODE_GALLERY_REQUEST
);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode==CODE_GALLERY_REQUEST){
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select Image"),CODE_GALLERY_REQUEST);
}else {
Toast.makeText(this," Pour créer une photo de profil merci de nous donner la permission",Toast.LENGTH_SHORT);
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==CODE_GALLERY_REQUEST&&resultCode==RESULT_OK&&data!=null){
Uri filePath=data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filePath);
bitmap = BitmapFactory.decodeStream(inputStream);
imagedata = imageToString(bitmap);
profileImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void updateLabel() {
String myFormat = "yyyy-MM-dd"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
naissance.setText(sdf.format(myCalendar.getTime()));
}
public void inscription(View view){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Chargement...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_inscription,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
if(response.equals("SUCCES")){
// Intent intent = new Intent(getApplicationContext(),Connexion.class);
// startActivity(intent);
}else {
Toast.makeText(Connect.this, response, Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"verifier votre connexion internet et réessayer",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("image",imagedata);
params.put("pseudo",pseudo.getText().toString());
params.put("nom",nom.getText().toString());
params.put("prenom",prenom.getText().toString());
params.put("password",password.getText().toString());
params.put("email",email.getText().toString());
params.put("naissance",naissance.getText().toString());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private String imageToString(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = android.util.Base64.encodeToString(byteArray, android.util.Base64.DEFAULT);
return encoded;
}
}
Error Stack:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tn.events.events, PID: 16587
java.lang.OutOfMemoryError: Failed to allocate a 24551844 byte allocation with 8376560 free bytes and 14MB until OOM
at java.lang.StringFactory.newStringFromBytes(StringFactory.java:88)
at java.lang.StringFactory.newStringFromBytes(StringFactory.java:65)
at android.util.Base64.encodeToString(Base64.java:456)
at tn.events.events.Connect.imageToString(Connect.java:195)
at tn.events.events.Connect.onActivityResult(Connect.java:129)
at android.app.Activity.dispatchActivityResult(Activity.java:6674)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4009)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4056)
at android.app.ActivityThread.access$1400(ActivityThread.java:196)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1588)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5982)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)

Sharing one image uploading multiple times

I am working on a Image sharing app. I can upload image to the sever but it uploading same image multiple times(3-4 times).
I have Images Fragment where i gave floating buttons to select camera or gallery.
Images Fragment
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_images, container, false);
floatcamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
File imageFolder = new File(Environment.getExternalStorageDirectory(), "/My Children");
imageFolder.mkdir();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmdd_hhmmss");
String timestamp = simpleDateFormat.format(new Date());
File image = new File(imageFolder, timestamp+ ".jpg");
// Uri uriImage = Uri.fromFile(image);
camerauri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", image);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, camerauri);
startActivityForResult(intent, TAKE_PICTURE);
}
});
floatgallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, SELECT_PICTURE);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == TAKE_PICTURE ) {
Intent i = new Intent(getContext(), Upload.class);
i.putExtra("image", camerauri.toString());
startActivity(i);
}
if (requestCode == SELECT_PICTURE) {
Intent i = new Intent(getContext() , Upload.class);
i.putExtra("image", data.getData().toString());
startActivity(i);
}
}catch (Exception e){
e.printStackTrace();
}
}
After Clicking or selecting image the resulting single image display on next Activity. And there is a button to upload it. I am using Custom Volley Request as Volley does not support Multipart.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
ImageView imageview = (ImageView) findViewById(R.id.imageview);
Intent intent = getIntent();
if (intent == null){
return;
}
final Uri imageUri = Uri.parse(intent.getStringExtra("image"));
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
} catch (IOException e) {
e.printStackTrace();
}
Glide
.with(this)
.load(imageUri)
.apply(new RequestOptions().priority(Priority.HIGH).fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL))
.into(imageview);
progressDialog = new ProgressDialog(Upload.this);
progressDialog.setMessage("Uploading");
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
caption = txtCaption.getText().toString();
uploadBitmap(bitmap);
}
});
}
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap(final Bitmap bitmap) {
progressDialog.show();
//our custom volley request
MultipartRequest volleyMultipartRequest = new MultipartRequest(Request.Method.POST, IMAGE_UPLOAD_URL,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
progressDialog.dismiss();
Toast.makeText(Upload.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
finish();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* 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<>();
userid = SharedPreferenceManager.getmInstance(Upload.this).getMobileno();
params.put("userid", userid);
params.put("caption", caption);
params.put("product","normal");
return params;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, MultipartRequest.DataPart> getByteData() {
Map<String, MultipartRequest.DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
params.put("uploadedfile", new MultipartRequest.DataPart(imagename + ".jpeg", getFileDataFromDrawable(bitmap)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
I Hope this will work for you
override this way
#Override
protected Map<String, MultipartRequest.DataPart> getByteData() {
Map<String, MultipartRequest.DataPart> params = new HashMap<>();
String imagename = imageUri.getLastPathSegment();
params.put("uploadedfile", new MultipartRequest.DataPart(imagename,getFileDataFromDrawable(bitmap)));
return params;
}

Volley PUT image request

I am trying to make a volley PUT request to upload an image, Since httpEntity is deprecated now, I had to do some other research, I came across these solutions and tried to implement them into my code :
1. https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594
2. How to send multipart request using Volley without HttpEntity?
3. Working POST Multipart Request with Volley and without HttpEntity
but still I cannot upload my image. The image I want to upload is either captured from the camera or selected in the gallery, and it is executed onClick.
ProfileSetting.java
public class ProfileSetting extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ImageView CustomerIcon;
private Button confirm_button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_setting);
CustomerIcon = (ImageView) findViewById(R.id.CustomerIcon);
confirm_button = (Button) findViewById(R.id.confirm_button);
CustomerIcon.setOnClickListener(new ImageView.OnClickListener(){
public void onClick(View v){
showPickImageDialog();
}
});
confirm_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view) {
//PUT VOLLEY
saveProfileAccount();
}
});
}
private void showPickImageDialog() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ProfileSetting.this);
builderSingle.setTitle("Choose Profile Icon");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
ProfileSetting.this,
android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Gallery");
arrayAdapter.add("Camera");
builderSingle.setNegativeButton(
"cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
case 1:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
break;
}
}
});
builderSingle.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
}
}
private void saveProfileAccount() {
// loading or check internet connection or something...
// ... then
String url = "https://url to put image to";
SharedPreferences sp1=this.getSharedPreferences("FINALTOKEN", Context.MODE_PRIVATE);
final String finalToken = sp1.getString("FINALTOKEN","");
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.PUT, 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 succeed 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
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers= new HashMap<>();
headers.put("Authorization",finalToken);
return headers;
}
#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", ImageConverter.getFileDataFromDrawable(getBaseContext(), CustomerIcon.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
}
VolleyMultipartRequest.java and VolleySingleton.java I am using the same class as what my first link has.
My errors are first of all I cannot resolve symbol 'Constant' in the if statement:
if (status.equals(Constant.REQUEST_SUCCESS))
so I tried commenting the statement, after running the code I got the following error:
BasicNetwork.performRequest: Unexpected response code 500 for https://my url
W/System.err: org.json.JSONException: No value for status
I am not sure what is causing my problem,please help, thank you!
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* #param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
#Override
public void onErrorResponse(VolleyError error) {
}
#Override
public void onResponse(String response) {
//Your response here
}
}
mChoosenFile is your image file
First of all convert your image bitmap to base64 string using the following code:
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Then make a PUT Request like the following one and pass the base64 string as a parameter of the request
url = "http://example.com";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("imageString", base64String);
return params;
}
};
queue.add(putRequest);
Refer Android Volley Tutorial if you face any difficulty in implementing volley request.

Categories

Resources