In AOSP of Android 12 I am getting error "java.lang.NullPointerException: getInstance(requireContext()) must not be null" while using AppWidgetManager

huangapple go评论72阅读模式
英文:

In AOSP of Android 12 I am getting error "java.lang.NullPointerException: getInstance(requireContext()) must not be null" while using AppWidgetManager

问题

"java.lang.NullPointerException: getInstance(requireContext()) must not be null" 在使用 AppWidgetManager 时,在 Android 12 的 AOSP 中出现运行时错误。
"mAppWidgetManager = AppWidgetManager.getInstance(requireContext())"

英文:

In AOSP of Android 12 I am getting error "java.lang.NullPointerException: getInstance(requireContext()) must not be null" at runtime while using AppWidgetManager.
"mAppWidgetManager = AppWidgetManager.getInstance(requireContext())"

答案1

得分: 1

getContext() 返回一个可为空的 Context。

requireContext() 返回一个非空的 Context,或者在没有可用的情况下抛出异常。

如果您的代码处于生命周期阶段,在这个阶段您知道您的片段已连接到一个 Context,只需使用 requireContext() 来获取一个 Context,并且还可以使静态分析器满足潜在的 NPE 问题。

如果您的代码位于常规片段生命周期之外(比如说,一个异步回调),您可能最好使用 getContext(),自己检查其返回值,只有在它非空时才继续使用它。

在 Kotlin 中,明确指定空值的可能性更加重要,因为它已经内置到语言的类型系统中。

英文:

getContext() returns a nullable Context.

requireContext() returns a nonnull Context, or throws an exception when one isn't available.

If your code is in a lifecycle phase where you know your fragment is attached to a context, just use requireContext() to get a Context and also keep static analyzers happy about potential NPE issues.

If your code is outside of regular fragment lifecycle (say, an async callback), you might be better off using getContext(), checking its return value yourself and only proceeding using it if it was non-null.

Being explicit with nullability is even more important in Kotlin where it is built into the language's type system.

huangapple
  • 本文由 发表于 2023年7月3日 14:23:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定