I want to delete image from gallery that was most recently captured. I have followed a couple of SO questions, but nothing seems to work. Can anyone give me a simple code that works?
Sample code:
public void deleteImage() {
File f = new File("/storage/emulated/0/Pictures");
File [] files = f.listFiles();
Arrays.sort(files, new Comparator<File>() {
#Override
public int compare(File a, File b) {
if (a.lastModified() < b.lastModified())
return 1;
if (a.lastModified() > b.lastModified())
return -1;
return 0;
}
});
files[0].delete();
}
This code sorts the files in gallery folder by time of last modification, and delete the most recent file.
Related
How do i get the list of all saved text files in (storage/emulated/0/Notes, in this case "Notes" is my folder where all my saved text files are located) and make them available in a new activity(generate a textView for every single file to be printed). i want all this to happen when for instance an "Open" button is clicked. THANKS in advance.
Try this code..
// take below variable as global level of class
public List<String> filesNames=new ArrayList<>();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// gets the files in the directory it fatch internal storage
File fileDirectory = new File(Environment.getDataDirectory()+"/YourDirectory/");
// below code for fatch sd card files on define folder;
File fileDirectorySD = new File(Environment.getExternalStorageDirectory()+"/YourDirectory/");
// lists all the files into an array
File[] dirFiles = fileDirectory.listFiles();
if (dirFiles.length != 0) {
// loops through the array of files, outputing the name to console
for (int ii = 0; ii < dirFiles.length; ii++) {
String fileOutput = dirFiles[ii].toString();
filesNames.add(fileOutput);
System.out.println(fileOutput);
}
}
}
});
and if you are run app in marshmallow above device then give read permission and also handling permission model..
I need to randomly select an image from a user's photo gallery. I don't mean starting an intent as in
Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, GALLERY_PHOTO_REQUEST_CODE);
No. I need to randomly select the image myself. Is there an efficient way to do this? Or do I have to actually read in all the image files and then randomly select a file, and then from the file get the image? By read all files, I mean with something as (snippet: I have a question not an answer)
void addFiles(final File parent, Set<File> images) {
try {
for (final File file : parent.listFiles()) {
if (!file.getParent().contains("Android")) {
if (!file.isDirectory()) {
if (isImageFile(file.getName())) {
images.add(file);
}
} else {
addFiles(file, images);
}
}
}
} catch (Exception e) {
}
}
Please don't be too concerned with the code snippet. If I knew the best way, I would not be asking for help. Does anyone know an efficient way of doing this?
I don't know your code aside from the snippets. Unless you have a large number of files, you could very well read all the files into an array. Then generate a random number with 0 as lowest and arrayList.size()-1 as highest and get that index from the array.
Pseudo code:
private static Random random = new Random();
ArrayList<File> list = readFiles();
File randomFile = list.get(getRandomValue(0, list.size()-1));
...
public static int getRandomValue(int low, int high) {
return random.nextInt((high - low) + 1) + low;
}
im trying to make folder browser for my app, but i have error that throws me out of browser activity. When activity is started , it shows root folder with all folders in it, then I can click on one of the folders, and it opens and shows all folders in it, and after that, if i click on something, ive got error,also variable File[] filenames is null after last click. So method getFileFromList(String path) works fine 2 times and crashes on 3rd. And i dont have any errors in console. Whats wrong with my code?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fflist);
pathtext = (TextView) findViewById(R.id.pathtext);
getFileFromList("/");
registerForContextMenu(getListView());
}
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.d(LOG_TAG, String.valueOf(position));
String clickedItem = neededFilenames.get(position);
getFileFromList(clickedItem);
}
public void getFileFromList(String path) {
Log.d(LOG_TAG, path);
neededFilenames = new ArrayList<String>();
File dir = new File(path);
File[] filenames = dir.listFiles();
Log.d(LOG_TAG, String.valueOf(filenames));
if (filenames != null) {
for (int i = 0; i < filenames.length; i++) {
if (filenames[i].isDirectory() && !filenames[i].isHidden() && filenames[i].canRead()) {
neededFilenames.add(filenames[i].getName());
}
}
Log.d(LOG_TAG, String.valueOf(neededFilenames));
} else Toast.makeText(this, "something wrong", Toast.LENGTH_SHORT).show();
Collections.sort(neededFilenames);
pathtext.setText("Location: /" + path);
FileFolderAdapter adapter = new FileFolderAdapter(this, neededFilenames);
setListAdapter(adapter);
}
actually i found out, that this "browser" only works in the root folder and 1 click out of it< because at the begining, when you using only items names,you have legit "path" to root- "/" , and after 1 click you will get "path" variable as - " /folder" and that still is legit path to folder, after 2 click on any folder in that first folder, you just have only that folder name "folder", without all path to root "/", so you cant make new File only out of name without having full path from root. not sure if its understandable enough, but maybe it helps someone :)
In my application, when a user want to upload Audio, that user should only be able to choose .mp3 extension file. If the user choose any other file like .ppt, .pdf, it wont be allowed.
I have got this approved code for File explore from SD Card: Choose file dialog.
But I want only .mp3 extension files or list of .mp3 extension files.
So what should I do?
maybe you can check for files like this
File f = new File("/sdcard/");
for (File file : f.listFiles())
{
if(file.getName().endsWith(".mp3"))
{
// do something with them, add them to list or whatever
}
}
Check file pattern and then compare, if it is mp3 then add into arraylist, check below function, which will return list of mp3.
Vector<String> mStrings =new Vector<String>();
int mTotalimage=0;
public void fileExtension(File dir) {
String mp3Pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
String mCheck=listFile[i].getAbsoluteFile().toString();
mCheck=mCheck.substring(mCheck.lastIndexOf("/")+1);
System.out.println("listFile[i].getAbsoluteFile().toString()"+listFile[i].getAbsoluteFile().toString());
System.out.println("mCheck..."+mCheck);
if (listFile[i].isDirectory() && !(mCheck.startsWith(".")) ) {
fileExtension(listFile[i]);
} else {
//fetch jpg from folders.
if (listFile[i].getName().endsWith(mp3Pattern)){
mStrings.add(listFile[i].getAbsolutePath().toString());
mTotalimage++;
//fetch png image from folders.
}
}
}
}
System.out.println("size on return......."+mStrings.size());
}
I want to read all the music files from the sd card but I tried to put the file in several places on the SD card and the program still doesn't find the music on the card. Anyone any suggestions? Where exactly to put the files?
I was just doing that last night :).
In android, the sdcard is mounted on '/sdcard'. I don't have the code here, but it was something like this.
public List<String> getMp3Files() {
File sdcard = new File("/sdcard");
return getMp3Files(sdcard);
}
private List<String> getMp3Files(File directory) {
List<String> mp3files = new ArrayList<String>();
File[] files = directory.listFiles();
if(files == null) {
return Collections.EMPTY_LIST;
}
for( File file : files) {
if( file.isFile() && file.getName().toLowerCase().endsWith(".mp3")) {
mp3files.add(file.getAbsolutePath());
} else if ( file.isDirectory()) {
mp3files.addAll(getMp3Files(file));
}
}
return mp3files;
}
it's not optimized AT ALL for mobiles, but it works. And be careful that if you run this code starting on the root folder, it will end up in a infinite loop of folders! (you can always try :D).
Maybe this could help you
http://blog.jayway.com/2009/04/22/working-with-sd-cards-in-the-android-emulator/