2016-03-09 45 views
3

響應數據這是我的代碼:如何保存在回調

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 response.body(),但是當我用斷點調試時,topics得到了null。什麼是保存響應數據的正確方法?

回答

0

確保響應真的有效。您可以使用response.isSuccess()response.isSuccessful()進行檢查,具體取決於您正在使用的Retrofit的版本。如果失敗,請查看可通過response.raw().code()訪問的HTTP狀態代碼。