Question

I want to know why my application is throwing a runtime exception when I run it? I used to the code in the following link for my application, 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)
Was it helpful?

Solution

the object on line 43 of your code within your onCreate method is null. Most likely the target of one of your findViewById calls is not returning what you expect it to.

See this for more info. How to interpret Logcat

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top