简体   繁体   English

Android 应用上下文 null 在 Activity.onCreate()

[英]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.

相关问题 App在Activity.onCreate()Java android之前发生异常崩溃 - App crashes with exception before Activity.onCreate() Java android Android 4.2+ Activity.OnCreate 片段 - Android 4.2+ Activity.OnCreate Fragment Activity.onCreate上的StackOverflowError - StackOverflowError on Activity.onCreate Android中的AspectJ:切入点调用(* Activity.onCreate(..))不会选择Activity.onCreate()调用 - AspectJ in Android: pointcut call(* Activity.onCreate(..)) doesn't pick out Activity.onCreate() calls Android项目生命周期 - 活动生命周期之前(Activity.onCreate()) - Android Project Lifecycle - before Activity Lifecycle ( Activity.onCreate() ) 在Activity.onCreate(..)中显示警报 - Displaying alerts in Activity.onCreate(..) 在Activity.onCreate()上具有Robolectric的NullPointerExcepcion - NullPointerExcepcion with Robolectric on Activity.onCreate() Activity.OnCreate被调用两次 - Activity.OnCreate is called twice 在Activity.onCreate()中,为什么Intent.getExtras()有时会返回null? - In Activity.onCreate(), why does Intent.getExtras() sometimes return null? Android什么时候在Activity.onCreate()中的setContentView()之后第一次调用View.onMeasure()? - When does Android make first call to View.onMeasure() after setContentView() in Activity.onCreate()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM