【问题标题】:Android App context null in Activity.onCreate()Activity.onCreate() 中的 Android 应用上下文为空
【发布时间】:2020-09-16 04:43:09
【问题描述】:

Activity中的这段代码

public void onCreate(Bundle bundle)
{
    super.onCreate(bundle);
    DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics(); //crash
}

有时会产生NullPointerException

这是自定义 App 类:

public class App extends Application
{
    private static Context context;

    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getAppContext()
    {
        return context;
    }
}

如何修复NullPointerException

【问题讨论】:

    标签: android nullpointerexception android-context


    【解决方案1】:

    替换:

    DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics();
    

    与:

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    

    你不仅在这里不需要Application,任何与GUI相关的东西都应该使用Activity

    【讨论】:

      【解决方案2】:

      你不需要App.getAppContext()

      只是

       DisplayMetrics metrics = getResources().getDisplayMetrics();
      

      DisplayMetrics metrics = this.getResources().getDisplayMetrics();
      

      DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-27
        • 1970-01-01
        • 1970-01-01
        • 2013-02-06
        • 1970-01-01
        相关资源
        最近更新 更多