【问题标题】:How can I pass array of images to another activity?如何将图像数组传递给另一个活动?
【发布时间】:2017-10-31 01:56:58
【问题描述】:

我正在通过onActivityResult() 从图库中获取用户选择的图像,如下所示:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == OPEN_MEDIA_PICKER) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK && data != null) {

            ArrayList<String> selectionResult = data.getStringArrayListExtra("result");


            System.out.println(selectionResult);
        }
    }
}

当我尝试将selectionResult 打印到控制台时,它会将每个图像的目录作为字符串打印到控制台。

如何将实际图像存储在数组中并通过 Intent 将它们发送到下一个 Activity?

【问题讨论】:

标签: android android-intent android-image


【解决方案1】:

你只需创建 Bitmap 数组然后使用 URI 生成 Bitmap 并放入 Array 然后将 Array 传递给 Adapter。

ArrayList<Bitmap> bitmaps =new ArrayList<>();

然后

Uri uri = data.getData();

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),uri);

bitmaps .add(bitmap );

然后通知适配器。

【讨论】:

    【解决方案2】:

    兄弟,将图像的位图数据从一个活动发送到另一个活动不是一个好方法,因为位图对象大多很大。因此可能会生成 outOfMemory 问题,并且您的应用程序将由于此 outOfMemory 而崩溃。所以你应该使用图像导向器而不是位图数据。我的意思是您将图像路径(图像目录)从一个活动发送到另一个活动。您通过意图将图像路径的 ArrayList 对象从一个活动发送到另一个活动。因为它是可序列化的,而且String格式的数据不大。

    【讨论】:

    • 我明白了,谢谢,我已经应用了你的方式并将图像目录存储在一个 ArrayList 中,但是当我想将它们发送到数据库(Firebase)时,我应该将它们转换为位图数组,我说的对吗?
    【解决方案3】:

    您可以在 arraylist 中添加文件路径,例如:

      arraylist.add(file.getAbsolutePath());
      adapter.notifyDataSetChanged();
    

    然后在新 Activity 中发送 arraylist 并在新 Activity 中获取图像表单文件,如:

        FileInputStream streamIn = null;
        try {
            streamIn = new FileInputStream(new File(arraylist.get(position)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(streamIn); //This gets the image
        custom_imageView.setImageBitmap(bitmap);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 2016-06-21
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多