Android Share动作提供商

时间:2014-04-27 21:15:50

标签: android

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.fullstory_m, menu);
MenuItem menuItem = menu.findItem(R.id.action_share)
mShareActionProvider = (ShareActionProvider)
MenuItemCompat.getActionProvider(menuItem);
mShareActionProvider.setShareIntent(getDefaultIntent());

上面的代码有什么问题,因为它给了我空指针异常 xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/action_share"
      android:title="share"
      app:showAsAction="ifRoom"
      app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
      />
  </menu>

导入

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

堆栈跟踪

04-27 21:01:42.676: E/AndroidRuntime(1908): FATAL EXCEPTION: main
04-27 21:01:42.676: E/AndroidRuntime(1908): java.lang.NullPointerException
04-27 21:01:42.676: E/AndroidRuntime(1908):     at com.pitech.danny.nhl.FullStory.onCreateOptionsMenu(FullStory.java:32)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at android.app.Activity.onCreatePanelMenu(Activity.java:2490)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:407)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:769)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:201)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at android.view.Choreographer.doFrame(Choreographer.java:531)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at android.os.Handler.handleCallback(Handler.java:725)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at android.os.Looper.loop(Looper.java:137)
04-27 21:01:42.676: E/AndroidRuntime(1908):     at 

2 个答案:

答案 0 :(得分:1)

问题可能是MenuItemCompat.getActionProvidernull中返回onCreateOptionsMenu。 由于您使用的是Android支持库ShareActionProvider,即android.support.v7.widget.ShareActionProvider,您的FullStory Activity类应该extend ActionBarActivity

public class FullStory extends ActionBarActivity {

答案 1 :(得分:0)

我遇到了同样的问题。我通过检查我的导入来解决它。请确保您的导入是否正确。

import android.widget.ShareActionProvider;

并在您的xml android:actionProviderClass="android.widget.ShareActionProvider"