The following code sometimes produces ExceptionInInitializerError
. Apparently the static variable res
is null
although it is used after it should have been initialized. What could be the reason?
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;
}
}
You can not access resources before app initialize. static
fields are generated in .dex
file with static definition, mean they should be static like "foo"
. But you can not use resources in static initialization with app resources.
Change your activity class by this.
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);
}
}
By the way why you need to create Resources object when you have directly access to getString
method in Activity
class
You can just do this.
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);
}
}
First Declare variables then after get a value in onCreate(), you missed onCreate() method.
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;
}
}
}
Directly you can get a lause of string from string.xml
file like this
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);
}
}
代替使用res = App.getAppContext().getResources()
只需调用res = getApplicationContext().getResources()
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.