使用FragmentTabHost与Resources对象的空指针异常

时间:2014-04-24 02:07:34

标签: android android-fragments android-studio fragment-tab-host

之前我没有使用过TabHost,并且在几个教程之后拼凑了一些内容,但是我在第81行继续获得NullPointerException,在使用它来获取可绘制图标时,我有我的Resources类变量使用

TabSpec tabSpecVolcano = tabHost
                .newTabSpec("Volcano") // Line 81
                .setIndicator("", resrc.getDrawable(R.drawable.ic_tab_volcano))
                .setContent(intentVolcano);

第81行是"由"在我的LogCat中。此错误导致模拟器崩溃而未在启动时显示任何内容。下面我将发布我的MainSelectorActivity.java,它的xml和属于第81行的选项卡的xml布局,Volcano布局(以及类)。所有其他选项卡都具有与Volcano类似的布局和类别。另外我会发布我的LogCat。如果您需要查看其他文件,请告诉我。非常感谢。

更新:通过在onCreate方法中实例化getResources()来解决原始错误。请参阅下面的答案,并解释其工作原理。

MainSelectorActivity.java

package com.azurespot.disastertimer.app;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.widget.TabHost.TabSpec;


public class MainSelectorActivity extends FragmentActivity {

    Resources resrc = getResources();
    FragmentTabHost tabHost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_selector);

        // TabHost setup
        tabHost = (android.support.v4.app.FragmentTabHost)findViewById(android.R.id.tabhost);
        tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        //------Zombie tab------
        // Creates tab and sets zombie image in view
//        tabHost.addTab(tabHost.newTabSpec("zombie").setIndicator("Zombie",
//                        getResources().getDrawable(R.drawable.ic_tab_zombie)),
//                ZombieTab.class, null);
        // When icon is clicked, zombie image shows
        Intent intentZombie = new Intent().setClass(this, ZombieTab.class);
        TabSpec tabSpecZombie = tabHost
                .newTabSpec("Zombie")
                .setIndicator("", resrc.getDrawable(R.drawable.ic_tab_zombie))
                .setContent(intentZombie);

        //------Nuclear tab------
        // Creates tab and sets nuclear image in view
//        tabHost.addTab(tabHost.newTabSpec("nuclear").setIndicator("Nuclear",
//                        getResources().getDrawable(R.drawable.ic_tab_nuclear)),
//                NuclearTab.class, null);
        // When icon is clicked nuclear image shows
        Intent intentNuclear = new Intent().setClass(this, NuclearTab.class);
        TabSpec tabSpecNuclear = tabHost
                .newTabSpec("Nuclear")
                .setIndicator("", resrc.getDrawable(R.drawable.ic_tab_nuclear))
                .setContent(intentNuclear);

        //------Tsunami tab------
        // Creates tab and sets tsunami image in view
//        tabHost.addTab(tabHost.newTabSpec("tsunami").setIndicator("Tsunami",
//                        getResources().getDrawable(R.drawable.ic_tab_tsunami)),
//                TsunamiTab.class, null);
        // When icon is clicked tsunami image shows
        Intent intentTsunami = new Intent().setClass(this, TsunamiTab.class);
        TabSpec tabSpecTsunami = tabHost
                .newTabSpec("Tsunami")
                .setIndicator("", resrc.getDrawable(R.drawable.ic_tab_tsunami))
                .setContent(intentTsunami);

        //------Godzilla tab------
        // Creates tab and sets tsunami image in view
//        tabHost.addTab(tabHost.newTabSpec("godzilla").setIndicator("Godzilla",
//                        getResources().getDrawable(R.drawable.ic_tab_godzilla)),
//                GodzillaTab.class, null);
        // When icon is clicked godzilla image shows
        Intent intentGodzilla = new Intent().setClass(this, GodzillaTab.class);
        TabSpec tabSpecGodzilla = tabHost
                .newTabSpec("Godzilla")
                .setIndicator("", resrc.getDrawable(R.drawable.ic_tab_godzilla))
                .setContent(intentGodzilla);

        //------Volcano tab------
        // Creates tab and sets volcano image in view
//        tabHost.addTab(tabHost.newTabSpec("volcano").setIndicator("Volcano",
//                        getResources().getDrawable(R.drawable.ic_tab_volcano)),
//                VolcanoTab.class, null);
        // When icon is clicked volcano image shows
        Intent intentVolcano = new Intent().setClass(this, VolcanoTab.class);
        TabSpec tabSpecVolcano = tabHost
                .newTabSpec("Volcano")
                .setIndicator("", resrc.getDrawable(R.drawable.ic_tab_volcano))
                .setContent(intentVolcano);

        // add all tabs
        tabHost.addTab(tabSpecZombie);
        tabHost.addTab(tabSpecNuclear);
        tabHost.addTab(tabSpecTsunami);
        tabHost.addTab(tabSpecGodzilla);
        tabHost.addTab(tabSpecVolcano);

        //set Zombie tab as default (zero based)
        tabHost.setCurrentTab(0);

    }

}

activity_main_selector.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.azurespot.disastertimer.app.MainSelectorActivity">

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TabWidget
                android:id="@android:id/tabs"

                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0" />

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_weight="0" />

            <FrameLayout
                android:id="@+id/realtabcontent"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1" />

        </LinearLayout>
    </android.support.v4.app.FragmentTabHost>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:orientation="horizontal"
        android:layout_marginTop="200dp"
        android:gravity="center_horizontal">

        <NumberPicker
            android:id="@+id/numberPicker1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="20dp" />

        <NumberPicker
            android:id="@+id/numberPicker2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:layout_marginTop="20dp" />

        <NumberPicker
            android:id="@+id/numberPicker3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:layout_marginTop="20dp" />
    </LinearLayout>

</RelativeLayout>

VolcanoTab.java

package com.azurespot.disastertimer.app;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by azuremoss on 4/22/14.
 */
public class VolcanoTab extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.volcano_tab, container, false);

        return v;
    }
}

volcano_tab.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:layout_marginTop="0dp"
        android:id="@+id/imageButton"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/volcano_image"
        android:text="@string/volcano_fragment_string"/>
</LinearLayout>

logcat的

1111-1111/com.azurespot.disastertimer.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.azurespot.disastertimer.app/com.azurespot.disastertimer.app.MainSelectorActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
            at android.app.ActivityThread.access$600(ActivityThread.java:130)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            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:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at android.content.ContextWrapper.getResources(ContextWrapper.java:81)
            at com.azurespot.disastertimer.app.MainSelectorActivity.<init>(MainSelectorActivity.java:13)
            at java.lang.Class.newInstanceImpl(Native Method)
            at java.lang.Class.newInstance(Class.java:1319)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
            at android.app.ActivityThread.access$600(ActivityThread.java:130)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            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:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

你应该在activity的onCreate()方法中调用getResources()。

答案 1 :(得分:1)

实际上,您的错误是13中的行MainSelectorActivity。行81ContextWrapper中出现空指针异常的地方,它来自活动类中行13中的调用。

13

Resources resrc = getResources();

你为什么在这里收到错误?由于您将getResources作为声明进行调用,因此此调用发生在您的onCreate活动之前。

getResources需要一个context,在这种情况下来自您的活动,但由于context尚未正确初始化,您将获得空指针异常。

因此,如果您仍想保留全局resrc变量,则需要在onCreate方法中进行设置。

Resources resrc;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    resrc = getResources();
    ...
}