Refresh gallery in android kitkat - android

How to refresh gallery the in android kitkat ?
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
I tried with the above, but its not refreshing in android 4.4. How to refresh the gallery when add/delete the images programatically ?

This works for me :)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("folderPATH", "fileName");
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
appContext.sendBroadcast(mediaScanIntent);
} else {
appContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/" + "FOLDER_TO_REFRESH")));
}
Hope it helps :)

You can use following technique to update all files present in a single folder:
for (File child : fileFolder.listFiles()) {
if (child.isFile()) {
fName = child.getName();
Log.d("MyTag", "Scanning >> " + child.getName());
MediaScannerConnection
.scanFile( MyActivity.this,
new String[] { "path/of/our/folder" + fName },
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(
String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
}
Source: here

Use this code to add/ refresh gallery images.
String version = Build.VERSION.RELEASE;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
String mCurrentPhotoPath = "file://"
+ Environment.getExternalStorageDirectory() + "/AppDirectory"; // image
// is
// the
// created
// file
// image
File file = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
} else {
MediaScannerConnection.scanFile(this, new String[] { Environment
.getExternalStorageDirectory().toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
*
* #see android.media.MediaScannerConnection.
* OnScanCompletedListener
* #onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
Log.i(TAG, "Scanned ................" + path);
}
});
}

Related

Image is not showing in gallery after save

Hi I am trying to save image in my gallery but the issue is that, not able to see in my gallery, following is my code can any one help?
public void OnClickSave(View view)
{
Bitmap bitmap =getBitmapFromView(idForSaveView);
try {
ContextWrapper wrapper = new ContextWrapper(context);
File file = wrapper.getDir("MilMilaImages",MODE_PRIVATE);
// Create a file to save the image
file = new File(file, "MilMila"+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e) // Catch the exception
{
e.printStackTrace();
}
// Parse the gallery image url to uri
final Uri savedImageURI = Uri.parse(file.getAbsolutePath());
// Display the saved image to ImageView
System.out.println("HLL"+savedImageURI);
iv.setImageURI(savedImageURI);
MediaScannerConnection.scanFile(context, new String[] { file.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
} else {
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getRootDirectory())));
}
// Display saved image uri to TextView
// Toast.makeText(context,"Saved Successfully",Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
I have used this code and it works for me :
// show the image in the device gallery
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
val contentUri = Uri.fromFile(compressFile) //out is your output file
mediaScanIntent.data = contentUri
this.sendBroadcast(mediaScanIntent)
} else {
sendBroadcast(Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())))
}// // show the image in the device gallery

How to reduce scan time of media using media scanner?

I am using below code to scan media after image deletion but it takes too much time. I want to quickly update my images list after image deletion. How to achieve that?
if (Build.VERSION.SDK_INT >= 14) {
Log.e("-->", " >= 14");
MediaScannerConnection.scanFile(this, new String[]{String.valueOf(Environment.getExternalStorageDirectory())}, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
Log.e("ext str gal", "Scanned " + path + ":");
Log.e("ext str gal", "-> uri=" + uri);
}
});
} else {
Log.e("-->", " < 14");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
I got the answer.Use ContentResolver to scan mediaStore.I hope it helps someone.
public void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
try{
final Uri uri = MediaStore.Files.getContentUri("internal");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[] {canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if(!absolutePath.equalsIgnoreCase(canonicalPath)){
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
//remove thumbnail of deleted image
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getContext().sendBroadcast(mediaScanIntent);
}catch (Exception e){
e.printStackTrace();
}
}

Image is not deleted but file.delete() returning true?

I am trying to delete image from device by using file.delete(). Delete method is being called and even it is returning true but when I open my gallery image is still there.
My image path is :
/data/user/0/com.myappname/app_myappname/20180413__164222_0.7680390806195996.png
Please have a look what i have tried.
1)
File file = new File(path);
if (file.exists()) {
file.delete();
}
2)
try {
File file = new File("file://" + path);
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null
File fileNew = new File(getDirectoryPath);
fileNew.delete();
} catch (Exception e) {
}
3)
File file = mContext.getFilesDir(); // this will get you internal directory path
Log.d("BLA BLA", file.getAbsolutePath());
File newfile = new File(file.getAbsolutePath() + imagePath); // foo is the directory 2 create
newfile.delete();
4)
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
File fileName = new File(data, imagePath);
if (fileName.exists())
{
fileName.delete();
}
}
} catch (Exception e) {
}
I have applied almost every solution from stack overflow related to file.delete(). But nothing is working ? Any help or clue will be appreciated.
Edit:
I have refreshed the gallery when delete() returns true using this method but still image is present in app gallery.
Look at my code:
public void callBroadCast() {
if (Build.VERSION.SDK_INT >= 14) {
Log.e("-->", " >= 14");
MediaScannerConnection.scanFile(mContext, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
} else {
Log.e("-->", " < 14");
mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}

Video not shown on Gallery

I have saved the video on SD card but its not showing in gallery
I can see the video in the sd card and its playing
I am using this method to get video uri and save it
public static Uri getVideoUri(Context context) {
Marapreferences marapreferences=Marapreferences.getInstance(context);
boolean ismedia=marapreferences.isMedia();
File file = null;
File file2 = new File(Environment.getExternalStorageDirectory()
+ "/mara_messenger/videos");
if (!file2.exists()) {
file2.mkdirs();
}
currentFileName = "" + System.currentTimeMillis() + ".mp4";
imageName = Environment.getExternalStorageDirectory()
+ "/mara_messenger/videos/" + currentFileName;
file = new File(imageName);
Uri imgUri = Uri.fromFile(file);
System.out.println("Image uri" + imgUri);
return imgUri;
}
File file=new File(uri);
MediaScannerConnection.scanFile(this, new String[] {file.getAbsolutePath()},
new String[]{"video/mp4"}, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri)
{
System.out.println("completed");
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(uri);
sendBroadcast(intent);
}
});
I can see after scan URI and path but still not showing on gallery

