Unable to cast Action Provider to Share Action Provider

I ran into this problem following the android dev actionbar guide which is basically what you are doing. After digging into the samples that utilize the action bar using the backwards compatible v7 and v4 support libraries I ended up using the following code for onCreateOptionsMenu().

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        File file = new File(mFilePath);


        ShareCompat.IntentBuilder b = ShareCompat.IntentBuilder.from(this)
        .setType("image/png")
        .setStream(Uri.fromFile(file));


        MenuItem item = menu.add("Share");
        ShareCompat.configureMenuItem(item, b);
        MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
        return true;
    }

Couple of things to note here is that you are not inflating from a menu resource. The menu is having the default share button added to it. You simply need to specify what type of resource your are sharing with .setType. Since I am sharing a file I need to setStream, with Uri.fromFile(new File()); If you were sharing text you would setType("text/plain").

Also make sure you have imported the $SDK\extras\android\support\v7\appcompat library project, which contains the needed packages. Also since have imported that library project, your project does not need the v4support.jar in your libs folder because the library project already has it.


You are using android.widget.ShareActionProvider, which is for the native API Level 11+ action bar. If you are using the AppCompat backport of the action bar, you need to use android.support.v7.widget.ShareActionProvider instead.


I had the same problem and I have found the solution:

1) You have to use:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bwq="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/menu_share"
        android:title="@string/menu_share"
        bwq:actionProviderClass="android.support.v7.widget.ShareActionProvider"
        bwq:showAsAction="always"/>
</menu>

2) and in Java

import android.support.v7.widget.ShareActionProvider;

and

// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

menu:

<item
    android:id="@+id/action_share"
    android:title="@string/action_share"
    app:showAsAction="ifRoom"
    app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>

java:

MenuItem menuItem = menu.findItem(R.id.action_share);
mActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);