Search code examples
androidandroid-fileandroid-sharing

How to share *.txt file in android


I tried many ways but I can't do this.

I have a *.txt file. I want to share it via Bluetooth, wifi, email and ....

When i used this code i cant share the file:

  File file = new File(Environment.getExternalStorageDirectory(), "Email-Ghap/Emails.txt");
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("*/txt");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, file);
        startActivity(Intent.createChooser(sharingIntent, "share file with"));

Totally I want this: when the user clicked on the share button and chooses one email sender like Gmail for sharing. the file must be attached file for the new email ...

I found this link https://stackoverflow.com/a/16036249/4016922

But it shares txt file content. I want to share the file not the content of the txt file


Solution

  • Change your Code Like this.

    From

    File file = new File(Environment.getExternalStorageDirectory(), "Email-Ghap/Emails.txt");
    

    To

    File file = new File(Environment.getExternalStorageDirectory() + "/" + "Email-Ghap/Emails.txt");
    

    from:

    sharingIntent.setType("*/txt");
    

    To

    sharingIntent.setType("text/*");
    

    so yourFinal Code Looks Like

        File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "abc.txt");
                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/*");
                sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file.getAbsolutePath()));
                startActivity(Intent.createChooser(sharingIntent, "share file with"));