Android TabHost.addTab -> Null pointer exception Android TabHost.addTab -> Null pointer exception android android

Android TabHost.addTab -> Null pointer exception


For people who might wonder about TabActivity being deprecated the documentation says that you need to call setup() before adding tabs, when you don't use a TabActivity.

tabHost.setup();


You should use TabActivity, it needs same special layout to be set as content (see http://developer.android.com/resources/tutorials/views/hello-tabwidget.html). If you can not use xml you should construct the same content from java code:

public class Main extends TabActivity {@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    TabHost tabHost = new TabHost(this);    tabHost.setId(android.R.id.tabhost);    TabWidget widget = new TabWidget(this);    widget.setId(android.R.id.tabs);    FrameLayout content = new FrameLayout(this);    content.setId(android.R.id.tabcontent);    LinearLayout layout = new LinearLayout(this);    layout.setOrientation(LinearLayout.VERTICAL);    layout.addView(widget);    layout.addView(content);    tabHost.addView(layout);    setContentView(tabHost);    TabHost.TabSpec tab1 = tabHost.newTabSpec("tab1");    tab1.setIndicator("Tab 1");    tab1.setContent(new TabHost.TabContentFactory() {        @Override        public View createTabContent(String tag) {            TextView tv = new TextView(Main.this);            tv.setText("tab 1 content");            return tv;        }    });    tabHost.addTab(tab1);    TabHost.TabSpec tab2 = tabHost.newTabSpec("tab2");    tab2.setIndicator("Tab 2");    tab2.setContent(new TabHost.TabContentFactory() {        @Override        public View createTabContent(String tag) {            TextView tv = new TextView(Main.this);            tv.setText("tab 2 content");            return tv;        }    });    tabHost.addTab(tab2);    setContentView(tabHost);}

}


Checking the method TabHost.addTab(...) in the framework source suggests that your TabWidget is not available yet. A TabWidget must be created in code first or by the system when creating a layout and must have an id of android.R.id.tabs.