当我的API请求由于无互联网连接而无法工作时,我正在尝试显示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)关于如何让它工作,有什么建议吗?提前谢谢你!
发布于 2021-04-02 23:15:12
听起来您并没有从主线程中调用Toast.makeText()。您从中调用的线程本质上需要访问UI才能显示Toast。
This SO thread可能会给你一些建议。
发布于 2021-04-02 23:24:30
不能在非主线程上显示Toast。您需要从主线程中调用Toast.makeText() (以及处理UI的大多数其他函数)。你可以在Can't toast on a thread that has not called Looper.prepare(),How do you display a Toast from a background thread on Android?上找到一些解决方案
getApplicationContext()的问题是您在一个片段中,您应该以这种方式获取活动上下文
Toast.makeText(getContext(), "No Internet Connection.", Toast.LENGTH_SHORT).show();getContext()方法是在Fragments.java上实现的,因此您不需要调用getApplicationContext(),因为它只在活动中可用,而不能从片段中获得。
/**
* Return the {@link Context} this fragment is currently associated with.
*
* @see #requireContext()
*/
@Nullable
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}发布于 2021-04-02 23:32:10
您可以尝试requireActivity(),而不是使用getApplicationContext()
https://stackoverflow.com/questions/66921333
复制相似问题