Java NullPointerException:尝试在空对象引用上调用虚拟方法“android.view.view android.widget.RelativeLayout.findViewById(int)”
我试图在操作栏中放置一个通知计数器,它在OnCreateOptions菜单方法中给了我这个错误: 代码如下:Java NullPointerException:尝试在空对象引用上调用虚拟方法“android.view.view android.widget.RelativeLayout.findViewById(int)”,java,android,nullpointerexception,Java,Android,Nullpointerexception,我试图在操作栏中放置一个通知计数器,它在OnCreateOptions菜单方法中给了我这个错误: 代码如下: public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); RelativeL
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.shopping_cart).getActionView();
TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);
tv.setText("12");
return true;
}
在添加最后3行代码之前,我的应用程序没有生成任何错误。有人能帮我吗?两条建议:
按id查找时去掉徽章布局-TextViewfindViewById
检查布局是否为null,错误null object reference表示调用实例为null。因此,在本例中,badgeLayout为null。请执行以下操作:
->检查所引用的布局xml是否存在
->删除getActionView
有一件事是,如何在menu.xml中使用RelativeLayout,这种方法行不通ever@sourabhbans这不管用。它说需要不兼容的类型:android.view.view Found:void您试图在操作栏中放置通知计数器的位置?还是在选项菜单内?@SourabBans在菜单内尝试了第二个建议,它给了我这个示例ClassCastException:android.support.v7.internal.view.menu.MenuItemImpl不能强制转换为android.widget.RelativeLayout。第一个建议给了我另一个例外:NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.TextView.setTextjava.lang.CharSequence”
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.shopping_cart).getActionView();
TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);
tv.setText("12");
return true;
}