androidshare-button

In android coding of share button got null pointer exception on this line mShareActionProvider.setShareIntent(getDefaultShareIntent());


Logcat Image In android coding of share button got NullPointerException on this line mShareActionProvider.setShareIntent(getDefaultShareIntent()); Can anyone solve this error?

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

    /** Inflating the current activity's menu with res/menu/items.xml */
    getMenuInflater().inflate(R.menu.menu_main, menu);
    MenuItem shareItem = menu.findItem(R.id.menu_item_share);

    // Now get the ShareActionProvider from the item
    mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);

    /** Getting the actionprovider associated with the menu item whose id is share */
   // mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_item_share).getActionProvider();

    /** Setting a share intent */
    mShareActionProvider.setShareIntent(getDefaultShareIntent());


    return super.onCreateOptionsMenu(menu);

}

/** Returns a share intent */
private Intent getDefaultShareIntent(){
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
    intent.putExtra(Intent.EXTRA_TEXT,"Extra Text");
    return intent;
}

Solution

  • UpDate :

    import this

    import android.widget.ShareActionProvider;
    

    declare it global

     private ShareActionProvider mShareActionProvider;
    
     @Override
            public boolean onCreateOptionsMenu(Menu menu) {
    
            // Inflate menu resource file.
            getMenuInflater().inflate(R.menu.menu_main, menu);
    
            // Locate MenuItem with ShareActionProvider
            MenuItem shareItem = menu.findItem(R.id.menu_item_share);
    
            // Fetch and store ShareActionProvider
            mShareActionProvider  = (ShareActionProvider)shareItem..getActionProvider();
    
           
           setShareIntent(getDefaultShareIntent());    
    
    
              // Return true to display menu
            return true;
    
        }
    
     // Call to update the share intent    
     private void setShareIntent(Intent shareIntent) {
          if (mShareActionProvider != null) {
               mShareActionProvider.setShareIntent(shareIntent);
          }
     }
    
    /** Returns a share intent */
    private Intent getDefaultShareIntent(){
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
        shareIntent.putExtra(Intent.EXTRA_TEXT,"Extra Text");
        return shareIntent;
    }