Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: java.io.File cannot be cast to android.os.Parcelable

I'm trying to create text file and share it (by Bluetooth, email..)

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

Here is the createFile2() fun:

 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)
like image 412
Andrii Kovalchuk Avatar asked Dec 18 '25 14:12

Andrii Kovalchuk


1 Answers

When filling the EXTRA_STREAM for an ACTION_SEND intent you must provide the Uri for the resource, not the File object itself.

As for the exception: while in general you can put a File object as part of the extended data of an Intent (since it implements Serializable), the receiver expects a Parcelable instance for EXTRA_STREAM, which File isn't.

like image 149
matiash Avatar answered Dec 21 '25 06:12

matiash