【发布时间】:2020-04-02 13:47:01
【问题描述】:
我有以下代码(它的骨架):
PostRequester(..., Fragment caller, final PostRequesterResponse callback ) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, baseUrl,
response -> {
if (callback != null && caller != null) {
callback.onResponse(response);
}
})...
从片段中调用上述示例:
...(this, result -> {
try {
if (result.contains("error")) {
throw new Exception(new JSONObject(result).getString("error"));
}
JSONObject jo = new JSONObject(result).getJSONObject("result");
tvIncome.setText(getString(R.string.income));
} catch (Exception e) {
...showPopup(getString(...));
}
我确实检查了回调和调用者不为空,但我得到以下信息:
Fatal Exception: java.lang.IllegalStateException: Fragment x2{8dc73ab (83fe8dc9-f7d2-4324-abf2-c4aae15c37ef)} not attached to a context.
第一个getString() 失败,然后异常的失败。也许调用者不是空的,但它是分离的。我可以添加caller.isDetached() 条件,但用户可能随时“返回”并分离片段。在每行代码之后检查 isDetached 并不是一个好主意。
在这种情况下可以做什么?谢谢
【问题讨论】:
标签: android android-fragments callback httprequest