OverflowStacker
OverflowStacker

Reputation: 41

aHow can I share a mp3 file to whatsapp? (Android Studio)

I want to share a mp3 file to whatsapp. I found this question on Stack Overflow, but the accepted answer does not work for me. If I try to share it with whatsapp it says "Sharing failed, please try again":

                    File dest = Environment.getExternalStorageDirectory();
                InputStream in = getResources().openRawResource(R.raw.sound);

                try
                {
                    OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
                    byte[] buf = new byte[1024];
                    int len;
                    while ( (len = in.read(buf, 0, buf.length)) != -1)
                    {
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();
                }
                catch (Exception e) {
e.printStackTrace();}

                Intent share = new Intent(Intent.ACTION_SEND);
                share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/sound.mp3"));
                share.setType("audio/mp3");
                startActivity(Intent.createChooser(share, "Shared"));

Here is the full MainActivity.java:

    package com.example.aaron.sharetest;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    Button shareBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "Android/data/com.example.aaron.sharetest/files");

        File sharefile= new File(FILES_PATH, "sound.mp3") ;
        putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sharefile));


        shareBtn = (Button)findViewById(R.id.shareBtn);

        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                1);

        shareBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {




                if (Environment.MEDIA_MOUNTED.equals(

                        Environment.getExternalStorageState())) {

                    if (!FILES_PATH.mkdirs()) {

                        Log.w("error", "Could not create " + FILES_PATH);

                    }

                } else {

                    Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG).show();

                    finish();

                }


                File dest = Environment.getExternalStorageDirectory();
                InputStream in = getResources().openRawResource(R.raw.bibikurz);

                try
                {
                    OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
                    byte[] buf = new byte[1024];
                    int len;
                    while ( (len = in.read(buf, 0, buf.length)) != -1)
                    {
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }

                Intent share = new Intent(Intent.ACTION_SEND);
                share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/sound.mp3"));
                share.setType("audio/mp3");
                startActivity(Intent.createChooser(share, "Shared"));



        }



        });
    }


}

Of course I wrote this line in my Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

What do I have to do to share the mp3 file to whatsapp, etc?

I tried so many accepted answers, but no one of them worked for me.

This is what I get in my LogCat:

06-23 02:41:17.589 23924-23924/? W/Bundle: Key android.intent.extra.STREAM expected ArrayList but value was a android.net.Uri$StringUri.  The default value <null> was returned.
06-23 02:41:17.659 23924-23924/? W/Bundle: Attempt to cast generated internal exception:
                                           java.lang.ClassCastException: android.net.Uri$StringUri cannot be cast to java.util.ArrayList
                                               at android.os.Bundle.getParcelableArrayList(Bundle.java:838)
                                               at android.content.Intent.getParcelableArrayListExtra(Intent.java:5481)
                                               at com.whatsapp.ContactPicker.k(ContactPicker.java:623)
                                               at com.whatsapp.ContactPicker.onCreate(ContactPicker.java:338)
                                               at android.app.Activity.performCreate(Activity.java:6367)
                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2511)
                                               at android.app.ActivityThread.access$900(ActivityThread.java:165)
                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1375)
                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                               at android.os.Looper.loop(Looper.java:150)
                                               at android.app.ActivityThread.main(ActivityThread.java:5621)
                                               at java.lang.reflect.Method.invoke(Native Method)
                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)

Upvotes: 0

Views: 951

Answers (2)

A Maharaja
A Maharaja

Reputation: 1247

Android 6.0 Marshmallow (API 23) or later. If this is the case, you mustimplement runtime permissions

Use file path and check memory card

File FILES_PATH = new File(

        Environment.getExternalStorageDirectory(),

        "Android/data/com.examples(your package )/files");

    File sharefile= new File(

            FILES_PATH,

            "demo.mp3") ;

putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sharefile))  

@Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);



        if (Environment.MEDIA_MOUNTED.equals(

            Environment.getExternalStorageState())) {

            if (!FILES_PATH.mkdirs()) {

                Log.w(TAG, "Could not create " + FILES_PATH);

            }

        } else {

            Toast.makeText(this, R.string.need_external_storage, Toast.LENGTH_LONG).show();

            finish();

        }

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007321

My "sound.mp3" file is located in the raw folder.

Your first two samples will not work, as they have nothing to do with a raw resource. They share a file that does not exist, from a directory that might also not exist.

But here I dont know what "ContextID" or "ResouceID" is.

If this code is going where your first two code snippets went, ContextID can be replaced with this. If you are trying to share res/raw/sound.mp3, then ResourceID is R.raw.sound.

Upvotes: 0

Related Questions