设置OnClickListener会抛出异常吗?

时间:2014-03-11 15:26:09

标签: java android adapter onclicklistener

我想知道为什么我的应用程序在运行时抛出运行时异常?我习惯了以下链接中的代码, dynamically add and remove view to viewpager

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar ab=getActionBar();

    pagerAdapter = new MainPagerAdapter();
    pager = (ViewPager) findViewById (R.id.pager);

    pager.setAdapter (pagerAdapter);


    inflater = (LayoutInflater)getSystemService
              (Context.LAYOUT_INFLATER_SERVICE);
    v0 = (FrameLayout) inflater.inflate (R.layout.listlayout, null);
    Button button=(Button)findViewById(R.id.button1);
    button.setOnClickListener(this);

    pagerAdapter.addView (v0, 0);

    pagerAdapter.notifyDataSetChanged();

}
@Override
public void onClick(View v) {
    if(v.getId()==R.id.button1)
    {
        pagerAdapter.addView (v0);

        pagerAdapter.notifyDataSetChanged();
    }

}

logcat的:

  FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.todolistworkable/com.example.todolistworkable.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)Caused by: java.lang.NullPointerException
at com.example.todolistworkable.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)

1 个答案:

答案 0 :(得分:0)

onCreate方法中代码的第43行上的对象为null。很可能你的一个findViewById调用的目标没有返回你期望的目标。

有关详情,请参阅此处。 How to interpret Logcat