JakeWharton / ActionBarSherlock

[DEPRECATED] Action bar implementation which uses the native action bar on Android 4.0+ and a custom implementation on pre-4.0 through a single API and theme.
http://actionbarsherlock.com
Apache License 2.0
7.1k stars 3.53k forks source link

NullPointerException using ShareActionProvider #527

Closed GiuseppeIuculano closed 12 years ago

GiuseppeIuculano commented 12 years ago

I'm trying to use ShareActionProvider with actionbarsherlock, but i got:

java.lang.NullPointerException
at com.iuculano.tvitaliane.Start.onCreateOptionsMenu(Start.java:387)
at com.actionbarsherlock.app.SherlockActivity.onCreatePanelMenu(SherlockActivity.java:167
at com.actionbarsherlock.ActionBarSherlock.callbackCreateOptionsMenu(ActionBarSherlock.java:542)

The relevant code on onCreateOptionsMenu(Menu menu) is this:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    super.onCreateOptionsMenu(menu);
    MenuItem menuItem = menu.findItem(R.id.share);

    //MenuInflater blowUp = getSupportMenuInflater();
    //getSupportMenuInflater().inflate(R.menu.menuhome, menu);

    ShareActionProvider mShareActionProvider =  (ShareActionProvider) menuItem.getActionProvider();  //line 387

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    shareIntent.setType("text/plain");

    shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.sharesubject));
    shareIntent.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.sharetext));

    mShareActionProvider.setShareIntent(shareIntent);

and the menuhome.xml has this:

<item
    android:id="@+id/share"
    android:actionProviderClass="com.actionbarsherlock.widget.ShareActionProvider"
    android:enabled="true"
    android:showAsAction="ifRoom"
    android:visible="true">
</item>
iNoles commented 12 years ago

It should be

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    getSupportMenuInflater().inflate(R.menu.menuhome, menu);
    MenuItem menuItem = menu.findItem(R.id.menu_share);

    ShareActionProvider mShareActionProvider =  (ShareActionProvider) menuItem.getActionProvider();  //line 387

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    shareIntent.setType("text/plain");

    shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.sharesubject));
    shareIntent.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.sharetext));

    mShareActionProvider.setShareIntent(shareIntent);
}

your menu file didn't have title and icon too.

JakeWharton commented 12 years ago

The key part to take away is that you need to inflate the menu before calling findItem. You don't need an icon but a title is required if the item were to be pushed into the overflow menu.