这是我的代码:
public class TopicsFragment extends Fragment {
TopicList topicList;
List<Map<String, Object>> topics;
TopicsAdapter adapter;
FragmentActivity listener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity) {
this.listener = (FragmentActivity) context;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RubyChinaService service =
RubyChinaApi.getInstance().getRubyChinaService();
//Create a call instance for looking up Retrofit topics.
Call<TopicList> call = service.getTopics();
call.enqueue(new Callback<TopicList>() {
@Override
public void onResponse(Call<TopicList> call,
Response<TopicList> response) {
topicList = response.body();
topics = DataUtil.ObjectToMapList(topicList);
Log.i("debug", topicList.getTopics().get(0).title);
}
@Override
public void onFailure(Call<TopicList> call, Throwable t) {
t.printStackTrace();
}
});
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
adapter = new TopicsAdapter(listener, topics, R.layout.item_topic,
new String[]{
"authorIcon",
"topicTitle",
"topicAuthor",
"repliesCount"
},
new int[]{
R.id.authorIcon,
R.id.topicTitle,
R.id.topicAuthor,
R.id.repliesCount
}
);
return inflater.inflate(R.layout.fragment_topics, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
ListView lv = (ListView) view.findViewById(R.id.lvItems);
lv.setAdapter(adapter);
}
}
我是 Retrofit 的新手。我想保存 Retrofit response.body()
,但是当我使用断点进行调试时,topics
得到了 null
。保存响应数据的正确方法是什么?
最佳答案
确保响应确实有效。您可以使用 response.isSuccess()
或 response.isSuccessful()
进行检查,具体取决于您使用的 Retrofit 版本。如果失败,请查看可通过 response.raw().code()
访问的 HTTP 状态代码。
关于android - Callback中如何保存响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881020/