Reputation: 617
I'm using Retrofit 2 to consume an API. I have a service (interface) which returns a list:
@GET("atenciones")
Call<List<Atencion>> getAtenciones(@Query("medico_id") int id, @Query("date1") String date1, @Query("date2") String date2)
Where should I do the request? In the MainActivity
which contains the Fragment
and send the result list using Bundle
? or should do the request in the Fragment? this is a list not a single object. Which is the correct way?
Try to call retrofit in Fragment, this is my code:
public class FragmentRendicion extends Fragment {
private LinearLayoutManager layoutManager;
View rootView;
APIService api;
public FragmentRendicion() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_rendicion, container, false);
api= ApiUtils.getAPIService();
getAtenciones();
return rootView;
}
private void getAtenciones() {
//using static parameters
Call<List<Atencion>> call= api.getAtenciones(293,"2014-10-13","2014-10-13");
call.enqueue(new Callback<List<Atencion>>() {
@Override
public void onResponse(Call<List<Atencion>> call, Response<List<Atencion>> response) {
System.out.println("estamos aquiiii "+response.message());
List<Atencion> atenciones= response.body();
layoutManager= new LinearLayoutManager(getActivity());
RecyclerView recycler= (RecyclerView)rootView.findViewById(R.id.rvRendicion);
recycler.setLayoutManager(layoutManager);
RvRendicionAdapter rvAdapter= new RvRendicionAdapter(atenciones);
recycler.setAdapter(rvAdapter);
}
@Override
public void onFailure(Call<List<Atencion>> call, Throwable t) {
System.out.println("FALLOOOOO: "+t.getMessage());//HERE RETUNRS NULL
}
});
}
}
Can someone tell me is if it correct way to call retrofit2 in fragment?
Upvotes: 4
Views: 6388
Reputation: 594
It depends on the structure of your code but since you are using fragments my best guess is you should do it in the Fragment
.
In the onResponseOK
of the Retrofit call you will have something like this:
@Override
public void onResponseOK(Response<List<Atencion>> response) {
...
//access data here
}
In the callback
you get your list. Pass the list to the adapter of your (I suppose) Recycler/Listview.
Access the list like this:
List<Atencion> myList = response.body();
Upvotes: 2