I am using Picasso 2.5.2 to use it with OkHttp 2.5.0
The code in onCreate() is like below:
File mypath = new File(getFilesDir().getAbsolutePath()+"/"+ date + "image.png");
if (mypath.exists())
{
Picasso.with(FullscreenImage.this).load(mypath).into(fullImage);
Toasty.info(FullscreenImage.this, mypath.toString()).show();
}
else
{
// Download the image from Firebase and create the image in the
// same directory and name
}
I see the image in the files folder in my app folder but it does not display in the image view.
The image size: 1.4 MB
I have resolved my issue by turning the file into a bitmap then use it in the ImageView:
Bitmap bitmap = BitmapFactory.decodeFile(mypath.toString());
fullImage.setImageBitmap(bitmap);
If someone is stuck like me, I did like this, checking on the Picasso webpage (
https://square.github.io/picasso/ ) - section RESOURCE LOADING, line 3:
String drPath = localData[position].getDrawablePath();
if(!drPath.equals(""))
{
var f = **new File(context.getFilesDir(), drPath)**;
try
{
Picasso.get()
.load(f)
.fit()
.centerCrop()
.into(holder.itemImage);
}
}
previously copied the file from Uri to local position like this:
try {
File f = new File(CategoryFragment.this
.getContext()
.getFilesDir()
, fileName);
f.setWritable(true, false);
OutputStream outputStream = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
registered ONLY THE NAME OF THE FILE like this: cmdEditVM.setDrawable(***fileName***, positionForNewDrawable);
It had been retrieved from the Uri with the following (taken from SO):
public String getFileName (Uri uri)
{
String result = null;
if (uri.getScheme().equals("content"))
{
Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
try
{
if (cursor != null && cursor.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (columnIndex >= 0) {result = cursor.getString(columnIndex);}
}
}
finally
{
if (cursor != null) {cursor.close();}
}
}
if (result == null)
{
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1)
{
result = result.substring(cut + 1);
}
}
return result;
}
Related
I want to get image path and upload to the server.
Here i successfully read image from gallery and set into image view but image path return null.
public void onActivityResult(int requestCode, int resultCode, Intent data)
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getRealPathFromURI(getActivity(), selectedImageUri);
Log.i(TAG, "IMAGE" + path);
Log.d("INFO", selectedImageUri.toString());
// Set the image in ImageView
profilepicture.setImageURI(selectedImageUri);
}
}
}
}
/* Get the real path from the URI */
public 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();
}
}
}
Delete getRealPathFromURI(), as it is not going to work reliably.
Instead, use your favorite image-loading library (e.g., Picasso, Glide) to load the image from the Uri.
Or, in a worst-case scenario, use getContentResolver().openInputStream() to get an InputStream on the content identified by the Uri, then pass that stream to BitmapFactory.decodeStream(). Just do this I/O on a background thread, please (which image-loading libraries will handle for you, among other benefits).
Update your method getRealPathFromURI:
public 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();
String imagePath = cursor.getString(column_index);
if (imagePath == null) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "New");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file;
String path = "img_" + timeStamp + ".jpg";
file = new File(mediaStorageDir.getPath() + File.separator + path);
imagePath = file.getAbsolutePath();
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor = context.getContentResolver()
.openFileDescriptor(contentUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory
.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
saveBitmapToPath(image, imagePath);
} catch (IOException e) {
e.printStackTrace();
}
}
return imagePath;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Use this function to convert String URL to Bitmap
public Bitmap getImage(String url) {
try {
BufferedInputStream bis = new BufferedInputStream(new
URL(url).openStream(), BUFFER_IO_SIZE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos,
BUFFER_IO_SIZE);
copy(bis, bos);
bos.flush();
return BitmapFactory.decodeByteArray(baos.toByteArray(), 0,
baos.size());
} catch (IOException e) {
Log.d(TAG, "loadImageFromArrayList: IMAGE DOWNLOAD FAILED!" +e);
}
return null;
}
try this
String path = yourAndroidURI.toString() // "/mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));
I am developing an application in which I open the file explorer and select any file of my choice and retrieve its contents. The default path that opens is /storage/sdcard0 . I am able to read contents of any file that resides directly in this path. However, for any file that in contained in any folder inside /storage/sdcard0/. is inaccessible. The program gives a file not found error. Also, I cannot understand the path that these files have, like for example, if a file resides in path:
/storage/sdcard0/DCIM/100ANDRO/DSC_0001.jpg
,
the logcat shows the path to be:
content:/media/external/images/media/84290/DSC_0001.jpg
How to access this file in my Java code?
Below is the code snippet:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "requestCode received: "+requestCode+" result code: "+resultCode);
if (requestCode == 1 && resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
String folderPath = "Anant";
String filePath = "image.jpg";
String imagePath = saveToInternalStorage(thumbnail, folderPath,
sImageName);
Log.i(TAG, "DeviceAPIS:actual path :: "
+ imagePath.trim().toString());
sendCameraData(imagePath.toString().trim(),
ptrAppContainerForCamera);
}
else if (requestCode == REQUEST_PATH){
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "data.getData() result line 742: " + uri);
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String base64 ="Error";
byte[] bytesRead = base64.getBytes();
String displayName = null;
String fileName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = mContext.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
displayName = path + "/" + displayName;
Log.d(TAG, "BEFORE REPLACE: "+displayName);
int index = displayName.indexOf(':');
fileName = displayName.substring(index + 1, displayName.length());
Log.d(TAG,"displayName line 762 " + Part);
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
Log.d(TAG, "FILE BLOCK LINE 768");
displayName = myFile.getName();
Log.d(TAG,"displayName 11" + displayName);
}
try{
File sdcard = Environment.getExternalStorageDirectory();
File readFile = new File(sdcard, fileName);
// File readFile = new File(uri);
int length = (int)readFile.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(readFile);
try{
in.read(bytes);
}finally {
in.close();
}
String contents = new String(bytes);
Log.d(TAG,"contents read :: \\n" + contents);
//convert to Base64
bytesRead = contents.getBytes("UTF-8");
base64 = Base64.encodeToString(bytesRead,Base64.DEFAULT);
}catch (Exception e){
Log.d(TAG, "THROWING EXCEPTION");
Log.e(TAG,e.getMessage(),e);
}
}
The exception thrown is java.io.FileNotFoundException. Any help is greatly appreciated.
You can try as below:
String path = null;
Uri originalUri = data.getData();
try {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = this.managedQuery(originalUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index);
} catch (Exception e) {
} finally {
cursor.close();
}
And if path is null, you can get bitmap first and then copy it to your local path.
ContentResolver resolver = this.getContentResolver();
Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
.... // copy photo to your local path
you can try this,
1. make sure you have added permission in you manifest file
2. Settings -> Apps -> Your App -> Permissions -> Storage = true/enabled
I had faced a same issue of FileNotFound and i was able to resolve it by #2 above.
What I am trying to achieve. I have a button, when the button is clicked the app opens a file picker and the user selects a file. The app then uses a FileInputStream to read the file and generates a byte[]. I have a TextView below the button which will then simply display the byte[].length. Here is the code in the button.onClick() event:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
requestFilePickerCode = parent.registerActivityResultListener(this);
try
{
parent.startActivityForResult(intent, requestFilePickerCode);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(task.getParent(), "Please install a file manager", Toast.LENGTH_SHORT).show();
}
Now this code works and I have confirmed that it fires onActivityResult when the file is chosen. I simply print a Log to display data.toString() which produces the following output:
11-02 15:14:36.196 2535-2535/? V/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> content:/com.android.providers.downloads.documents/document/1
So it seems to be getting the selected file. When I run the app and I select a file it throws my custom error:
11-02 15:14:36.196 2535-2535/? E/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> File does not exist
This obviously indicates that I am not getting the file. Here is my code:
#Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data)
{
byte[] fileContent;
// check that data is not null and assign to file if not null
if (data != null)
{
Uri uri = data.getData();
String uriString = uri.toString();
file = new File(uriString);
Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> " + file.toString());
// declare file input stream and read bytes
// write to string variable to test and test output
FileInputStream fin = null;
try
{
fin = new FileInputStream(file);
fileContent = new byte[(int) file.length()];
fin.read(fileContent);
String test = new String(fileContent);
Log.v(PebbleTypeHandlerBinary.class.toString(), "=====> " + test);
}
catch (FileNotFoundException e)
{
Toast.makeText(task.getParent(), "File not found", Toast.LENGTH_SHORT).show();
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File does not exist");
}
catch (IOException e)
{
Toast.makeText(task.getParent(), "Error reading file", Toast.LENGTH_SHORT).show();
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error while reading the file");
}
finally
{
// close the file input stream to stop mem leaks
try
{
if (fin != null)
{
fin.close();
}
} catch (IOException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error closing the stream");
}
}
Log.v(PebbleTypeHandlerBinary.class.toString(), data.toString());
}
return false;
}
Please can you guys review my code and help me to get this working. Any help would be appreciated.
/* you can get just name and size with this method.
use Cursor .
Uri uri = data.getData();
get data from onActivityResult()
*/;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
cursor.moveToFirst();
String name = cursor.getString(nameIndex);
String size = Long.toString(cursor.getLong(sizeIndex));
Toast.makeText(this, "name : "+name+"\nsize : "+size, Toast.LENGTH_SHORT).show();
I managed to fix it as follows:
I used inputStream = task.getParent().getContentResolver().openInputStream(uri); to get an InputStream. Then used a ByteArrayOutputStream to write to a byte[]. See code below.
#Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data)
{
Uri uri = data.getData();
byte[] fileContent;
InputStream inputStream = null;
try
{
inputStream = task.getParent().getContentResolver().openInputStream(uri);
if (inputStream != null)
{
fileContent = new byte[(int)file.length()];
inputStream.read(fileContent);
fileContent = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read;
while((read=inputStream.read(fileContent))>-1) baos.write(fileContent,0,read);
fileContent = baos.toByteArray();
baos.close();
Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> Input Stream: " + inputStream);
Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> Byte Array: " + fileContent.length);
}
else
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Input Stream is null");
}
}
catch (FileNotFoundException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File not found", e);
}
catch (IOException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error reading file", e);
}
finally
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error reading file", e);
}
}
}
return false;
}
Thanks for all your help.
U can search converting uri to filepath.
GetData() retruns a uri.
But new File() need a filepath param;
Like this:
public static String getRealFilePath( final Context context, final Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if
( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}
1. File Name:
You can get the file name with the following method:
public static String getFileName(Context context, Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
You will call it inside onActivityResult() and pass to it the context and uri. and you can find the uri through the intent you get from the onActivityResult which is mostly called "data", you will get the Uri from it like this:
data.data
which ".data" is the Uri.
Ex:
Utils.getFileName(this, data!!.data)
And finally it will return the file name as a String.
2. File Path:
Simply to get the file path you can get it from the data intent uri like this:
data!!.data!!.path.toString()
It will get you the path of the file as a String.
I use basic4android and I want to know the size of selected image from gallery.
my code is :
Dim PicChooser As ContentChooser
PicChooser.Initialize("PicChooser")
PicChooser.Show("image/*", "Select a pic")
Sub PicChooser_Result(Success As Boolean, Dir As String, FileName As String)
If Success = True Then
Dim inp As InputStream
inp = File.OpenInput(Dir, FileName)
Dim btm As Bitmap
btm.Initialize2(inp)
end if
end Sub
I use below method in b4a but it doesn't work.
File.Size(Dir,FileName)
it returns zero because Dir and Filename in this sub doesn't really shows the path of the file.
Somewhere i found this maybe untested code:
public static String getContentSizeFromUri(Context context, Uri uri) {
String contentSize = null;
String[] proj = {MediaStore.Images.Media.SIZE };
CursorLoader cursorLoader = new CursorLoader(
context,
uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null)
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
if (cursor.moveToFirst() )
contentSize = cursor.getString(column_index);
}
return contentSize;
}
Check if return value is null before use.
If you already get the Uri of the file, you can use the following code to get some information
if (uri != null) {
File file = new File(uri.getPath());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("FileName", file.getName());
jsonObject.put("FilePath", file.getAbsolutePath());
jsonObject.put("FileSize", file.length());
} catch (JSONException e) {
e.printStackTrace();
}
}
i am getting multiple uri's from the gellery Intent.ACTION_SEND_MULTIPLE intent
all i want to do is copy these files to a new location "/sdcard/BACKUP/"
i have been trying for hours without a solution
here is the code:
ArrayList<Uri> imageUris = null;
if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
File createDir = new File(root+"BACKUP"+File.separator);
if(!createDir.exists()) {
createDir.mkdir();
}
for (Uri uri : imageUris){
File file = new File(uri.getPath());
File newfile = new File(root + "BACKUP" + File.separator + uri.toString() +".jpg" );
copyFile(file,newfile);
}
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
i am getting a java.io.Filenotfound exception
you need the WRITE_EXTERNAL_STORAGE permission the you can simply do
sourceFile.renameTo(destFile);
the doc for renameTo says
Renames this file to newPath. This operation is supported for both
files and directories
you can find it here
The problem was initializing the sourcefile
this is what worked :
File file = new File(getPath(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;
}
Thank you everyone for your support