activity
activity

Reputation: 2733

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.

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

Answers (2)

Javad Dehban
Javad Dehban

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

CommonsWare
CommonsWare

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

Related Questions