我想将照片&文件夹中的所有项目添加到arraylist,以下是我的代码 -
这是我的模特
public class Model {
private String image;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
这是我的活动
public class MainActivity extends Activity {
private Model model;
private ArrayList<Model> alPhoto;
private File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alPhoto = new ArrayList<Model>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd + "/photo/");
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
// alPhoto.add(list[i].getName());
model = new Model();
model.setImage(alPhoto.get(i).getImage());
alPhoto.add(model);
Log.e("Load image from sd card******* : ", "Loading...." + alPhoto.get(i));
}
}
}
答案 0 :(得分:1)
最后我得到了解决方案。
for (int i = 0; i < list.length; i++)
{
String strPath = list[i].getAbsolutePath();
Log.e("Checking path",">>"+strPath);
Model model = new Model();
model.setImage(strPath);
alPhoto.add(model);
Log.e("Checking arraylist",">>"+alPhoto);
}
答案 1 :(得分:0)
问题在于你的循环。你是全局声明模型所以只添加列表中的最后一项是你的问题,而不是在for循环中本地声明
for (int i = 0; i < list.length; i++) {
// alPhoto.add(list[i].getName());
Model model = new Model();
model.setImage(alPhoto.get(i).getImage());
alPhoto.add(model);
Log.e("Load image from sd card******* : ", "Loading...." + alPhoto.get(i));
}