繁体   English   中英

Null 在 Fragment 中创建 Toast 后指针异常

[英]Null Pointer Exception after creating Toast in Fragment

当我的 API 请求由于无 Internet 连接而无法工作时,我正在尝试显示 Toast。 首先,我只是尝试在 try-block 失败后立即显示 Toast,然后我想在 catch-block 中显示 Toast。 我尝试了 developer.android.com 的方法,但我什至无法启动应用程序。

我在 catch-block 中的代码是这样的:

} catch {
Context context = getApplicationContext();
Toast.makeText(context, "No Internet Connection.", Toast.LENGTH_SHORT).show();
}

我似乎对getApplicationContext()方法有问题,因为它以红色突出显示。 这似乎是一个问题,因为我在片段中使用这个。 我使用Activity activity = getActivity()阅读了一些内容,但是当尝试将此activity作为上下文插入到makeText()方法中时,我收到以下错误消息:

E/AndroidRuntime: FATAL EXCEPTION: Thread-4
    Process: com.example.dhapp, PID: 16158
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:287)
        at android.widget.Toast.<init>(Toast.java:256)
        at android.widget.Toast.makeText(Toast.java:891)
        at android.widget.Toast.makeText(Toast.java:879)
        at com.example.dhapp.SearchFragment$apiThread.run(SearchFragment.java:112)

关于我如何让它工作的任何提示? 非常感谢提前!

听起来您没有从主线程中调用Toast.makeText() 您调用的线程需要访问 UI 才能显示 Toast。

这个 SO 线程可能会给你一些指示。

您不能在非主线程上显示 Toast。 您需要从主线程中调用 Toast.makeText() (以及处理 UI 的大多数其他函数)。 您可以在Can't toast on a thread that has not called Looper.prepare()找到一些解决方案, 如何在 Android 上显示来自后台线程的 Toast?

getApplicationContext()的问题是您在一个片段中,您应该以这种方式获取活动上下文

Toast.makeText(getContext(), "No Internet Connection.", Toast.LENGTH_SHORT).show();

它在 Fragments.java 上实现的 getContext() 方法,因此您不需要调用getApplicationContext()因为它仅可用于活动而不是片段。

   /**
     * Return the {@link Context} this fragment is currently associated with.
     *
     * @see #requireContext()
     */
    @Nullable
    public Context getContext() {
        return mHost == null ? null : mHost.getContext();
    }

您可以尝试 requireActivity() 而不是使用 getApplicationContext()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM