views:

2632

answers:

14

I've tried the Tab Layout example, and I've also fixed the few typos in the example (and added all the activities to the manifest). However, when I run it on the emulator I get a NullPointerException on the first line that says

tabHost.addTab(spec);

So my question, of course, is. What is wrong with the example that would cause this exception? I'm using Eclipse Galileo and set the target package as Android 1.5. So far I've had no other problems with the other examples on the android dev site.

package com.example.hellotabwidget;

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;

public class HelloTabWidget extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) throws RuntimeException {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Resources res = getResources(); // Resource object to get Drawables
    TabHost tabHost = getTabHost();  // The activity TabHost
    TabHost.TabSpec spec;  // Reusable TabSpec for each tab
    Intent intent;  // Reusable Intent for each tab

    // Create an Intent to launch an Activity for the tab (to be reused)
    //final Context context = getApplicationContext();
    intent = new Intent().setClass(this, ArtistsActivity.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("artists").setIndicator("Artists",
            res.getDrawable(R.drawable.ic_tab_artists))
            .setContent(intent);
    tabHost.addTab(spec); //******** NullPointerException after running this line

    // Do the same for the other tabs
    intent = new Intent().setClass(this, AlbumsActivity.class);
    spec = tabHost.newTabSpec("albums").setIndicator("Albums",
            res.getDrawable(R.drawable.ic_tab_artists))
            .setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SongsActivity.class);
    spec = tabHost.newTabSpec("songs").setIndicator("Songs",
            res.getDrawable(R.drawable.ic_tab_artists))
            .setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTabByTag("artists");
}
}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">
    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" />
</LinearLayout>
</TabHost>
A: 

You should post some more of the code so that we can make better assumptions. Especially make sure you instantiate the tabHost Somewhere.

Soulreaper
I've updated the question to include more code.
Poindextrose
From looking at the code i don't see what is wrong. Could you post the stracktrace of the exception?
Soulreaper
There is no stacktrace on the exception nor a detailed message. Clicking on stackState field gives this:'JDI thread evaluations' has encountered a problem. Exception processing async thread queue.Then Details >> shows:Exception processing async thread queue Exception processing async thread queue org.eclipse.jdt.internal.debug.core.model.JDIObjectValue cannot be cast to org.eclipse.jdt.debug.core.IJavaArray
Poindextrose
A: 

Have you put your activity in the AndroidManifest.xml? You have to tell the application about the activity you want to show, otherwise what you'll got is just an error.

For example, you can put the following xml code inside the <application> element:

    <activity android:name=".ArtistsActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
        </intent-filter>
    </activity>

Hope this will help.

-Surya Wijaya Madjid

swMadjid
Thanks, but I've don't this. Totally weird because I've successfully ran all the other examples.
Poindextrose
A: 

Same error, still no solution

java.lang.NullPointerException at android.widget.TabWidget.initTabWidget(TabWidget.java:104) at android.widget.TabWidget.(TabWidget.java:69) at android.widget.TabWidget.(TabWidget.java:64) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at android.view.LayoutInflater.createView(LayoutInflater.java:500) at android.view.BridgeInflater.onCreateView(BridgeInflater.java:77) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563) at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:122) at android.view.LayoutInflater.rInflate(LayoutInflater.java:618) at android.view.LayoutInflater.rInflate(LayoutInflater.java:621) at android.view.LayoutInflater.inflate(LayoutInflater.java:407) at android.view.LayoutInflater.inflate(LayoutInflater.java:296) at com.android.layoutlib.bridge.Bridge.computeLayout(Bridge.java:396) at com.android.ide.eclipse.adt.internal.editors.layout.gle1.GraphicalLayoutEditor.computeLayout(Unknown Source) at com.android.ide.eclipse.adt.internal.editors.layout.gle1.GraphicalLayoutEditor.recomputeLayout(Unknown Source) at com.android.ide.eclipse.adt.internal.editors.layout.gle1.GraphicalLayoutEditor.activated(Unknown Source) at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditor.partActivated(Unknown Source) at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditor.partBroughtToTop(Unknown Source) at org.eclipse.ui.internal.PartListenerList$2.run(PartListenerList.java:87) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.core.runtime.Platform.run(Platform.java:888) at org.eclipse.ui.internal.PartListenerList.fireEvent(PartListenerList.java:57) at org.eclipse.ui.internal.PartListenerList.firePartBroughtToTop(PartListenerList.java:85) at org.eclipse.ui.internal.PartService.firePartBroughtToTop(PartService.java:208) at org.eclipse.ui.internal.WorkbenchPagePartList.firePartBroughtToTop(WorkbenchPagePartList.java:76) at org.eclipse.ui.internal.WorkbenchPagePartList.fireActiveEditorChanged(WorkbenchPagePartList.java:52) at org.eclipse.ui.internal.PartList.setActiveEditor(PartList.java:162) at org.eclipse.ui.internal.WorkbenchPage.makeActiveEditor(WorkbenchPage.java:1277) at org.eclipse.ui.internal.WorkbenchPage.setActivePart(WorkbenchPage.java:3524) at org.eclipse.ui.internal.WorkbenchPage.requestActivation(WorkbenchPage.java:3071) at org.eclipse.ui.internal.PartPane.requestActivation(PartPane.java:279) at org.eclipse.ui.internal.EditorPane.requestActivation(EditorPane.java:98) at org.eclipse.ui.internal.PartPane.setFocus(PartPane.java:325) at org.eclipse.ui.internal.EditorPane.setFocus(EditorPane.java:127) at org.eclipse.ui.internal.PartStack.presentationSelectionChanged(PartStack.java:846) at org.eclipse.ui.internal.PartStack.access$1(PartStack.java:829) at org.eclipse.ui.internal.PartStack$1.selectPart(PartStack.java:139) at org.eclipse.ui.internal.presentations.util.TabbedStackPresentation$1.handleEvent(TabbedStackPresentation.java:133) at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:270) at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:279) at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder.access$1(DefaultTabFolder.java:1) at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder$2.handleEvent(DefaultTabFolder.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1027) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1012) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:770) at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:3256) at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:2045) at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:323) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3910) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3503) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2369) at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2221) at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:500) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:493) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149) at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:113) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:194) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:368) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:559) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:514) at org.eclipse.equinox.launcher.Main.run(Main.java:1311)

