This code in Activity
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics(); //crash
}
sometimes produces a NullPointerException
.
This is the custom App 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?
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.
You don't need App.getAppContext()
just
DisplayMetrics metrics = getResources().getDisplayMetrics();
or
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
or
DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
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.