android - Callback中如何保存响应数据

标签 android retrofit2

这是我的代码:

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/

相关文章:

android - 你如何从android http get访问本地端口8080 url

android - 自定义调用适配器改造中的通用类型

java - 如何使用 Retrofit 2 获取字符串响应?

android - 在 jython 中编写 Android 应用程序

android - 如何从同一代码库为多个客户端构建移动应用程序

android - 如何在 Google Maps Android API V2 中获取位置及其更新

android - 如何在自定义对象的android中使用ArrayAdapter

kotlin - 数据类中的改造响应 null

android - 使用 GSON : response. body() 进行改造,返回带有空字段的对象

android - 如何读取 JSON 数组?