Android: Refreshing the Gallery after saving new images

So in my application I at one point save a bunch of images to a temporary folder, and I want them to show up immediately in the Gallery. Off of a reboot, they do, but otherwise they don't.
I've tried using the sendBroadcast method:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
But I get a permission error:
E/AndroidRuntime( 2628): java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=2628, uid=10068
Could I be missing a permission in my AndroidManifest, or is this just no longer supported? Thanks
Code provided by Petrus in another answer works for me on Kitkat (4.4):
MediaScannerConnection.scanFile(this, new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri)
{
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
I tried Environment.getExternalStorageDirectory().toString(), but it didn't find my custom folder.
I just wanted to share my experience to solving this issue.
At the end, I had MediaScannerConnection configured to scan one file at a time and now missing folder that was holding those images showed up. Every time I download each image, I called MediaScannerConnection and file path as Uri instead of folder itself.
Also, many people asked why sendBroadcast stop working on kitkat and the answer is that sendBroadcast was abused and called too many times and causing system to drain battery or slowdown, so they removed the direct call to prevent abuse which makes sense. I was hoping to use above solution to the folder that hold all images, but it didn't work on the folder. I was hoping that finding folder would expose rest of the files within the custom folder, but it didn't in my case. I am hoping to find better answer in the future...
Here's snippet of my code.
MediaScannerConnection.scanFile(ApplicationContext.context, new String[] { imageFile.getPath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i(TAG, "Scanned " + path);
}
});
Try this one:
after saving your file to folder,write below code
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("your image path"))));
Below code work all device for refreshing the gallery after saving image.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f1 = new File("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f1);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("your image path"))));
Implement MediaScannerConnectionClient and add the below code.Works perfectly in 4.4 :)
MediaScannerConnection conn;
public void startScan(String url) {
imagepath = url;
if (conn != null)
conn.disconnect();
conn = new MediaScannerConnection(activity.this, activity.this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
try {
conn.scanFile(imagepath, getMimeType(imagepath));
} catch (java.lang.IllegalStateException e) {
//Do something
}
}
#Override
public void onScanCompleted(String path, Uri uri) {
conn.disconnect();
}
I know its late but try this can working in all versions:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(out); //out is your file you saved/deleted/moved/copied
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} else {
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}
Use MediaScannerConnection instead of SendBroadcast..
MediaScannerConnection.MediaScannerConnectionClient(
{
#Override
public void onScanCompleted(String path, Uri uri) {
if (path.equals(**your filename**.getAbsolutePath()))
{
Log.i("Scan Status", "Completed");
Log.i("uri: ",uri.toString());
conn.disconnect();
}
}
#Override
public void onMediaScannerConnected()
{
// TODO Auto-generated method stub
conn.scanFile(**your file name**.getAbsolutePath(),null);
}
});
conn.connect();
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
//Gallery Refresh Code
MediaScannerConnection.scanFile(getActivity(), new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri)
{
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
out.close();

Categories

Resources