Multiple image delete

125 views Asked by At

I have a group of images that users upload in my app. I store the image path in an sqlite database and the image in the internal storage of the app. I was able to go around deleting a single image if the user selects it and chooses to delete it. My problem now is that I have a clear all button sort of, that is meant to clear a particular group of images. How do I loop around this?

1

There are 1 answers

0
Qadir Hussain On

Here I have made a asynTask class for deleting multiple files at once.

private class DeleteFilesAsync extends AsyncTask<String, Integer, Integer> {

    ProgressDialog mProgressDialog;
    ArrayList<String> fileNames = new ArrayList<String>();

    public DeleteFilesAsync(ArrayList<String> fileNames) {
        this.fileNames = fileNames;
    }

    @Override
    protected void onPreExecute() {

        try {

            mProgressDialog = new ProgressDialog(
                    SavedImageListingActivity.this);
            mProgressDialog.setMessage("deleting...");
            mProgressDialog.show();

        } catch (Exception e) {
            // TODO: handle exception
        }

        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(String... params) {

        for (int i = 0; i < fileNames.size(); i++) {

            String fileName = fileNames.get(i);

            File file = new File(fileName);
            if (file.exists()) {
                if (file.isFile()) {
                    file.delete();
                    onProgressUpdate(i);
                }
            }

        }

        return null;
    }

    @Override
    protected void onPostExecute(Integer result) {

        try {

            mProgressDialog.dismiss();
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Do more here after deleting the files

        super.onPostExecute(result);
    }

}

How to use it

new DeleteFilesAsync(imgFilesSelected).execute("");

Where imgFilesSelected is type ArrayList<String> Add all files path in imgFilesSelected list like

imgFilesSelected.add("my_path_dir/filename.jpg");
imgFilesSelected.add("my_path_dir/filename2.png");
imgFilesSelected.add("my_path_dir/filename3.png"); // etc

then pass it to DeleteFilesAsync() class contructor as shown above.

All done.