Retrofit2 in Android Fragment how to implement correctly?

Viewed 5965

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?

Edit

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?

1 Answers
Related