我在运行时收到空指针异常。我试图在单击图像按钮时从另一个活动调用接口方法。
我已经提到了错误行并发布了相关代码。
堆栈跟踪:
07-24 04:42:38.962 4414-4414/com.ms.ha E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.ms.ha.activity.GridActivity3.onClick(GridActivity3.java:62)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
LayoutActivity.java:
public class LayoutActivity extends Activity implements OnClickListener {
ImageButton btn_click;
private static ItemSelectedListener mListener=null;
public static void register(ItemSelectedListener listener){
mListener = listener;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid3);
btn_click = (ImageButton) findViewById(R.id.btn_click);
btn_click.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_click:
if(mListener!=null){
mListener.onItemSelected(0, "Home Details");
}else{
mListener.onItemSelected(1, "List Details"); --->62nd line
}
break;
}
}
}
ItemSelectedListener
public interface ItemSelectedListener {
public void onItemSelected(final int position, final String content);
}
MainActivity.java:
public class MainActivity extends ActionBarActivity implements OnTabChangeListener,ItemSelectedListener {
private TextView action_bar_hometext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onItemSelected(int position, String content)
{
if(position==0)
{
action_bar_hometext.setText(content);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
HomeFirstFragment newFragment = new HomeFirstFragment();
ft.replace(R.id.realtabcontent, newFragment);
ft.addToBackStack(null);
ft.commit();
}
}
如果我在LayoutActivity类中单击btn_click,我需要执行onClick以从MainActivity调用接口方法。但不幸的是我在运行时遇到错误。
我不知道如何解决这个问题。任何人都可以帮助我。谢谢。
答案 0 :(得分:0)
if(mListener!=null){
mListener.onItemSelected(0, "Home Details");
}else{
mListener.onItemSelected(1, "List Details"); --->62nd line
}
如果你的监听器不为null你就调用了一些方法,否则你也试图在空引用上调用一些方法