Hi i want to get image from a specific folder. Now im using this code:
Intent intent = new Intent();
Uri uri = Uri.parse(Environment.DIRECTORY_PICTURES);
intent.setDataAndType(uri, "image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Scegli foto"),PICK_IMAGE_REQUEST);
Now,with that uri i see the recent and i have to open manually folder.I've tryed setting uri.parse input with the path of my folder,but i got anyway my recent.How can i open automatically my folder?
try this my friend
private void getImages() {
String[] filenames = new String[0];
File path = new File(Environment.getExternalStorageDirectory() + "/FolderName");
if (path.exists()) {
filenames = path.list();
}
ArrayList<String> imagesPathArrayList;
for (int i = 0; i < filenames.length; i++) {
imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
Log.e("FAV_Images", imagesPathArrayList.get(i));
///Now set this bitmap on imageview
}
}
set image like this
Bitmap bitmap = BitmapFactory.decodeFile(imagesPathArrayList.get(position));
ImageView.setImageBitmap(bitmap);
Related
I know that is easy to take a photo and save it to Gallery.
protected async Task<MediaFile> TakePhoto()
{
var storageOptions = new StoreCameraMediaOptions()
{
SaveToAlbum = true,
Directory = pictureAlbumName,
Name = $"test_{DateTime.Now.ToString("HH_mm_ss_ff")}.jpg"
};
return await CrossMedia.Current.TakePhotoAsync(storageOptions);
}
As the result I got the URL that looks like this:
/storage/emulated/0/Android/data/com.companyname.appname/files/Pictures/MyAlbum/photo_18_47_29_69.jpg
But when I tried to save the image from bytes it appears in the folder but never appears in the gallery. After saving the image I tried of course to scan the newly created path but there was no effect
First attempt
File.WriteAllBytes("/storage/emulated/0/Android/data/com.companyname.appname/files/Pictures/MyAlbum/downloaded_image_223213a3as.jpg", immageBytes);
MediaScannerConnection.ScanFile(Application.Context, new string[] { path },null,null);
Second attempt using obsoleted Android methods
Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
string path = System.IO.Path.Combine(storagePath.ToString(), filename);
System.IO.File.WriteAllBytes(path, imageByte);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
CurrentContext.SendBroadcast(mediaScanIntent);
Update:
Basically you need to use this method and save it
private void SaveImageToStorage(Bitmap bitmap)
{
Stream imageOutStream;
if (Build.VERSION.SdkInt >= BuildVersionCodes.Q)
{
ContentValues values = new ContentValues();
values.Put(MediaStore.IMediaColumns.DisplayName,
"image_screenshot.jpg");
values.Put(MediaStore.IMediaColumns.MimeType, "image/jpeg");
values.Put(MediaStore.IMediaColumns.RelativePath,
Android.OS.Environment.DirectoryPictures + Java.IO.File.PathSeparator + "AppName");
Android.Net.Uri uri = this.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values);
imageOutStream = ContentResolver.OpenOutputStream(uri);
}
else
{
String imagesDir =Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).ToString() + "/AppName";
imageOutStream = File.OpenRead(System.IO.Path.Combine(imagesDir, "image_screenshot.jpg"));
}
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, imageOutStream);
imageOutStream.Close();
}
OG Answer:
As far as I know, Only images in your media store provider are visible to your gallery and to add it to the media store you need to use the following:
MediaStore.Images.Media.InsertImage(Activity.ContentResolver, ImgBitmap, yourTitle , yourDescription);
Hope this helps :)
I am creating an app where every time press the download button it's create a pdf file in my storage.My problem is newly created file overwrites the existing file with same file name.I need to download with new filename.What i am trying
dirpath =
android.os.Environment.getExternalStorageDirectory().toString();
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");}
This above lines of program create files but i need to open the last download file
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf"));
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
These above lines of code generate an error.
Error:File no longer exist,the file maybe deleted or changed or
removed by another program
1.create a new file and prevent overwiting whenever i click the button
2.open the last downloaded file
I am new to Android and little confused about that and kindly need some help from you guys.
You call Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf")); for open file, so why you added /NewPDF.pdf because its already in your file. just remove it.
Replace this line
Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf"));
to
Uri uri = Uri.fromFile(new File( file));
You are assigning the same name to every file you create. Try giving a unique name like this:
UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();
the randomUUIDString will be your unique string for the pdf files. Also, store these strings in a SQLite db if you wish to use them.
The path you have entered in intent not matching with the created file path.
Try this.
dirpath = android.os.Environment.getExternalStorageDirectory().toString();
String lastFilePath = null;
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");}
lastFilePath = file.getAbsolutePath();
Then you can open the file like this.
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(lastFilePath));
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Hope it helps:)
Replace if with while and display Intent:
dirpath = android.os.Environment.getExternalStorageDirectory().toString();
int increase = 0;
file = new File(dirpath+"/NewPDF.pdf");
while(file.exists()) {
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");
}
file.createNewFile();
... store data in file here ...
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Use Time stamp instead of Counter, so that you can create a new file every time.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);
Date timeStamp = new Date();
dirpath =
android.os.Environment.getExternalStorageDirectory().toString();
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +formatter.format(timeStamp )+".pdf");}
I am making a photo app in which in the first activity the user takes a picture (he can see the picture in the ImageView), in the second activity he chooses with who to share the image,and in the 3rd activity he should be able to see the image again in a different ImageView than the first to add some data. I know how to move the bitmap from one activity to the next one by an intent, but how to do it if i want to send it to the 3rd activity of my user path? If i startActivity(intent) it will skip my second activity and if i don´t put it the 3rd activity is showing me an empty ImageView.. Can someone please help me in telling me ways of how to automatically load (without user interaction) this picture in the 1st and 3rd activity and some example?
I already being reading posts about how to convert to Base64 and load again, but their examples are using images already in the memory of the phone and in my case are pictures that were just taken by the user, so in principle i don´t know the name of the image file..
Thank a lot!
Add This Image In Your Custome Catch Folder
Like Make Your Folder in External or Internal Storage
Then Save Image that will capture by camera inside That Folder..
public static void SaveImagecatch(Bitmap finalBitmap) throws IOException {
File Folder = new File(Environment.getExternalStorageDirectory() + "/data/Catch");
if (Folder.mkdir()) {
nomediaFile = new File(Environment.getExternalStorageDirectory() + "/data/Catch/" + NOMEDIA);
if (!nomediaFile.exists()) {
nomediaFile.createNewFile();
}
}
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/data/Catch");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
Catch_uri = Uri.parse("file://" + myDir + "/" + fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Log.e("yes", "yes");
} catch (Exception e) {
e.printStackTrace();
Log.e("no", "no");
}
}
Then.. get Image From Uri path of Your saved Image.
Uri imageUri = Catch_uri;
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
Imageview my_img_view = (Imageview ) findViewById (R.id.my_img_view);
my_img_view.setImageBitmap(bitmap);
This is Worked For Me.. I Hope This Will be Helpfull to you
Actually in second activity, you need to get Intent from first activity and do your work and then create new Intent and put your image into it, finally start third activity using new intent.
in second activity:
Intent firstToSecodeIntent = getIntent();
// some codes
Intent secondToThirdIntent = new Intent(this, ThirdActivity.class);
Intent.putExtra("image", /*your Image object*/);
startActivity(secondToThirdIntent);
in third activity:
Intent secondToThirdIntent = getIntent();
// get your image and set it into your imageView
Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(video_path+".***"), "video/*");
startActivity(tostart);
Let's say I have a file path
/mnt/sdcard/video/my_birthday_moovie001
'my_birthday_moovie001' can be either .mkv, .mpg or .mkv. I've tried to add ".***" to the file path but I still can't open the file.
Well i read the comments you have stored your path in db without extensions there are many extensions that exists so android cant automatically pick the extension you have to create some way to detect extension.
following is a robust way that is best match in your case but not recommended in proper cases where extensions are known
public String chk_path(String filePath)
{
//create array of extensions
String[] ext=new String[]{".mkv",".mpg"}; //You can add more as you require
//Iterate through array and check your path which extension with your path exists
String path=null;
for(int i=0;i<ext.Length;i++)
{
File file = new File(filePath+ext[i]);
if(file.exists())
{
//if it exists then combine the extension
path=filePath+ext[i];
break;
}
}
return path;
}
now to play a song in your code
if(chk_path(video_path)!=null)
{
Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(video_path), "video/*");
startActivity(tostart);
}
else
//tell user that although the path in database but file on this path do not exists
Well as I put on comments
You could compare if the path matches with any filename(it doesn't contains the extension) and then if it does you got it.
You can simply do this :
Get the directory path
File extStore = Environment.getExternalStorageDirectory();
Set the file name my_birthday_moovie001 on my example I put unnamed but change it as your like
String NameOfFile = "unnamed";
Add the videos, I put it Downloads but you can change it
String PathWithFolder = extStore + "/Download/";
Create a method that lists all the files from your path
private List<String> getListFiles(File parentDir) {
ArrayList<String> inFiles = new ArrayList<String>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
String AbsolutePath = file.getAbsolutePath();
//Get the file name ex : unnamed.jpg
String nameofFile = AbsolutePath.substring(AbsolutePath.lastIndexOf("/") + 1, AbsolutePath.length());
//Remove the .jpg --> Output unnamed
String fileNameWithoutExtension = nameofFile.substring(0, nameofFile.lastIndexOf('.'));
//Add each file
inFiles.add(fileNameWithoutExtension);
}
}
return inFiles;
}
You got the names of the files doing this
List<String> files = getListFiles(new File(PathWithFolder));
Simply add a for that looks for a match of your file
for (int i = 0; i<=files.size()-1; i++){
if(PathWithFolder.equals(files.get(i))) {
Toast.makeText(MainActivity.this, "You got it!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "You don't.", Toast.LENGTH_SHORT).show();
}
}
If you want to get the path as well and do what #Zain Ul Abidin proposed and compare it on getListFiles() method add this :
String fileExtension = nameofFile.substring(nameofFile.lastIndexOf("."));
Hope it helps.
From the other question :
Consider DirectoryScanner from Apache Ant:
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
You'll need to reference ant.jar (~ 1.3 MB for ant 1.7.1).
And then, run on files array and check
if files[i].include(yourfile)
yourfile= files[i]
You may try in this way , first getting the name of file and extension then finally compare and implement. like this :
Example file name is 04chamelon and extension is .png:
File f = new File("/mnt/storage/sdcard/Pictures/04chameleon");
File yourDir = new File("/mnt/storage/sdcard/Pictures");
nametwo = f.getName();
for (File fa : yourDir.listFiles()) {
if (fa.isFile())
fa.getName();
String path = fa.getName(); // getting name and extension
filextension = path.substring(path.lastIndexOf(".") + 1); // seperating extension
name1 = fa.getName();
int pos = name1.lastIndexOf(".");
if (pos > 0) {
name1 = name1.substring(0, pos);
}
}
if (name1.equals(nametwo)) {
Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(f + "." + filextension), "image/*");
//tostart.setDataAndType(Uri.parse(f + "." + filextension), "video/*");
startActivity(tostart);
}
With the latest ContentResolver, you can easily make this work using the contentResolver.getType(uri) function which detects the filetype.
private fun getIntentForFile(intent: Intent, filePath: String, context: Context): Intent {
val uri = FileProvider.getUriForFile(
context,
context.applicationContext.packageName + ".fileprovider",
File(filePath)
)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(uri, context.contentResolver.getType(uri))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent
}
I am trying to save an image from my application to the default gallery of my phone. The code below works perfectly if I have a SD card on the phone. The image saved appears in the phone's gallery and everything, as expected:
private Uri saveMediaEntry(File f, String title, String description, int orientation, Location loc) {
ContentValues v = new ContentValues();
v.put(Images.Media.TITLE, title);
v.put(Images.Media.DISPLAY_NAME, title);
v.put(Images.Media.DESCRIPTION, description);
v.put(Images.Media.ORIENTATION, orientation);
String nameFile = f.getName();
File parent = f.getParentFile() ;
String path = parent.toString().toLowerCase() ;
String nameParent = parent.getName().toLowerCase() ;
v.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
v.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, nameParent);
v.put(Images.Media.SIZE,f.length()) ;
if( nameFile.toLowerCase().contains(".png") ){
v.put(Images.Media.MIME_TYPE, "image/png");
}else if( nameFile.toLowerCase().contains(".jpg") ||
nameFile.toLowerCase().contains(".jpeg") ){
v.put(Images.Media.MIME_TYPE, "image/jpeg");
}else{
v.put(Images.Media.MIME_TYPE, "image/jpeg");
}
String imagePath = f.getAbsolutePath();
v.put("_data", imagePath) ;
ContentResolver c = getContentResolver() ;
Uri uriOfSucessfulySavedImage = null;
uriOfSucessfulySavedImage = c.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, v);
return uriOfSucessfulySavedImage;
}
However, if I try to save the same image into the internal storage (for when the phone does not have a SD card), the image does not appear in the phone's gallery! To try to do that, I only change one line from the above code:
uriOfSucessfulySavedImage = c.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, v);
The interesting thing about this, however, is that the variable uriOfSucessfulySavedImage is not null (it returns content://media/internal/images/media/x, where 'x' is a number). So, the image is being saved somewhere in the internal storage of the phone, but it is not getting displayed in the phone gallery's as when I use MediaStore.Images.Media.EXTERNAL_CONTENT_URI.
Does anybody have any clue what is going on? How can I save an image into the internal storage of the phone and have that image in the phone's gallery?
Update
I forgot one important information. The File "f" in the parameters of the method "saveMediaEntry" is coming from this other method for when the SD card is mounted (that is, for the first code):
public static File getCacheDirectory(String desiredNameOfTheDirectory){
File fileCacheDir = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ){
fileCacheDir = new File( Environment.getExternalStorageDirectory(), desiredNameOfTheDirectory );
}
if(!fileCacheDir.exists()){
fileCacheDir.mkdirs();
}
return fileCacheDir;
}
and from the following code for when the SD card is not founded:
public static File getCacheDirectory(String desiredNameOfTheDirectory, Context context){
File fileCacheDir = null;
fileCacheDir = context.getCacheDir();
if(!fileCacheDir.exists()){
fileCacheDir.mkdirs();
}
return fileCacheDir;
}
Another easy way to do it. Add this after saving your file.
File imageFile = ...
MediaScannerConnection.scanFile(this, new String[] { imageFile.getPath() }, new String[] { "image/jpeg" }, null);
I haven't tried this, but I believe you need to run the Media Scanner to scan the internal storage directory so that the gallery can see your newly saved image. Check this post here.
Copy Past this Function in your Activity
private void scanner(String path) {
MediaScannerConnection.scanFile(FrameActivity.this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
And then add this Line where you save your image
scanner(imageFile.getAbsolutePath());
Try this.
Write down this line once image stored in gallery.
File file = ..... // Save file
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}