Reputation: 2733
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?
Upvotes: 0
Views: 146
Reputation: 1292
You don't need App.getAppContext()
just
DisplayMetrics metrics = getResources().getDisplayMetrics();
or
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
or
DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
Upvotes: 0
Reputation: 1006584
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.
Upvotes: 3