通过意图传递大量数据时出现TransactionTooLargeException异常

4
在我的应用程序中,我通过Intent extras向我的Activity发送数据。在我的特定情况下,我下载一个JSON文件,将其内容转换为String,并将其作为Intent extra发送到我的Activity。大小约为500kB。但是我遇到了TransactionTooLargeException异常。
09-28 13:40:46.647: E/JavaBinder(441): !!! FAILED BINDER TRANSACTION !!!
09-28 13:40:46.647: W/ActivityManager(441): Exception in new application when starting activity com.vektor.sourfer/.SourceActivity
09-28 13:40:46.647: W/ActivityManager(441): android.os.TransactionTooLargeException
09-28 13:40:46.647: W/ActivityManager(441):     at android.os.BinderProxy.transact(Native Method)
09-28 13:40:46.647: W/ActivityManager(441):     at android.app.ApplicationThreadProxy.scheduleLaunchActivity(ApplicationThreadNative.java:723)
09-28 13:40:46.647: W/ActivityManager(441):     at com.android.server.am.ActivityStack.realStartActivityLocked(ActivityStack.java:716)
09-28 13:40:46.647: W/ActivityManager(441):     at com.android.server.am.ActivityManagerService.attachApplicationLocked(ActivityManagerService.java:4341)
09-28 13:40:46.647: W/ActivityManager(441):     at com.android.server.am.ActivityManagerService.attachApplication(ActivityManagerService.java:4405)
09-28 13:40:46.647: W/ActivityManager(441):     at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:390)
09-28 13:40:46.647: W/ActivityManager(441):     at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:1737)
09-28 13:40:46.647: W/ActivityManager(441):     at android.os.Binder.execTransact(Binder.java:388)
09-28 13:40:46.647: W/ActivityManager(441):     at dalvik.system.NativeStart.run(Native Method)
09-28 13:40:46.647: W/ActivityManager(441): Force removing ActivityRecord{421bbed8 u0 com.vektor.sourfer/.SourceActivity}: app died, no saved state

在这种情况下,绕过此错误的最佳方法是什么?

1
阅读此链接:http://stackoverflow.com/a/8192532/786337 - Tarun
1
使用SharedPreferences来共享数据,并在使用后将其删除。 - Biraj Zalavadia
3个回答

4
数据传输大小有1MB的限制,但实际上较小并且与设备有关。你是如何传输这个字符串的?通过putExtra(String string)方法吗?如果可能,请尝试将其包装为Serializable对象,因为这样可以聪明地使用每个字符仅占用一个字节。但是,如果您的字符串可能比此更大,则说明您已接近限制,因此应该将其保存到磁盘而不进行传输。
我写了一篇关于此主题的博客文章,对任何遇到此异常问题的人可能会很有帮助。链接:blog post

4

一种解决方案是将数据保存到公共静态成员变量中,然后从第二个活动中访问它。

另一种解决方案是将结果保存到外部存储器上的文件中,然后从该文件中读取。


1

第一种方法: 由于您正在使用Json,因此请使用JsonReader

https://sites.google.com/site/gson/streaming

这段代码读取一个包含消息数组的JSON文档。它逐个遍历数组元素作为流,以避免将整个文档加载到内存中。 它非常简洁,因为它使用Gson的对象模型解析单个消息。
public List<Message> readJsonStream(InputStream in) throws IOException {
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    List<Message> messages = new ArrayList<Message>();
    reader.beginArray();
    while (reader.hasNext()) {
        Message message = gson.fromJson(reader, Message.class);
        messages.add(message);
    }
    reader.endArray();
    reader.close();
    return messages;
}

第二种方法:保存文件并将文件URI/路径传递给第二个活动。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接