java - 无法使用异步任务将图像移动到图库中的另一个文件夹

标签 java android image file android-asynctask

我创建了一个图库应用。

我的要求:我想选择多个图像,单击按钮剪切并返回到显示所有文件夹的 Activity (ImageGallery.java)。现在,我想选择一个文件夹,然后在选择该文件夹时将所有选定的图像粘贴到该文件夹​​中。

发生了什么?我可以使用我的应用程序选择图像并返回显示所有文件夹但无法使用我的应用程序移动它们的 Activity 。 我使用任务将移动图像的代码放在后台线程中。我从一个文件夹中选择图像,返回到显示所有文件夹的 Activity (ImageGallery.java) 并选择图像要移动到的文件夹。但是当我尝试移动图像时,在选择文件夹时,所选图像不会移动到正在选择的其他文件夹中。我猜 AsyncTask 中的代码甚至都没有被执行。

我该如何解决?

PhotosActivity.java(用于选择图片的 Activity):

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

最佳答案

您必须使用 Intent.ACTION_MEDIA_SCANNER_SCAN_FILE 来更新媒体存储。

在 AsyncTask 内部 -> onPostExecute 方法从 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
        }
    }

只是一个更好的移动文件的方法

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

        }
    }

关于java - 无法使用异步任务将图像移动到图库中的另一个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48191168/

相关文章:

java - 如何在java中从xsd生成Long类类型变量

java - 单击按钮后在弹出窗口中显示图像 - Android/Java

java - synchronized 在 Vector/ArrayList 的上下文中意味着什么?

Java Swing 和 JComboBox 事件

java - 改造中如何上传和检索特定用户下的数据?

image - 在 Unity 3d 中切换设备相机

python - 转换 Pygame 图像出现错误

Android:应用程序在开始新 Activity 时崩溃

java - 更改 Android TextView 可见性时出错

android - Firebase:检查用户名是否已存在