i am facing 3 problems with my ArrayList. It reads without any problem files from my sdcard.
Files have this structure:
1.3.2016.csv
2.3.2016.csv
29.2.2016.csv
30.2.2016.csv
4.2.2016.csv
Here is my method to read files from sdcard:
private List<String> getList(File parentDir) {
ArrayList<String> inFiles = new ArrayList<String>();
String[] fileNames = parentDir.list();
for (String fileName : fileNames) {
if (fileName.toLowerCase().endsWith(".csv")) {
inFiles.add(removeLastChar(fileName));
} else {
File file = new File(File.separator + fileName + ".csv");
if (file.isDirectory()) {
inFiles.addAll(getList(((file))));
}
}
}
itemTexte.addAll(Arrays.asList(fileNames));
return inFiles;
}
private static String removeLastChar(String str) {
return str.substring(0,str.length()-4);
}
And here is what i call from onCreate:
List<String> files = getList(new File(Environment.getExternalStorageDirectory() + File.separator + "Test" + File.separator + "Files"));
First problem. I don't want to see the ".csv" in my recycler view. So i try to remove 4 chars from it (see removeLastChar method). But it stays at ".csv" at the end no matter what i do.
I want to order the recycler view, by the name of the files. For now it does not order it by the name. I tried the method Comparator, but i didn't understood how, i should parse my elements there.
Even if my files don't have the ending ".csv", they are still shown in the recycler view. Looks like it catch all files that are in the folder.
UPDATE I can sort my list with this(thanks guys):
Collections.sort(inFiles);
But it sorts kind of wrong... Example:
1.3.2016
10.2.2016
11.4.2016
2.3.2016
3.3.2016
But it should be something like this:
10.2.2016
1.3.2016
2.3.2016
3.3.2016
11.4.2016
Is there any easy fix? Or should i implement writing "0" to the files when user create it?
UPDATE 2
So i added this
Collections.sort(inFiles, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
String[] s1Values = s1.split(".");
String[] s2Values = s1.split(".");
//define your comparison, arrays will have each value between '.', e.g. {"1", "3", "2016", "csv" } for "1.3.2016.csv"
int compare_result = s1.compareTo(s2);
return compare_result; //return -1 if s1 < s2, 0 if equal, 1 if s1 > s2
}
});
My list looks like this
01.04.2016
02.04.2016
15.04.2016
16.03.2016
But the 16.03.2016 should be first... Thanks for help in advance!