[英]Android App context null in Activity.onCreate()
This code in Activity活动中的这段代码
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics(); //crash
}
sometimes produces a NullPointerException
.有时会产生
NullPointerException
。
This is the custom App class:这是自定义应用程序 class:
public class App extends Application
{
private static Context context;
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public static Context getAppContext()
{
return context;
}
}
How can the NullPointerException
be fixed?如何修复
NullPointerException
?
Replace:代替:
DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics();
with:和:
DisplayMetrics metrics = getResources().getDisplayMetrics();
Not only do you not need the Application
here, anything GUI-related should be using an Activity
anyway.这里不仅不需要
Application
,任何与 GUI 相关的东西都应该使用Activity
。
You don't need App.getAppContext()
你不需要
App.getAppContext()
just只是
DisplayMetrics metrics = getResources().getDisplayMetrics();
or要么
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
or要么
DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.