[英]ExceptionInInitializerError - static final variables
以下代碼有時會產生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;
}
}
應用初始化之前,您無法訪問資源。 static
字段是在具有靜態定義的.dex
文件中生成的,這意味着它們應該像"foo"
一樣是靜態的。 但是您不能在應用程序資源的靜態初始化中使用資源。
以此更改您的活動類別。
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);
}
}
順便說一句,當您直接訪問Activity
類中的getString
方法時,為什么需要創建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);
}
}
首先聲明變量,然后在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
文件中獲取字符串的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);
}
}
代替使用res = App.getAppContext().getResources()
只需調用res = getApplicationContext().getResources()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.