I am trying to get selected images from user and upload it to backend. I tried getting path of selected images then reading it with file and then parsing it to multipart. I am getting only null values from getRealPathFromURI method. Is there any other way to do this or what wrong i am doing?
ActivityResultLauncher<Intent> activityResultLauncher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode()== Activity.RESULT_OK){
imageURI=new ArrayList<>();
Intent data=result.getData();
ClipData mClipData = data.getClipData();
int count = data.getClipData().getItemCount();
for (int i = 0; i < count; i++) {
Uri imageurl = data.getClipData().getItemAt(i).getUri();
imageURI.add(imageurl);
}
}else {
Toast.makeText(getApplicationContext(), "Some error occured", Toast.LENGTH_SHORT).show();
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
activityResultLauncher.launch(Intent.createChooser(intent,"choose image"));
}
});
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
for (int i = 0; i < imageURI.size(); i++) {
Uri uri=imageURI.get(i);
String path=getRealPathFromURI(uri); // here I am getting only null values
File file=new File(path);
builder.addFormDataPart("files[]",file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}