开发者

Problem running android HelloTabWidget example - NullPointerException on addTab()

开发者 https://www.devze.com 2022-12-20 16:49 出处:网络
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

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_开发者_C百科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>


Try this in your 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> 


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"


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?


Hey do the following steps and i am sure that your problem goes out:-

Create a class HelloTabWidget.java

package com.pericent;             //this is package name
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.widget.TabHost;

public class HelloTabWidget extends TabActivity  {

private String TAG="HelloTabWidget";

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

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

  // Create an Intent to launch an Activity for the tab (to be reused)
  intent = new Intent().setClass(this,ArtistsActivity.class);
  Log.v(TAG,"---artist activity is called---");

  // 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);


  // Do the same for the other tabs
  intent = new Intent().setClass(this,AlbumsActivity.class);
  Log.v(TAG,"---album activity is called---");
  spec = tabHost.newTabSpec("albums").setIndicator("Albums",res.getDrawable(R.drawable.ic_tab_albums)).setContent(intent);
  tabHost.addTab(spec);

  intent = new Intent().setClass(this, SongsActivity.class);
  Log.v(TAG,"---song activity is called---");
  spec = tabHost.newTabSpec("songs").setIndicator("Songs",res.getDrawable(R.drawable.ic_tab_songs)).setContent(intent);
  tabHost.addTab(spec);

  }

}

Create your second activity: ArtistActivity.java

package com.pericent;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class ArtistsActivity extends Activity {
 private String TAG="ArtistsActivity";
    /** Called when the activity is first created. */
    @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textview=new TextView(this);
        textview.setText("This is Artist Activity");
        setContentView(textview);
        Log.v(TAG,"---in artist activity---");
    }
}

Create your third activity: AlbumsActivity.java

package com.pericent;

import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class AlbumsActivity extends Activity{
    private String TAG="AlbumsActivity";
    @Override
    public void onCreate(Bundle savedInstance)
    {
        super.onCreate(savedInstance);
        TextView textview_album=new TextView(this);
        textview_album.setText("This is album activity");
        setContentView(textview_album);
        Log.v(TAG,"---in album activity---");
    }

}

Create your fourth activity: SongsActivity.java

package com.pericent;

import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class SongsActivity extends Activity{
    private String TAG="SongsActivity";
    @Override
    public void onCreate(Bundle savedInstance)
    {
        super.onCreate(savedInstance);
        TextView textview_song=new TextView(this);
        textview_song.setText("This is song activity");
        setContentView(textview_song);
        Log.v(TAG,"---in songs activity---");
    }

}

Make a folder in res/drawable In this folder make 3 XML files: the code of these files like this:-

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/ic_tab_artists_grey"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/ic_tab_artists_white" />
</selector>

In the above XML code we use two images, the following are images which must be save in the same folder (res/drawable).

Problem running android HelloTabWidget example - NullPointerException on addTab()

Problem running android HelloTabWidget example - NullPointerException on addTab()

This is the main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/upper">
<TabHost 
    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">
    <HorizontalScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" android:scrollbars="none">
           <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
     </HorizontalScrollView>
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp" />
    </LinearLayout>
</TabHost>
</LinearLayout>

This is AdroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pericent"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
       <activity android:name=".HelloTabWidget" 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=".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>
    </application>
</manifest> 

I think this all information will help, if you have any problem then free to ask me anything. I am always feel happy to help anyone.


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


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


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>


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.


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.


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


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);


I too was having trouble with the tab widget tutorial.

I was onyl able to solve the proble reading this SO post, thansk for the answers guys.

Going back to the tutorial.... the android dev team could improve their documentation.

They do infact tell us to add the XML activities to the manifest, they just dont' specify it very well.. here is the quote:

Notice that this doesn't use a layout file. Just create a TextView, give it some text and set that as the content. Duplicate this for each of the three activities, and add the corresponding tags to the Android Manifest file.

0

精彩评论

暂无评论...
验证码 换一张
取 消