Hey I have a code that let the user pick an image from the gallery and after he chooses the image is shown in an image view, now when the user click a button it should upload the image to ftp server , but from some reason the app tells me that the location of the file I am giving is not found.
here is the ftp upload code (I execute it using asynctask)
public UploadImage(String host,int port,String username,String password,String imagePath) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.imagePath = imagePath;
}
public void uploadingFilestoFtp() throws IOException
{
FTPClient con = null;
try
{
con = new FTPClient();
con.connect(host);
if (con.login(username, password))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
Uri uri = Uri.parse(this.imagePath);
String data = uri.getPath();
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/img.png", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
and the loading file to imageview
loadedImage = (ImageView)findViewById(R.id.upload_image1);
Drawable drawable = loadedImage.getDrawable();
if(drawable.getConstantState().equals(getResources().getDrawable(R.drawable.camera_icon).getConstantState())) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "SelectPicture"), SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageURI = data.getData();
loadedImage = (ImageView)findViewById(R.id.upload_image1);
loadedImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
Glide.with(this).load(selectedImageURI)
.into((ImageView) findViewById(R.id.upload_image1));
ImageView m =(ImageView)findViewById(R.id.remove_image);
m.setFocusable(true);
m.setVisibility(View.VISIBLE);
}
}
}
The imagePath String is the image uri converted to string.
can anyone help me and tell me why isn't it finding the file?
Ask user to pick the image and use that image to imageView.. the path consist of the actual image path you can upload it..
#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 = data.getData();
if (uri != null)
{
path = uri.toString();
if (path.toLowerCase().startsWith("file://"))
{
// Selected file/directory path is below
path = (new File(URI.create(path))).getAbsolutePath();
}
else{
path = getRealPathFromUri(getApplicationContext(),uri);
}
}
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
profileImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Hope you are giving permission also
Related
I'm trying to get image from gallery and store the path to the database for further use.
File path is saved in database but I am unable to get the view on ImageView.
File path is: /storage/emulated/0/DCIM/Camera/image.jpg
Here I'm getting the image path as imgS
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = data.getData();
img.setImageURI(imageUri);
imgS = getPath(getApplicationContext(), imageUri);
}
}
public static String getPath(Context context, Uri uri) {
String result = null;
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndex("_data");
result = cursor.getString(column_index);
}
cursor.close();
}
if (result == null) {
result = "Not found";
}
return result;
}
Here I'm trying to retrieve the path and show the image in image view.
File f = new File(item.getImg());
Glide.with(c).load(f).into(holder.img);
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(c, f.getAbsolutePath(), Toast.LENGTH_SHORT).show();
if (f.exists()) {
Toast.makeText(c, f.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
}
});
Note: File exist at the path.
Just need to add android:requestLegacyExternalStorage="true" to Application tag in Manifest.xml .
I am working on a address book like Android SDK 14+ app. The users should be able to pick an image from the Gallery to add it to a contact entry.
Running the following code to pick and copy the image is no problem in API 14-20 but does not work in API 21+. The file is not found anymore:
protected void pickFoto() {
if (filePermissionsRequired()) {
askForFilePermissions(new PermissionRequestCompletionHandler() {
#Override
public void onPermissionRequestResult(boolean permissionGranted) {
if (permissionGranted)
addOrEditReceipt();
}
});
return;
}
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent , PICK_FOTO_ACTION);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
...
case PICK_FOTO_ACTION: {
Uri imageUri = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
public interface PermissionRequestCompletionHandler {
void onPermissionRequestResult(boolean permissionGranted);
}
private PermissionRequestCompletionHandler permissionRequestCompletionHandler;
public boolean filePermissionsRequired() {
if (Build.VERSION.SDK_INT >= 23)
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
else
return false;
}
public boolean askForFilePermissions(PermissionRequestCompletionHandler completionHandler) {
if (Build.VERSION.SDK_INT >= 23) {
permissionRequestCompletionHandler = completionHandler;
boolean hasPermission = this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!hasPermission) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return true;
}
}
permissionRequestCompletionHandler = null;
return false;
}
The app has runtime permissions to access the Gallery. So what am I doing wrong? How to access the file on newer API versions?
}
try below code to open the camera and getting result:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + System.currentTimeMillis() + ".png");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICK_FOTO_ACTION);
for getting result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_FOTO_ACTION: {
Uri imageUri = imageUri;
File imgFile = new File(imageUri.getPath());
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
}
for getting actual path from uri :
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
remove unwanted uri part :
public String RemoveUnwantedString(String pathUri){
//pathUri = "content://com.google.android.apps.photos.contentprovider/-1/2/content://media/external/video/media/5213/ORIGINAL/NONE/2106970034"
String[] d1 = pathUri.split("content://");
for (String item1:d1) {
if (item1.contains("media/")) {
String[] d2 = item1.split("/ORIGINAL/");
for (String item2:d2) {
if (item2.contains("media/")) {
pathUri = "content://" + item2;
break;
}
}
break;
}
}
//pathUri = "content://media/external/video/media/5213"
return pathUri;
}
For versions 21 and higher you can do this , you need to add a condition to check the SDK version for this. Exectute this code in the API 21+ condition block.
String wholeID = DocumentsContract.getDocumentId(imageUri );
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
Call the Gallery with belo code
public static final int SELECT_IMAGE_FROM_GALLERY_CODE = 701;
public static void callGallery(Activity activity) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
SELECT_IMAGE_FROM_GALLERY_CODE);
}
In OnActivityResult, read URI and read path from uri.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CommonUtils.SELECT_IMAGE_FROM_GALLERY_CODE) {
if (data != null) {
Uri selectedImageUri = data.getData();
// get path from Uri
String imagepath = getPath(this, selectedImageUri);
if (null != imagepath && (!imagepath.isEmpty())) {
// if the image path is not null and not empty, copy image to sdcard
try {
copyDirectoryOrFile(new File(imagepath), new File(myTargetImageFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// load the image into imageView with the help og glide.
loadImageWithGlide(myImageViewContactImage,
myTargetImageFilePath, myDefaultImagePath, myErrorImagePath, false);
} else {
Toast.makeText(this, "Error: Photo selection failed.", Toast.LENGTH_LONG).show();
}
}
}
}
public void loadImageWithGlide(ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int theErrorImagePath,
boolean theIsSkipMemoryCache) {
if (theIsSkipMemoryCache) {
Glide.with(ProfileActivity.this) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(theErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.centerCrop()
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
} else {
Glide.with(ProfileActivity.this)
.load(theLoadImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.centerCrop()
.into(theImageViewToLoadImage);
}
}
public static String getPath(Context theCtx, Uri uri) {
try {
Cursor cursor = (theCtx).getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = (theCtx).getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
} catch (Exception e) {
return null;
}
}
public static void copyDirectoryOrFile(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectoryOrFile(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create directory " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To load image with glide, add following dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
I'm making an App where I call the file explorer, the when I choose a file i get the name with file.getName() and put it in a TextView and get the path with file..getPath() and save it in a String, this String I use it to attach the file into a mail... my problem is that when a choose a file like .PDF, .DOC, .DOCX, .MP3 I can attach it but when a select an image I get this kind of path: "/media/external/images/media/1220" and does not attach anithing, I've been serarching everywhere and use almost every option I have found with no result.
Here is my code:
private void PickFile(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, PICKER);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((resultCode == RESULT_OK) && (requestCode == PICKER)) {
String FilePath = data.getData().getPath();
File file = new File(FilePath);
}
if (txtAdjunto1.getText() == "_") {
adjunto1 = file.getPath();// I get the path to add it to the MimeBodyPart
txtAdjunto1.setText(file.getName());// I put the name in the TextView
I've been trying this:
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
int column_index;
String ruta = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null){
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
ruta = cursor.getString(column_index);
}
return ruta;
} finally {
if (cursor != null) {
cursor.close();
}
}
But the app crashes when I pick the file.
Also tried this:
file = new File(file.getAbsolutePath());
But still geting this "/media/external/images/media/1220"...
Hop someone can help me with this, and thanks in advance
ACTION_GET_CONTENT and ACTION_OPEN_DOCUMENT allow the user to choose a piece of content. That content might be a local file. That content might also be:
Something on a file server on the network
Something in a cloud storage service, such as Google Drive
Something in an encrypted volume
Something that is a file, but is not a file that you can access directly
And so on
You have two main options. If you only want files, then use a third-party file chooser library to replace all of the code in your question.
Or, you can take the Uri that you get from data.getData() in onActivityResult() and do two things with it:
First, use DocumentFile.fromSingleUri() to get a DocumentFile object pointing to that Uri. You can call getName() on the DocumentFile to get a "display name" for the content, which should be something that the user will recognize.
Then, use a ContentResolver and openInputStream() to get at the content itself, similar to how you might use a FileInputStream to get at the bytes in a file.
Try this...
The following code is to select any type of file from file manager and camera then convert to byte array and attach file make edit as per your requirement
private void selectFile() {
final CharSequence[] items = {"Camera", "Choose from File Manager",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(ComposeActivity.this);
builder.setTitle("Add Attachment!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Constant.checkPermission(ComposeActivity.this);
if (items[item].equals("Camera")) {
userChoosenTask = "Camera";//String
if (result)
cameraIntent();
} else if (items[item].equals("Choose from File Manager")) {
userChoosenTask = "Choose from File Manager";//String
if (result) {
FileManagerIntent();
}
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
to call camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
file from file manager
private void FileManagerIntent() {
try {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), 111);
} catch (Exception e) {
// Handle exceptions here
e.printStackTrace();
}
}
results
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
getting camera result and converting it to bytearray
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
Uri uri = Uri.fromFile(destination);
String uriString = uri.toString();
String path = destination.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = ComposeActivity.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
strFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
strFileName = destination.getName();
}
attachLayout.setVisibility(View.VISIBLE);
txtFileName.setText(strFileName);
try {
fileByteArray = bytes.toByteArray();
strFile = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
Log.v("Soma", strFile);
Log.v("Byte Array * ", strFile);
} catch (Exception e) {
e.printStackTrace();
}
}
result from file manager
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
if (uri.toString().contains("video") || uri.toString().contains("audio")) {
Toast.makeText(ComposeActivity.this, "Oops! can't send video/audio file", Toast.LENGTH_SHORT).show();
} else {
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = ComposeActivity.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
strFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
strFileName = myFile.getName();
}
Log.v("Super DisplayName", strFileName);
attachLayout.setVisibility(View.VISIBLE);
txtFileName.setText(strFileName);
try {
InputStream iStream = getContentResolver().openInputStream(uri);
fileByteArray = getBytes(iStream);
strFile = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
Log.v("Byte Array * ", strFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
file to bytearray
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
I have an onclick that will allow a user to select a file from gallery like so:
case R.id.ColourCustom:
customBorderChange();
break;
private void customBorderChange() {
final ImageView QPBackground = (ImageView) findViewById(R.id.QPBackground);
menuHandler.removeCallbacks(menuTimer);
menuHandler.postDelayed(menuTimer, 5000);
bgHandler.removeCallbacks(runnableBG);
bgHandler.postDelayed(runnableBG, 2000);
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GALLERY_REQUEST);
File file = getFileStreamPath("QuickPlayBG.png");
if (file.exists()) {
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
} else {
String uri21 = "#drawable/bg_green";
int imageResource21 = getResources().getIdentifier(uri21, null, getPackageName());
QPBackground.setBackgroundResource(imageResource21);
}
}
This sends you here:
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
Uri selectedImageUri;
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && null !=
data) {
selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
cursor.close();
}
try {
Bundle extras = data.getExtras();
Bitmap photo = extras.getParcelable("data");
saveBGFile(photo);
} catch (Exception e) {
String errorMessage = "Make your mind up mate!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
try {
saveQPConfig();
} catch (IOException e) {
String errorMessage = "Saving failed";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Which saves the file, using saveBGFile:
public void saveBGFile(Bitmap image) {
FileOutputStream out = null;
String filename = "QuickPlayBG.png";
try {
out = new FileOutputStream(filename);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue is with this line only:
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
It doesn't load anything. If I change "QuickPlayBG.png" to another filename that I am using in another part of my app, it loads fine. Both files are created using the same method. I verified that "QuickPlayBG.png" exists.
Compiler gives me the following hint:
E/﹕ ReadStreamToBuffer : Qmage Stream read error!! required length 12 bytes, but red 0 bytes
E/﹕ isQmage : input SkStreamRewindable length is less than Qmage minimum size : 0
I think it has to do with the way I am saving the image, but I cannot see the fault myself. What could be the problem, that it is not loading the image?
Edit:
Here is the getThumbnail method I am using (works for another filename):
public Bitmap getThumbnail(String filename) {
final Context context = this;
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
Bitmap thumbnail = null;
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() !exist", ex.getMessage());
}
}
return thumbnail;
}
Use this short and sweet code for this. use intent of gallery.
1.declaire variable.
private static int RESULT_IMG = 1;
String imgString;
2.call intent of gallery on onclick of button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
3.onActivityResult to your code.
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
try {
if (requestCode == RESULT_IMG && responseCode == RESULT_OK
&& null != data) {
Uri pickedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgString = cursor.getString(columnIndex);
cursor.close();
//set bitmap to your imageview
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory.decodeFile(imgString));
} else {
Toast.makeText(this, "please select picture",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "error message", Toast.LENGTH_LONG)
.show();
}
}
I am launching the intent for selecting documnets using following code.
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"), 1);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
In onActivity results when i am trying to get the file path it is giving some other number in the place of file name.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
File myFile = new File(uri.toString());
String path = myFile.getAbsolutePath();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
That path value i am getting like this.
"content://com.android.providers.downloads.documents/document/1433"
But i want real file name like doc1.pdf etc.. How to get it?
When you get a content:// uri, you'll need to query a content resolver and then grab the display name.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String displayName = null;
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));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
First Check if the permission is granted for Application.. Below method is used to check run-time permission'
public void onClick(View v) {
//Checks if the permission is Enabled or not...
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, USER_IMG_REQUEST);
}
}
and below method is used to find the uri path name of the file
private String getRealPathFromUri(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
CursorLoader cursorLoader = new CursorLoader(thisActivity, uri, projection, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column);
cursor.close();
return result;
}
and the above method can be used as
if (requestCode == USER_IMG_REQUEST && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
String imagePath = getRealPathFromUri(path);
File file = new File(imagePath);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part imageFile = MultipartBody.Part.createFormData("userImage", file.getName(), reqFile);
You can try this,m I hope it will help u:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("inside", "onActivityResult");
if(requestCode == FILE_MANAGER_REQUEST_CODE)
{
// Check if the user actually selected an image:
if(resultCode == Activity.RESULT_OK)
{
// This gets the URI of the image the user selected:
Uri selectedFileURI = data.getData();
File file = new File(getRealPathFromURI(selectedFileURI));
// Create a new Intent to send to the next Activity:
}
}
}
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;
}
Here is the complete solution:
Pass your context and URI object from onActivityResult to below function to get the correct path:
it gives the path as /storage/emulated/0/APMC Mahuva/Report20-11-2017.pdf (where I've selected this Report20-11-2017.pdf file)
String getFilePath(Context cntx, Uri uri) {
Cursor cursor = null;
try {
String[] arr = { MediaStore.Images.Media.DATA };
cursor = cntx.getContentResolver().query(uri, arr, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}