radsinsky
A: 

Try this in ur manifest

<activity android:name=".AlbumsActivity"  android:label="@string/app_name"></activity> 
    <activity android:name=".ArtistsActivity"  android:label="@string/app_name"></activity> 
    <activity android:name=".SongsActivity"  android:label="@string/app_name"></activity> 
Ngetha
A: 

This is what worked for me:

I changed this line to use "artists" tabHost.setCurrentTabByTag("artists");

And then added a "." in front of TabAndroid(the main activity name) and added the three activities that Ngetha suggested.

</application>
Zeke
A: 

I'm only starting programming for the Android, and I encountered this problem, too. I have to say I was quite frustrated with it. Doing what Ngetha suggested helped me out, but I also had to edit my code a little. What I noticed is that apparently the Android does not like sub-classed Activities. At all. I thought I would make my code cleaner by encapsulating everything, but that's apparently not okay. I had to move my classes to separate files. I hope this helps other new programmers with the same encapsulation problem I had.

Jon
I'm using Eclipse. It forces me to have each class in a separate file.
Poindextrose
A: 

I had the same wired error.

Try This:

If you are using eclipse delete the error, change some code(so the app will recompile) and then it should work fine.

Lehto
A: 

Better, if you get stuck in such errors, try Project > Clean to regenerate automatically generated files.

sazwqa
A: 

I was having the same issue. I started the tutorials yesterday and this was the only one to have problems.

The null pointer is thrown at this line the first time its called

tabHost.addTab(spec);

turn out the fix was in the manifest XML

<activity android:name=".MyTabActivity"
      android:label="@string/app_name"
      android:theme="@android:style/Theme.NoTitleBar">
    <intent-filter>
       <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>


<activity android:name=".DateActivity"  android:label="@string/app_name"></activity> 
<activity android:name=".RandomNumActivity"  android:label="@string/app_name"></activity> 

the last two activities were not present before, and it would fail. I added them (thanks to Ngetha's suggestion above!) and it worked perfectly. For the tutorial's example itself, it would be the three artists, albums, and songs activities that you would need to add

I guess I learned that every activity needs to be listed in the manifest, makes sense I just didn't think of it while following the example to the T.

Is it true that this is the case? all activities must be in the manifest?

Cameron
A: 

thanks to Ngetha's, its working perfect.

lakshmikanthreddy
A: 

I had the same issue - check your emulator configuration and whether it is attached to debugger.

Subhajit
+1  A: 

Just want to say thanks to all that posted here. Solved my problem (the same as everyone else here). It was very frustrating to get this to work. They should have really simplified the example much better.

To try to sum up the changes needed.

  1. add the 3 activity lines Ngetha says.
  2. Move all 3 activity classes to separate files. example I ended up using for my SongsActivity.java file (with eclipse error suggestions)

    package com.example.HelloTabWidget;
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    public class SongsActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textview = new TextView(this);
        textview.setText("This is the Songs tab");
        setContentView(textview);
    }
    }
    
  3. I had to create a res\drawable directory and place all icons there plus I made 3 xml files for the icons such as "ic_tab_songs.xml"
ray
A: 

Not working for me.....I am gonna show what i have on my files: Manifest file:

</application>

main.xml file:

I try to click on the tab "layout" on the main.xml, and it appears the grey window and a message telling:"Null Pointer Exception:null". Don´t understand why! I have the classes created, and i think all the references.

I think my problem is going on the main.xml when it is "android:id="@android:id/tabhost"

Jorge
A: 

SOLVED I was getting nullPointerException after .addTab(spec) when returning back from a launched intent. I did not get the error on the initial entry to this activity.

I solved it by adding:

TabHost tabHost = (TabHost) getTabHost(); tabHost.setCurrentTab(0); // this stopped the nullPointerException ..... .... tabHost.addTab(spec);

Jim