How to delete file from storage - android

I have a content menu where it is pop up a menu of rename and delete when you press the item in few seconds. But i dont know how to get the correct directory of one file. Here is my code:
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.rename:
// edit stuff here
return true;
case R.id.delete:
File dir = new File(Environment.getExternalStorageDirectory()+"/Music/MusicPlayer");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
// remove stuff here
return true;
default:
return super.onContextItemSelected(item);
}
}

Use below util function to either delete File or Directory.
public static boolean delete(File path) {
boolean result = true;
if (path.exists()) {
if (path.isDirectory()) {
for (File child : path.listFiles()) {
result &= delete(child);
}
result &= path.delete(); // Delete empty directory.
} else if (path.isFile()) {
result &= path.delete();
}
return result;
} else {
return false;
}
}
Usage:
File dir = new File(Environment.getExternalStorageDirectory()+"/Music/MusicPlayer");
delete(dir);

use below function to delete file from Folder, just pass folder path in perameter like
File fDir = new File(PERENT_PATH);
DeleteRecursive(fDir);
// where PERENT_PATH = Environment.getExternalStorageDirectory()+"/folderName"
public static void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
DeleteRecursive(child);
if (fileOrDirectory.exists()) {
boolean b = fileOrDirectory.delete();
if (b) {
Log.e( "delete dir", "delete dir");
} else {
Log.e( "not delete dir", "not delete dir");
}
}
}

Please check the Below code
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
.........
case R.id.delete:
deleteDirectory(Environment.getExternalStorageDirectory()+"/Music/MusicPlayer");
.........
}
}
static public boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return( path.delete() );
}

Instead of use String[] children = dir.list() try to use:
File dir = new File(PATH);
File[] children = dir.listFiles();
for(int i = 0; i < children.length; i++) {
children[i].delete();
}

Related

String[] array not working properly

