[英]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.