在Android Fragment中如何正确使用Retrofit2实现?

4

我正在使用Retrofit 2来消费一个API。我有一个服务(接口),它返回一个列表:

@GET("atenciones")
Call<List<Atencion>> getAtenciones(@Query("medico_id") int id, @Query("date1") String date1, @Query("date2") String date2)

我应该在哪里发出请求?在包含FragmentMainActivity中并使用Bundle发送结果列表?还是应该在Fragment中发出请求?这是一个列表而不是单个对象。哪种方式是正确的?

编辑

尝试在Fragment中调用Retrofit,这是我的代码:

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

}
}

有人能告诉我在fragment中调用retrofit2的正确方式吗?

1
旋转您的屏幕并看看会发生什么:D - phatnhse
你需要处理配置更改。除此之外,看起来还不错。你应该检查谷歌提供的新架构组件示例,GitHub示例可以让你了解如何进行架构设计,并给出调用Web服务的提示。 - Raghunandan
@Raghunandan 你说得对。这个问题涉及到太多的内容:片段生命周期、Retrofit实现、配置更改、架构等等... 这些链接可以帮助 matQ 了解相关知识 https://guides.codepath.com/android/Consuming-APIs-with-Retrofit 和 https://guides.codepath.com/android/Creating-and-Using-Fragments - phatnhse
谢谢大家!使用Postman并使用相同的参数显示了所有记录,但在我的Geny Motion模拟器中不行(使用API进行登录完美运行),它会显示null,这是输出:E/RecyclerView:未附加适配器; 跳过布局 E/RecyclerView:未附加适配器; 跳过布局 I/System.out:FALLOOOOO:null 应用程序终止。 - matQ
它以“失败”方式运行。为什么?有什么建议吗?输出没有显示其他错误。谢谢。 - matQ
1个回答

2

这取决于你的代码结构,但由于你使用了片段,我最好的猜测是你应该在Fragment中进行操作。

在Retrofit调用的onResponseOK中,你将会有类似这样的代码:

@Override
public void onResponseOK(Response<List<Atencion>> response) {
    ...
    //access data here
}

在回调函数中,您会获得您的列表。将列表传递给您的(我猜测是)Recycler/Listview 的适配器。像这样访问列表:
List<Atencion> myList = response.body();

你的代码看起来是正确的!如果回调函数在onFailure()中返回,请尝试执行t.printStackTrace()并检查它返回的错误。t.getMessage()通常返回null。 - Samuele Pontremoli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接