How to save response data in Callback

Viewed 464

This is my code:

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);
    }
}

I am new to use Retrofit. I wanted to save Retrofit response.body(), but when I debug with breakpoints, topics got null. What's the right way to save response data?

1 Answers
Related