I followed Google's directions to the letter (http://developer.android.com/guide/topics/ui/actionbar.html#ActionProvider) and yet I couldn't make it work. I'm trying to add a share button the the action bar. Here's my code:

MyActivity.java

import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;

private ShareActionProvider mShareActionProvider;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.my_activity, menu);

    MenuItem menuItem = menu.findItem(R.id.menu_item_share);
    mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("image/png");
    intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(FILE_PATH));
    mShareActionProvider.setShareIntent(intent);    // Line 52

    return super.onCreateOptionsMenu(menu);
}

my_activity.xml

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

    <item android:id="@+id/menu_item_share"
        android:title="@string/share"
        android:icon="@drawable/social_share"
        android:orderInCategory="100"
        app:showAsAction="always"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />

</menu>

LogCat says:

java.lang.NullPointerException
        at it.mrhyde.example.activity.MyActivity.onCreateOptionsMenu(MyActivity.java:52)
        at android.app.Activity.onCreatePanelMenu(Activity.java:2449)
        at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:405)
        at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:756)
        at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:2852)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4424)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
        at dalvik.system.NativeStart.main(Native Method)

What am I doing wrong?!

有帮助吗?

解决方案

Make sure that your activity extends ActionBarActivity (not just Activity). It has to so that MenuItemCompat.getActionProvider(menuItem); can return a proper value.

其他提示

It seems you are chaining a null value.

Can't you use breakpoint ?

otherwise, output log on each object, don't chain method

and you'll find your null value

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top