我使用 Retrofit library处理来 self 的 WCF 网络服务的 JSON 响应。
RestService.getRestService().search("tools", new Callback<SearchResult>() {
@Override
public void success(SearchResult searchResult, Response response) {
if( searchResult == null) return;
textView.setText(searchResult.toString());
} // end of success(
@Override
public void failure(RetrofitError error) {
showToast(R.string.internet_sikintisi);
}
});
我注意到,如果我离开调用此函数的 fragment 或 Activity ,我会收到错误消息。因为我在 Activity 或 fragment 尚不存在的 textView 中设置了文本。
我把代码修改成这样:
RestService.getRestService().search("tools", new Callback<SearchResult>() {
@Override
public void success(SearchResult searchResult, Response response) {
if( searchResult == null) return;
try{
textView.setText(searchResult.toString());
} catch(Exception e) {}
} // end of success(
@Override
public void failure(RetrofitError error) {
try{
showToast(R.string.internet_sikintisi);
} catch(Exception e) {}
}
});
基本上,问题已解决,应用程序不会在用户每次立即进出时崩溃。这个问题可能还有更好的解决方案。
我检查过 Retrofit 没有有取消请求功能!
请您参考如下方法:
您需要添加检查成功和失败的方法,就像您在使用异步任务检查上下文是否仍然存在时一样,或者创建一个您在 Activity 或 fragment 的 onResume/onPause 上设置的 isActive 字段。