0

Logcat Image In android coding of share button got NullPointerExceptionon this linemShareActionProvider.setShareIntent(getDefaultShareIntent()); 谁能解决这个错误?

    @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;
}
4

1 回答 1

0

更新 :

导入这个

import android.widget.ShareActionProvider;

将其声明为全局

 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;
}
于 2016-04-16T11:47:10.797 回答