【问题标题】:java.lang.ClassCastException: java.io.File cannot be cast to android.os.Parcelablejava.lang.ClassCastException:java.io.File 无法转换为 android.os.Parcelable
【发布时间】:2014-07-10 02:08:31
【问题描述】:

我正在尝试创建文本文件分享(通过蓝牙、电子邮件..)

File file = null;
try {
    file = createFile2(json);
} catch (IOException e) {
    e.printStackTrace();
}

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, file);
shareIntent.setType(getString(R.string.share_contact_type_intent));

这里是 createFile2() 的乐趣:

 public File createFile2(String text) throws IOException {
        File file = new
                File(getFilesDir() + File.separator + "MyFile.txt");

        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
        bufferedWriter.write(text);
        bufferedWriter.close();
        return file;
    }

Logcat:

Bundle﹕ Key android.intent.extra.STREAM expected Parcelable but value was a java.io.File.  The default value <null> was returned.
Bundle﹕ Attempt to cast generated internal exception:
    java.lang.ClassCastException: java.io.File cannot be cast to android.os.Parcelable
            at android.os.Bundle.getParcelable(Bundle.java:1212)
            at android.content.Intent.getParcelableExtra(Intent.java:4652)
            at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7235)
            at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7219)
            at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
            at android.app.Activity.startActivityForResult(Activity.java:3424)
            at android.app.Activity.startActivityForResult(Activity.java:3385)

【问题讨论】:

标签: android file serialization android-sharing


【解决方案1】:

在为ACTION_SEND 意图填充EXTRA_STREAM 时,您必须为资源提供Uri,而不是File 对象本身。

至于例外:虽然一般情况下您可以File 对象作为Intent 的扩展数据的一部分(因为它实现了Serializable),但接收者期望一个ParcelableEXTRA_STREAM 的实例,而 File 不是。

【讨论】:

  • 我想你的意思是android.net.Uri,它是Parcelable 而不是java.net.URI
  • @dmcontador 是的,当然。但我只是将 URI 称为一个概念,而不是特定的类。 :)
猜你喜欢
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
  • 2023-02-02
  • 2016-06-30
  • 2016-01-14
  • 2013-07-25
  • 2016-07-05
  • 2017-01-24
相关资源
最近更新 更多