Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not able to move images to another folder in gallery, using asynctask

I created an image gallery app.

My requirment: I want to select multiple images, click on button cut and come back to activity which displays all folders (ImageGallery.java). Now, I want to select a folder and paste all the selected images in that folder, on selecting the folder.

What is happening? I am able to select images using my app and come back to activity which displays all folders but not able to move them using my app. I put the code for moving images in a background thread using task. I select images from one folder, come back to the activity which displays all the folders (ImageGallery.java) and select the folder to which the images are to be moved. But when I try to move images, selected images do not move to other folder being selected, on selecting a folder. I guess the code inside AsyncTask isn't even getting executed.

How do I fix it ?

PhotosActivity.java (Activity used to select images):

int int_position;
private GridView gridView;
GridViewAdapter adapter;
ArrayList<Model_images> al_menu = new ArrayList<>();
private ArrayList<Integer> mSelected = new ArrayList<>();
boolean boolean_folder;

gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
            if (mSelected.contains(position)) {
                mSelected.remove(position);
                view.setBackgroundColor(Color.TRANSPARENT);// remove item from list
                // update view (v) state here
                // eg: remove highlight
            } else {
                mSelected.add(position);
                view.setBackgroundColor(Color.LTGRAY);// add item to list
                // update view (v) state here
                // eg: add highlight
            }

            buttoncut.setVisibility(View.VISIBLE);
            button2.setVisibility(View.VISIBLE);
            button3.setVisibility(View.VISIBLE);
            button4.setVisibility(View.VISIBLE);
            button5.setVisibility(View.VISIBLE);
            buttoncut.setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View view) {
                            buttoncut.setVisibility(View.GONE);
                            button2.setVisibility(View.GONE);
                            button3.setVisibility(View.GONE);
                            button4.setVisibility(View.GONE);
                            button5.setVisibility(View.GONE);
                            Intent moveIntent = new Intent(PhotosActivity.this, ImageGallery.class);
                            moveIntent.putIntegerArrayListExtra("selected_images", mSelected);
                            startActivity(moveIntent);
                        }
                    });

ImageGallery.java:

public static ArrayList<Model_images> al_images = new ArrayList<>();
ArrayList<Integer> selectedImages = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
int int_position;

selectedImages = getIntent().getIntegerArrayListExtra("selected_images");

if (selectedImages != null) {
    Toast.makeText(ImageGallery.this, "This code gets executed", Toast.LENGTH_SHORT)
            .show();
    new LongOperation().execute();
}

private class LongOperation extends AsyncTask<String, Void, String> {   
    @Override
    protected String doInBackground(String... params) {

        for (int image : selectedImages) {

            File sourceImage = new File(al_images.get(int_position).getAl_imagepath().get(image)); //returns the image File from model class to be moved.
            File destinationImage = new File(al_images.get(int_position).getStr_folder(), ".jpeg");

            try {
                copyOrMoveFile(sourceImage, destinationImage, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //Method to move the file
    private void copyOrMoveFile(File file, File dir, boolean isCopy) throws IOException {
        File newFile = new File(dir, file.getName());
        FileChannel outChannel = null;
        FileChannel inputChannel = null;
        try {
            outChannel = new FileOutputStream(newFile).getChannel();
            inputChannel = new FileInputStream(file).getChannel();
            inputChannel.transferTo(0, inputChannel.size(), outChannel);
            inputChannel.close();
            if (!isCopy)
                file.delete();
        } finally {
            if (inputChannel != null) inputChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }
}
like image 232
Amelia Avatar asked Jan 10 '18 15:01

Amelia


2 Answers

You have to use Intent.ACTION_MEDIA_SCANNER_SCAN_FILE for updating media store.

Inside AsyncTask -> onPostExecute method fetch latest images from MediaStore

private class LongOperation extends AsyncTask<String, Void, File> {

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

            for (String imagePath : selectedImages) {
                File sourceImage = new File(imagePath); //returns the image File from model class to
                // be// moved.
                File destinationImage = new File(al_images.get(int_position).getDirectoryPath() +
                        File.separator + sourceImage.getName());

                try {
                    moveFile(sourceImage, destinationImage, true);
                    return destinationImage;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            getBaseContext().sendBroadcast(new Intent(
            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    fn_imagespath(); // Call method to fetch latest images.
                }
            }, 1000); // additional delay time of 1 sec to update media scanner
        }
    }

Just a better method to move file

private void moveFile(File file_Source, File file_Destination, boolean isCopy) throws IOException {
        FileChannel source = null;
        FileChannel destination = null;
        if (!file_Destination.exists()) {
            file_Destination.createNewFile();
        }

        try {
            source = new FileInputStream(file_Source).getChannel();
            destination = new FileOutputStream(file_Destination).getChannel();

            long count = 0;
            long size = source.size();
            while ((count += destination.transferFrom(source, count, size - count)) < size) ;
            if (!isCopy) {
                file_Source.delete();
            }
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }

        }
    }
like image 118
Jitesh Mohite Avatar answered Oct 12 '22 13:10

Jitesh Mohite


Not much changes in code added MediaScannerConnection. Give it a try .

 private class LongOperation extends AsyncTask<String, Void, Integer> {
    @Override
    protected Integer doInBackground(String... params) {
        int movedCount=0;
        for (int i=0;i<selectedImages.size();i++) {
            File sourceImage = new File(al_images.get(int_position).getAl_imagepath().get(i));
            File destinationImage = new File(al_images.get(int_position).getStr_folder(), ".jpeg");
            try {
              boolean isMoved= copyOrMoveFile(sourceImage, destinationImage, true);
                if(isMoved) {
                    movedCount++;
                    callMediaScanner(ImageGallery.this, destinationImage.getAbsolutePath());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return movedCount;
    }

    @Override
    protected void onPostExecute(Integer val) {
        super.onPostExecute(val);
        // Here you have to modify return type of doInBackground as per your convineance
        if(val.intValue()==selectedImages.size()){
            Log.e("Moved","Allfile moved");
        }else{
            Log.e("Moved","Some file missing");
        }
    }
    public boolean copyOrMoveFile(File localFile, File destinationFile, boolean isCopy) {
            FileChannel outputChannel = null;
            FileChannel inputChannel = null;
            try {
                outputChannel = new FileOutputStream(destinationFile).getChannel();
                inputChannel = new FileInputStream(localFile).getChannel();
                inputChannel.transferTo(0, inputChannel.size(), outputChannel);
                inputChannel.close();
                if (!isCopy)
                    localFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                try {
                    if (inputChannel != null) inputChannel.close();
                    if (outputChannel != null) outputChannel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        return true;
    }
}

public void callMediaScanner(Context context, String path) {
    MediaScannerConnection.scanFile(context,
            new String[] { path }, null,null);
}
like image 1
ADM Avatar answered Oct 12 '22 11:10

ADM