0

I want to add all item from photo's folder to arraylist and below is my code -

here is my model

public class Model {
    private String image;

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}

here is my activity

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));
        }
    }
}
1
  • i am unable to set image to arraylist as showing array index outof bound. Commented Mar 10, 2016 at 9:57

2 Answers 2

1

Finally I got the solution.

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is in your for a loop. You declare model globally so which is added only the last item in list is your problem instead of declare locally in for loop

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));

    }

2 Comments

Thanks for the answer but still showing error like this. Unable to start activity ComponentInfo{com.example.android.demogridview/com.example.android.demogridview.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Before for loop check with condition list.length>0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.