Reputation: 659
I just don't understand what's going on here.
ArrayList<ListItem> list=new ArrayList<ListItem>();
ListItem curItem=new ListItem();
String[] contents=cwFile.list();
for(int i=0;i<contents.length;i++){
curItem.itemName = contents[i];
if(new File(cwd+contents[i]).isDirectory()){
curItem.isDir=true;
}
list.add(i,curItem);
}
Log.i("Main",list.get(0).itemName);
Log.i("Main",contents[0]);
So in this code snippet, I get the contents of a directory using the File.list() method
Then, I store the names in an ArrayList
of ListItem
objects, where ListItem
is a self-created class.
But, ListItem
is just a class that stores the string
class ListItem {
protected String itemName ="";
protected boolean isDir=false;
protected Double size=0.0;
}
However, after logging the first elements of both the array and the ArrayList
(last 2 lines of the first code snippet), I get different results!
This is the log output:
03-15 20:29:46.427 465-465/com.harshal.filer I/filer: .userReturn
03-15 20:29:46.427 465-465/com.harshal.filer I/filer: Android
The second output,"Android" is an actual directory on the device. But what's ".userReturn" and where did it come from???
Upvotes: 0
Views: 210
Reputation: 2066
Change your code to the following:
ArrayList<ListItem> list=new ArrayList<ListItem>();
String[] contents=cwFile.list();
for(int i=0;i<contents.length;i++){
ListItem curItem=new ListItem();
curItem.itemName = contents[i];
if(new File(cwd+contents[i]).isDirectory()){
curItem.isDir=true;
}
list.add(i,curItem);
}
Log.i("Main",list.get(0).itemName);
Log.i("Main",contents[0]);
You see I moved
ListItem curItem=new ListItem();
into the for-loop. If it's outside the reference of the item at position 0 in the list will always point to the latest entry in your array, thus the weird result.
Upvotes: 2