I am using following code to find last created files.
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
ArrayList<File> fileArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileArrayList = new ArrayList<>();
textView = (TextView) findViewById(R.id.tv);
final String dir = String.valueOf(Environment.getExternalStorageDirectory());
Log.d("Directory Path",dir);
fileArrayList = listf(dir,fileArrayList);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
File lastModified = lastFileModified(fileArrayList);
textView.setText(lastModified.getPath());
}
});
}
public static File lastFileModified(ArrayList<File> fileArrayList) {
long lastMod = Long.MIN_VALUE;
File choice = null;
for (File file : fileArrayList) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
return choice;
}
public ArrayList<File> listf(String directoryName, ArrayList<File> files) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
return files;
}
}
The above code gives me some random last created file. But I want last created audio file. Also the audio file created should be most recent either from Internal storage or external storage. Please help. Thank You.
I took a look at your code. Please do the following changes, it works for me.