i have a Problem with String[] array.I refer about this from Here
& Here
But still, i have not found any solution from the link.
What I want:
I am developing a Custom Camera App.I have a Folder in which I am saving a Captured images.also, i have 1 ImageView. when my App Launched the Image [or Bitmap] of Folder is set into that ImageView (Always set the First image of the folder into ImageView).
Following is my Code.
private void loadImageInImageView() {
Uri[] mUrls;
String[] mFiles = new String[0];
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (mFiles.length >= 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
mFiles = new String[imageList.length];
for (int i = 0; i < imageList.length; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for (int i = 0; i < mFiles.length; i++) {
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
}
in Above code [when Folder is Empty] :
When i set if (mFiles.length > 0)
it shows me an Error
Error: Attempt to get length of null array
When i set if (mFiles.length >= 0)
Then it shows me same as Above Error.
When i set if (mFiles == null)
it is also not Working because I have initialized String[] in above code.
String[] mFiles = new String[0];
Hence it also not work.
When I have some Images then it working Fine.because it executed the else part.
what should I do?Whenever my Folder is Empty then it Shows me a Toast.otherwise my else code will be executed.
Any help will be Highly appreciated.
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (imageList.length = 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
String[] mFiles = new String[imageList.length];
for (int i = 0; i < imageList.length; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for (int i = 0; i < mFiles.length; i++) {
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
If the function you want works when the size of the imageList is greater than zero, try below code.
private void loadImageInImageView() {
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
// conditional operator [ ? : ]
// value = (experssion) ? value if true : value if false
// ref : https://www.tutorialspoint.com/java/java_basic_operators.htm
int imgLength = imageList == null ? 0 : imageList.length;
if(imgLength > 0)
{
String[] mFiles = new String[imgLength];
Uri[] mUrls = new Uri[imgLength];
//merge for condition
for (int i = 0; i < imgLength; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
else
{
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
}
}
Do not initialize mFiles. Initialize it in the moment when you add some data.
And for checking if it isn't empty use this:
if (mFiles != null && mFiles.length > 0) {
...
}
private void loadImageInImageView() {
Uri[] mUrls;
File[] imageList
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (imagelist==null && imageList.length == 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < imageList.length; i++) {
imgBtnThumbnail.setImageURI(Uri.parse(imageList[i].getAbsolutePath()););
}
}
}
try this;
but your image changes continuously because of for loop;

Android clearing app cache clears provider also

I used following code to delete my app cache.
public void clearApplicationData() {
File cacheDirectory = getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
if (applicationDirectory.exists()) {
String[] fileNames = applicationDirectory.list();
for (String fileName : fileNames) {
if (!fileName.equals("lib")) {
deleteFile(new File(applicationDirectory, fileName));
}
}
}
}
public static boolean deleteFile(File file) {
boolean deletedAll = true;
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
}
} else {
deletedAll = file.delete();
}
}
return deletedAll;
}
Once I delete the code means it deletes the provider which I declared in manifest. Is there any way to clear cache without deleting content provider?
You can avoid this by not deleting database folder
if (!fileName.equals("lib")&&!fileName.equals("files")&&!fileName.equals("database")) {
deleteFile(new File(applicationDirectory, fileName));
}

I want to make a function that will display only folders that contains images / mp3 / audio

What I want here is to display only the folders and subfolders that contains images or videos or mp3.
for (int i = 0; i < fileList.size(); i++) {
TextView textView = new TextView(this);
textView.setText(fileList.get(i).getName());
textView.setPadding(5, 5, 5, 5);
System.out.println(fileList.get(i).getName());
if (fileList.get(i).isDirectory()) {
textView.setTextColor(Color.parseColor("#000000"));
}
view.addView(textView);
}
}
public ArrayList<File> getfile(File dir) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (((sel.isFile() || sel.isDirectory()) && !sel.isHidden()));
//...
}
};
File listFile[] = dir.listFiles(new ImageFileFilter());
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
fileList.add(listFile[i]);
getfile(listFile[i]);
} else {
if (listFile[i].getName().endsWith(".png") || listFile[i].getName().endsWith(".JPG") || listFile[i].getName().endsWith(".jpeg") || listFile[i].getName().endsWith(".gif") || listFile[i].getName().endsWith(".mp3")) {
//fileList.add(listFile[i].getParentFile());
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
I tried the functions below but it still display the folders that doesn't include images or videos or mp3
private boolean isImageFile(String filePath) {
if (filePath.endsWith("JPG") || filePath.endsWith("PNG") || filePath.endsWith(".mp3"))
// Add other formats as desired
{
return true;
}
return false;
}
private class ImageFileFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
}
In your accept function, you have the code return (((sel.isFile() || sel.isDirectory()) && !sel.isHidden()));
Instead of returning true if sel.isDirectory, you'd need to search all files in that directory and look for media files in it, and return true only if one is found. This would turn your algorithm into a recursive one which may have issues if you use symbolic links in your filesystem- you'll have to beware of loops. It may also cause performance issues.

Deleting older images from external storage after a limit

I have implemented offline caching in my app and for that I am storing images in external storage.I want that once my cached images folder limit reaches 30 then it starts replacing the older images with new ones.For that i implemented following deletion algorithm-
public static boolean deleteDir(File dir)
{
if (dir != null && dir.isDirectory())
{
String[] children = dir.list();
if(children.length>30)
{
int exceed=children.length-30;
for (int i = 0; i <exceed; i++)
{
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
{
return false;
}
else
{
Log.e("deleted","file deleted");
}
}
}
}
return dir.delete();
}
But the above algorithm doesn't work as expected.It might deletes the newly added images.I also tried implementing below algorithm.But it also not working as expected.I failed to understand where I am going wrong.
public static boolean deleteDir(File dir)
{
if (dir != null && dir.isDirectory())
{
String[] children = dir.list();
if(children.length>30)
{
int exceed=children.length-30;
int destroy=(children.length-exceed)-1;
for (int i = children.length; i >destroy; i--)
{
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
{
return false;
}
else
{
Log.e("deleted","file deleted");
}
}
}
}
return dir.delete();
}
Try this
public static void deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
File[] files = dir.listFiles();
if (files.length > 30) {
Arrays.sort(files, new Comparator<File>() {
#Override
public int compare(File o1, File o2) {
if (o1.lastModified() > o2.lastModified()) {
return 1;
} else if (o1.lastModified() < o2.lastModified()) {
return -1;
}
return 0;
}
});
for (int i = 0; i < files.length - 30; i++) {
files[i].delete();
}
}
}
}

