I use a Intent to get pictures path and open them into a File. I can open files allocated in "Camera" folder like "/storage/emulated/0/DCIM/Camera/IMG_20160817_232858.jpg", but I cannot open files in locations like "/storage/emulated/0/Pictures/1634894_.png". Using file.exists() it just says that it doesn't.
Need to say that I'm using API 23 and I request READ_EXTERNAL_STORAGE, so this souldn`t be a problem... But I can't access those files even with that.
What can be wrong?
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
File file = new File(picturePath);
if(file.exists()) {
} else {
}
cursor.close();
}
}
Updated: it doesn't happens with all the files from the same folder, just some of them, but they really exist since I can open them from the gallery.
Update2:
I use this Intent.
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
Update3:
Running time permissions:
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
SomeWork();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}
else {
SomeWork();
}
Permissions in Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
The MediaStore will index images that are not accessible to you from the filesystem. There is no requirement for a DATA column to return a value that you can use.
Instead, stop trying to get a File, and use the Uri itself:
getContentResolver().openInputStream() to get an InputStream on it
DocumentFile.fromSingleUri() to get a DocumentFile for easy access to metadata (e.g., MIME type)
try{
// this works!!!
File csvfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/brcOrdersaved.csv");
final String filename = csvfile.toString();
if (!csvfile.exists()) {
// displayMsg(context, "No Saved Order: ");
return (false);
}
FileReader fr = new FileReader(filename);
BufferedReader reader = new BufferedReader(fr);
String csvLine = "";
final char Separator = ',';
final char Delimiter = '"';
final char LF = '\n';
final char CR = '\r';
boolean quote_open = false;
if (reader.equals(null)) {
displayMsg(context, "NULL");
return (false);//rww 11/13/2021
}
int i = 0;
while (!myendofcsvfile) {
csvLine = reader.readLine();
if (csvLine == null) {
myendofcsvfile = true;
}
// do stuff here
}
fr.close();
fileexists = true;
} catch (Exception e) {
String msg = "Can not Load Saved Order ";
fileexists = false;
return (fileexists);
}
Related
When I am uploading a pdf file to windows server it's getting corupted when downloading from FileZilla. The File size is also increasing in bytes.
Some files gets corrupted or some files only have half content.
Any help or code would be appreciated.
Thanks!
On Click to choose file from phone's directory:
btnSelectFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(Intent.createChooser(intent, "Select PDF File"), 21);
}
});
On Activity Result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 21:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
uri = data.getData();
uriString = uri.toString();
myFile = new File(uriString);
path = myFile.getAbsolutePath();
displayName = null;
file1 = Uri.fromFile(new File(path));
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
textFileSelectedOrNot.setText(displayName);
fileName = textFileSelectedOrNot.getText().toString();
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
textFileSelectedOrNot.setText(displayName);
fileName = textFileSelectedOrNot.getText().toString();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Creating directory on server and uploading file:
class CreateDir extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String server = "XX.XXX.X.XX";
String username = "XXXXXXX";
String password = "XXXXX";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, 2102);
ftpClient.login(username, password);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
Log.d(TAG, "CONNECTED");
String dirPath = "/ws.gajeratrust.org/TestingApp/" + fileId + "/";
boolean created = ftpClient.makeDirectory(dirPath);
FTPUtils.mkdir(ftpClient, dirPath);
InputStream inputStream =getContentResolver().openInputStream(uri);
ftpClient.storeFile(dirPath+"/"+fileName,inputStream);
inputStream.close();
ftpClient.logout();
ftpClient.disconnect();
Log.d(TAG, "DISCONNECTED");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Please check the code any alterations or something I have coded wrong, please comment it.
InputStream inputStream = new FileInputStream(file);
Replace that by
InputStream inputStream = getContentResolver().openInputStream(data.getData());
You can throw away all code messing around with File and Cursor instances.
Also i wonder what those four lines before the line i quoted should do.
The problem was that I was setting the transfer mode incorrect way.
Right way is :
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
I am trying to get an image from the camera or gallery to upload on the server. My code is working perfectly in Android 9 or lower but I cannot able to access the image path in Android 10. I don't know much about Android 10’s Scoped Storage, Please review my code and help.
private void selectImage(Context context, final int cameraRequestCode, final int galleryRequestCode) {
if (!hasPermissions(context, PERMISSIONS)) {
ActivityCompat.requestPermissions(requireActivity(), PERMISSIONS, PERMISSION_ALL);
} else {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
/* Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, cameraRequestCode);*/
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, cameraRequestCode);
} else if (options[item].equals("Choose from Gallery")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, galleryRequestCode);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
}
public File convertBitmaptoFile(Bitmap bitmap, String filename) throws IOException {
File f = new File(requireContext().getCacheDir(), filename);
f.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
return f;
}
'Here is my onActivity code'
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
try {
String millisecond = String.valueOf(Calendar.getInstance().getTimeInMillis());
// logo_file = new File(String.valueOf(convertBitmaptoFile(fileToBitmap(sdImageMainDirectory.getPath()), "IMAGE_" + millisecond + ".jpg")));
// img_logo.setImageURI(Uri.parse(logo_file.getAbsolutePath()));
img_logo.setImageURI(Uri.parse(getPath(Uri.fromFile(logo_file = new File(String.valueOf(convertBitmaptoFile(fileToBitmap(sdImageMainDirectory.getPath()), "IMAGE_" + millisecond + ".jpg")))))));
Log.e("logo file path","" + logo_file.getPath());
Log.e("logo file absolute path","" + logo_file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
// fa_image.setImageURI(Uri.parse(fa_image_file.getPath()));
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = Uri.parse(data.getData().getEncodedPath());
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
logo_file = new File(picturePath);
Log.e("IMAGE", "ja_image :" + logo_file);
img_logo.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}
}
break;
}
}
}
Have you used android:requestLegacyExternalStorage="true" in AndroidManifest.xml
<application
android:name="com.xyz"
android:allowBackup="true"
android:exported="false"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:requestLegacyExternalStorage="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning"
tools:targetApi="q">
In Android 10, you cannot access image using the uri provided in onActivityResult. Try this. I'm sure it will work for you. This is will work when you are selecting an image from gallery. For taking pictures from camera photo, the approach is a little different.
Kotlin Solution :
val imageType = contentResolver.getType(data.data!!)
data.data!!.let {
application.contentResolver.openInputStream(it).use { inputStream ->
filePartImage = MultipartBody.Part.createFormData(
"image", //should be same as the key of your parameter
"filename" + ".jpg", // extension of file name is must
inputStream!!.readBytes().toRequestBody(imageType.toMediaTypeOrNull())
)
}
}
Later pass this filePartImage as your image parameter for uploading image to server.
In my app, I am using webview to render a webpage from which I need to upload multiple files to the server. OnShowFileChooser() (for lollipop and upper versions) is working fine but onOpenFileChooser() (for other lower android versions). OnshowFileChooser() method not working if I pass an Uri array(Uri[]) to its onValueCallback(). It throws the classCastException. Below is my code which i have used for performing the required opertation. I need a solution to upload multiple file using webview which will work for all android versions.
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri[]> uploadMsg) {
openFileChooser(uploadMsg, "");
}
}
This is the onActivityResult code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
if (data.getData() != null) {
String dataString = data.getDataString();
if (dataString != null) {
// results = new Uri[]{Uri.parse(dataString)};
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(Uri.parse(dataString.replace("%3A", ":")));
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
results = new Uri[]{Uri.parse("file:" + filePath)};
}
cursor.close();
}
} else {
if (data.getClipData() != null) {
ClipData clipData = data.getClipData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item image = clipData.getItemAt(i);
Uri uri = image.getUri();
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String contentUri;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.DATA;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.DATA;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.DATA;
}
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
results[i] = Uri.parse("file:" + filePath);
}
}
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result[] = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
if (data.getData() != null)
result[0] = data.getData();
else {
if (data.getClipData() != null) {
result = new Uri[data.getClipData().getItemCount()];
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
result[i] = data.getClipData().getItemAt(i).getUri();
}
} else {
result = null;
}
}
// retrieve from the private variable if the intent is null
//result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
this is the Error report
I am using code listed here Check Incoming number is stored in Contacts list or not android for checking whether incoming number exist or not in contacts. This code does not give correct result always.
Is there some correction required in this or some other better way to check?
Code:
String res = null;
try {
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String a = uri.getLastPathSegment();
Cursor c = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, ContactsContract.CommonDataKinds.Phone._ID + "=?", new String[]{a}, null);
if (c != null) { // cursor not null means number is found contactsTable
if (c.getCount() > 0) {
if (c.moveToFirst()) { // so now find the contact Name
res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
c.close();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return res;
Try the below code its simple & working for me.
public class TestActivity extends Activity {
private static final int REQUEST_CONTACT_NUMBER = 8512885487;
/** Pops the "select phone number" window */
public void onBrowseForNumbersButtonClicked(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, REQUEST_CONTACT_NUMBER);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data != null && requestCode == REQUEST_CONTACT_NUMBER) {
Uri uriOfPhoneNumberRecord = data.getData();
String idOfPhoneRecord = uriOfPhoneNumberRecord.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, Phone._ID + "=?", new String[]{idOfPhoneRecord}, null);
if(cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
String formattedPhoneNumber = cursor.getString( cursor.getColumnIndex(Phone.NUMBER) );
Log.d("TestActivity", String.format("The selected phone number is: %s", formattedPhoneNumber));
}
cursor.close();
}
}
else {
Log.w("TestActivity", "WARNING: Corrupted request response");
}
}
else if (resultCode == RESULT_CANCELED) {
Log.i("TestActivity", "Popup canceled by user.");
}
else {
Log.w("TestActivity", "WARNING: Unknown resultCode");
}
}
}
I know that there is a lot of examples on the internet for it but no one of those does what I really want. I want to select multiple images with an intent and get it "url" like this code does with one. (I know that this code cannot select more than one, but I use this as example of what I'm trying to do)
Code:
public static final int RESULT_LOAD_IMG = 0;
public void LoadImg() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
ArrayList<Part> files = new ArrayList<>();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
files.add(new FilePart("uploadedfile[" + String.valueOf(files.size()) + "]", new File(picturePath)));
cursor.close();
}
}
Searching on the internet I found this example from Laith Mihyar in this post: Select multiple images from android gallery
and I want to do the same here, but the file path is different here and dont work for what I'm trying to do.
Code:
int PICK_IMAGE_MULTIPLE = 1
String imageEncoded;
List<String> imagesEncodedList;
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
}else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Thanks
There is no "file path". ACTION_GET_CONTENT does not have to return a file Uri, and most of the time on newer devices it will return a content Uri.
Use ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Use DocumentFile and fromSingleUri() to get at metadata about the content identified by the Uri.
I can't even load it in an ImageView
Picasso and other image-loading libraries (even Ion) work with content Uri values without an issue.
I'm trying to upload those files with the Ion lib, that needs a path
The best solution would be to use a better HTTP client library, one that offers greater flexibility. OkHttp (with Okio) should be able to handle uploading from a Uri.
Or, use ContentResolver and openInputStream() to get an InputStream on the content. Use FileOutputStream to get a stream on some local file (e.g., in getCacheDir()). Use Java I/O to copy the bytes from the InputStream to the FileOutputStream. Then, use the local file with Ion.