以下代码有时会生成ExceptionInInitializerError
。
显然静态变量res
是null
,尽管它应该在它应该被初始化之后使用。
可能是什么原因?
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;
}
}
答案 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()
。