android multichoicemodelistener delete internal storage file

In my app i have a Listview where multichoicemodelistener is enabled. I want to delete the internal storage files (files that is shown in my listview) using multichoicemodelistener. But with no luck.
Here is my code
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.list_context_delte:
SparseBooleanArray sparseBooleanArray = getListView().getCheckedItemPositions();
for(int i = sparseBooleanArray.size() -1; i >= 0; i--)
context.deleteFile(sparseBooleanArray.keyAt(i));
mAdapter.notifyDataSetChanged();
mode.finish();
Toast.makeText(ShowListActivity.this, R.string.deleted, Toast.LENGTH_SHORT).show();
mode.finish();
}
return false;
}
I got an Error that says: The method deleteFile(String) in the type Context is not applicable for the arguments (int)
Any ideas ?
UPDATE
I have edited my code, so know it look like
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.list_context_delte:
nr = 0;
SparseBooleanArray sparseBooleanArray = getListView().getCheckedItemPositions();
for(int i = sparseBooleanArray.size() -1; i >= 0; i--)
if (sparseBooleanArray.get(i)) {
String items = getListView().getAdapter().getItem(sparseBooleanArray.keyAt(i)).toString();
File dir = getFilesDir();
File file = new File(dir, (items));
file.delete();
RowItem selecteditem = mAdapter.getItem(sparseBooleanArray.keyAt(i));
mAdapter.remove(selecteditem);
mAdapter.notifyDataSetChanged();
Toast.makeText(ShowListActivity.this,items+ R.string.deleted, Toast.LENGTH_SHORT).show();
}
mode.finish();
}
return false;
}
After I press the delete button, the file(s) is gone. But when I go out of the activity and go back to the activity all the deleted files is back.
Are the files not deleted correctly from the internal storage ?
Does someone have a suggestions?
Assuming that the file exists, looks like your code will delete the file.you can add a line for safety.
if(file.exists()){
boolean isDeleted = file.delete();
Log.v(TAG,"file delection is success : "+isDeleted);
}
I think the actual problem exists here.Its possible that file is actually deleted but you are not refreshing the listview.As soon as you delete the file,delete the item in the adapter and update the list view.Like this:
for(int i = sparseBooleanArray.size() -1; i >= 0; i--)
if (sparseBooleanArray.get(i)) {
String items = getListView().getAdapter().getItem(sparseBooleanArray.keyAt(i)).toString();
File dir = getFilesDir();
File file = new File(dir, (items));
boolean isDeleted = file.delete();
if(isDeleted){
mAdapter.deleteItem(items); // create a method in adapter which will delete the item.
mAdapter.notifyDataSetChanged();
Toast.makeText(ShowListActivity.this,items+ R.string.deleted, Toast.LENGTH_SHORT).show();
}
}
mode.finish();
I finally figure it out.
My code know look like this, and it work perfect about deleting internal storage files
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.list_context_delte:
nr = 0;
SparseBooleanArray sparseBooleanArray = getListView().getCheckedItemPositions();
for(int i = sparseBooleanArray.size() -1; i >= 0; i--) {
if (sparseBooleanArray.get(i)) {
RowItem selecteditem = mAdapter.getItem(sparseBooleanArray.keyAt(i));
String selecteditemString = selecteditem.getFilename().toString();
File dir = getFilesDir();
File file = new File(dir, (selecteditemString));
file.delete();
mAdapter.remove(selecteditem);
mAdapter.notifyDataSetChanged();
}
}
mode.finish();
}
return false;
}

Categories

Resources