0

Share menu item

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

MainActivity.java

@Override

public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_main, menu);
    MenuItem menuItem = menu.findItem(R.id.action_share);
    shareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
    setIntent("This is a sample text");
    return true;
}

private void setIntent(String string)
{
    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(android.content.Intent.EXTRA_TEXT,string);
    shareActionProvider.setShareIntent(intent);
}

@Override

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_share)
    {

    }

This is not working at all, the app crashes.

The logcat is -

03-09 21:38:46.567 30763-30763/? E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.example.pooja1.bitsandpizzas, PID: 30763
   java.lang.UnsupportedOperationException: This is not supported, use MenuItemCompat.getActionProvider()
       at android.support.v7.view.menu.MenuItemImpl.getActionProvider(MenuItemImpl.java:645)
       at com.example.pooja1.bitsandpizzas.MainActivity.onCreateOptionsMenu(MainActivity.java:31)
       at android.app.Activity.onCreatePanelMenu(Activity.java:2862)
       at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:341)

The line MainActivity.java:31 -> shareActionProvider = (ShareActionProvider) menuItem.getActionProvider();

Thanks in advance!

alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46

2 Answers2

0

Well it is clearly written in the exception to use

MenuItemCompat.getActionProvider()

provided by android v7 support library rather than using the

menuItem.getActionProvider();

method provided by the default android.

AmanSinghal
  • 2,404
  • 21
  • 22
  • yes but if I use that then I have to pass a parameter to getActionProvider() I dont know what to pass – Pooja Karki Mar 09 '16 at 16:32
  • I think this post can help you in solving your question. [link](http://stackoverflow.com/questions/27887716/exception-this-is-not-supported-use-menuitemcompat-getactionprovider) – AmanSinghal Mar 09 '16 at 16:36
0

Try change android:actionProviderClass="android.widget.ShareActionProvider" to app:actionProviderClass="android.support.v7.widget.ShareActionProvider"