我是改装的新手,我想让我的getData列表从onResponse正文列表中保存值,并在不同的程序中调用它.最简单的方法是什么?
我一直在尝试它,数据已经在onResponse中显示但是当我想在不同的过程中使用它时,值getData列表仍为null
我的onCreate
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getDataSeason();
listSeason=new ArrayList<>();
progress = new ProgressDialog(getActivity());
progress.setCancelable(false);
progress.setMessage("Loading. . .");
progress.show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getURL.GetMyURL())
.addConverterFactory(GsonConverterFactory.create())
.build();
SeasonAPI api = retrofit.create(SeasonAPI.class);
Call<SeasonList> call = api.getAllSeason();
call.enqueue(new Callback<SeasonList>() {
@Override
public void onResponse(Call<SeasonList> call, Response<SeasonList> response) {
progress.dismiss();
response.body();
for(int i=0;i<response.body().getResult().size();i++){
getData.add(i,response.body().getResult().get(i));
}
}
@Override
public void onFailure(Call<SeasonList> call, Throwable t) {
t.printstacktrace();
progress.dismiss();
Toast.makeText(getActivity(),"Network Connection Error",Toast.LENGTH_SHORT).show();
}
});}
字符串临时
我的getData列表
public class FragmentPromo extends Fragment {
public List<Season> getData;
我的季节清单
public class SeasonList {
@Serializedname("value")
@Expose
private Integer value;
@Serializedname("result")
@Expose
private List<Season> result = null;
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public List<Season> getResult() {
return result;
}
public void setResult(List<Season> result) {
this.result = result;
}}
当我想在oncreateView中显示getData值时,它为null
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_promo,container,false);
//Set date in Text View
txtDate=(TextView)view.findViewById(R.id.txtDateTime);
txtDate.setText(currendtDateTimeString);
myRecycleView=(RecyclerView)view.findViewById(R.id.season_view);
recycleViewAdapterSeason =new RecycleViewAdapterSeason(getContext(),listSeason);
myRecycleView.setLayoutManager(new linearlayoutmanager(getActivity()));
myRecycleView.setAdapter(recycleViewAdapterSeason);
getDataSeason();
Toast.makeText(getActivity(),getData.get(0).getNamaSeason(),Toast.LENGTH_SHORT).show();
return view;
}
解决方法:
>首先,在处理Retrofit时,最好制作一个Singleton类,你可以阅读这个设计模式以及它在内存管理方面是如何帮助的
>其次,在onResponse()为什么你在循环之前调用response.body()而不使用它?
>您将获得空指针异常,因为您希望在不初始化的情况下使用列表
>所有你要做的就是从SesaonList类创建一个对象并将它的值赋给你的响应,getData将通过调用getResult从对象获取season的列表来分配,这应该工作
@覆盖
public void onResponse(Call< SeasonList> call,Response< SeasonList> response){
progress.dismiss();
Seasonlist seasonlist = response.body();
getData = seasonlist.getResult();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。