如何解决尝试在空对象引用问题上调用虚拟方法“android.content.res.Resources android.content.Context.getResources()”
我在 MainActivity 以外的其他类中创建了方法(不在 onCreate 中),其中包括 val textView = TextView(MainActivity())
。它编译时没有错误,但我在运行时正好在这一行上得到了这个异常。完整的错误列表:
at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2951)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.Contextwrapper.getResources(Contextwrapper.java:91)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at androidx.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:607)
at android.view.View.<init>(View.java:4796)
at android.view.View.<init>(View.java:4948)
at android.widget.TextView.<init>(TextView.java:892)
at android.widget.TextView.<init>(TextView.java:886)
at android.widget.TextView.<init>(TextView.java:882)
at android.widget.TextView.<init>(TextView.java:878)
at currency.exchanger.UI.createTextViews(UI.kt:26)
at currency.exchanger.MainActivity.onCreate(MainActivity.kt:57)
at android.app.Activity.performCreate(Activity.java:7144)
at android.app.Activity.performCreate(Activity.java:7135)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2931)
任何想法如何从其他类成功实例化 TextView?
解决方法
试试这个方法可能对你有帮助
"--bird.flight"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。