gpt4 book ai didi

android - java.lang.ClassCastException : java. io.File 无法转换为 android.os.Parcelable

转载 作者:太空狗 更新时间:2023-10-29 16:37:55 25 4
gpt4 key购买 nike

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

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

日志:

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)

最佳答案

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

至于异常(exception):虽然通常您可以File对象作为Intent的扩展数据的一部分(因为它实现 Serializable),接收方需要 EXTRA_STREAMParcelable 实例,而 File 不是。

关于android - java.lang.ClassCastException : java. io.File 无法转换为 android.os.Parcelable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23783079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com