ExceptionInInitializerError - 静态最终变量

时间:2018-05-04 13:09:26

标签: java android nullpointerexception

以下代码有时会生成ExceptionInInitializerError。 显然静态变量resnull,尽管它应该在它应该被初始化之后使用。 可能是什么原因?

public class GameActivity extends Activity {
    private static final Resources res = App.getAppContext().getResources();
    public static final String foo = res.getString(R.string.foo); //NullPointer here
}

public class App extends Application {
    private static Context context;
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }   
    public static Context getAppContext() {
        return context;
    }
}

3 个答案:

答案 0 :(得分:0)

在初始化应用之前,您无法访问资源。在static文件中使用静态定义生成.dex个字段,这意味着它们应该像"foo"一样是静态的。但是你不能在使用app资源进行静态初始化时使用资源。

按此更改您的活动类。

public class GameActivity extends Activity {
    private static Resources res;
    public static String foo;

    @Override
    protected void onCreate(@android.support.annotation.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        res = App.getAppContext().getResources();
        foo = res.getString(R.string.foo);
    }
}

顺便提一下,当您在getString

中直接访问Activity方法时,需要创建Resources对象

你可以这样做。

public class GameActivity extends Activity {
    public static String foo;

    @Override
    protected void onCreate(@android.support.annotation.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        foo = getString(R.string.foo);
    }
}

答案 1 :(得分:0)

首先声明变量然后在onCreate()中获取一个值后,你错过了onCreate()方法。

 public class GameActivity extends Activity {
        Context context;
 private static Resources res;
    public static String foo;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_add_address);
            context = this;
            init();
        }

        private void init() {
            res = App.getAppContext().getResources();
            foo = res.getString(R.string.foo); //NullPointer here
        }

        public class App extends Application {
            private static Context context;

            public void onCreate() {
                super.onCreate();
                context = getApplicationContext();
            }

            public static Context getAppContext() {
                return context;
            }
        }
    }

您可以直接从string.xml文件中获取字符串

public class GameActivity extends Activity {
    Context context;
    public String foo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        context = this;
        init();
    }

    private void init() {
        foo = getString(R.string.foo);
    }
}

答案 2 :(得分:0)

而不是使用res = App.getAppContext().getResources(),只需致电res = getApplicationContext().getResources()