尝试在空对象引用问题上调用虚拟方法“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"