【问题标题】:How should I send an ArrayList of Bitmaps from one activity to another ? I我应该如何将位图的 ArrayList 从一个活动发送到另一个活动?一世
【发布时间】:2020-08-31 22:23:00
【问题描述】:

发送活动中的代码:

    Intent intent = new Intent(MainActivity.this,Main2Activity.class);
    intent.putParcelableArrayListExtra("bitmaps",  bitmapArrayList);
    startActivity(intent);

接收活动中的代码:

    Intent intent = getIntent();
    bitmapArrayList =  intent.getParcelableArrayListExtra("bitmaps");

应用程序一进入接收活动就会崩溃。请帮忙。

【问题讨论】:

    标签: android arraylist android-intent bitmap parcelable


    【解决方案1】:

    您不应将此类数据从活动 A 发送到 B。在它们之间使用某种中类,您可以在其中设置此数据然后检索,例如存储库。 Bundles 和 Intents 不是为大数据设计的。还可以考虑保留 Id 或 URI-s 并从另一个活动中访问它们,而不是直接发送纯位图

    文档:https://developer.android.com/reference/android/os/TransactionTooLargeException

    Binder 事务缓冲区有一个有限的固定大小,目前为 1Mb,由进程正在进行的所有事务共享。因此,当有许多事务正在进行时,即使大多数单个事务的大小适中,也可能会引发此异常。

    【讨论】:

    • 好的,我会调查的。
    • 您能否提供一些链接,让我可以通过 URI-s 学习如何做到这一点?
    • 我想没有特定的链接/教程来学习如何通过 URI 做到这一点。如果您从文件创建位图,URI 将是您文件的地址。我在答案中的意思是只保留参考,不要在意图中发送原始位图,传递文件的 id 或 URI,并在另一个活动中检索它。
    【解决方案2】:

    Bitmap 扩展了 Parcelable,这意味着您可以提供这样的列表:

     ArrayList<Bitmap> bitmapList = new ArrayList<Bitmap>();
    // Poupulate list here
    
    Intent intent = new Intent();
    intent.putParcelableArrayListExtra("list", bitmapList);
    

    然后您可以在接收活动中将其转换为 Bitmap[]:

    Bitmap[] bitmapArray = bitmapList.toArray(new Bitmap[bitmapList.size()]);
    

    但请记住,在您的意图中添加太多内容通常是不好的做法。最好存储您的数据(数据库、文件系统、单例...)并传递 URI 或 ID。

    【讨论】:

    • 应用程序存储在位图数组后仍然崩溃。
    • 否,但应用程序崩溃了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多