我是初学者,我正在尝试使用ArrayList
中的Interface
,我从这里的文章中得到了结构,问题是当我尝试在{ {1}}。
这个班是
Fragment
我需要使用onSuccess中的arraylist并在我的setAdapter方法中传递它,当我在setAdaper中传递它时问题是null,但是在onSuccess中它不是null,我该如何解决?抱歉语言清晰
这是 logcat:
public class NewsFRagment extends Fragment implements BackgroundTask.CallBack{
private ArrayList<NewsPOJO> arrayList1;
public NewsFRagment() {
// Required empty public constructor
}
@Override
public void onSuccess(ArrayList<NewsPOJO> arrayList) {
this.arrayList1 = arrayList;
Log.d("arraylist in onSuccess", String.valueOf(arrayList.size()));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.news_fragment, container, false);
BackgroundTask backgroundTask= new BackgroundTask(this.getActivity(),this);
backgroundTask.execute();
RecyclerView recyclerView= (RecyclerView) v.findViewById(R.id.rv_news);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
Log.d("Arraylist1 size", String.valueOf(+arrayList1.size()));
recyclerView.setAdapter(new MyRecyclerAdapter(this.getActivity(),arrayList1 ));
return v;
}
@Override
public String toString() {
return "News Fragment";
}
}
答案 0 :(得分:0)
检查回调发生的顺序......
您的arraylist可能无法初始化,当回调发生在setAdapter,因为您只声明它,您永远不会在构造函数中初始化它。与在OnSuccess回调中相反,您在其中接收arraylist引用作为输入并将本地实例变量设置为它。
视图的创建将是初始回调运行,因此如果您需要先传递列表,则需要首先启动它,例如,您可以添加到构造函数中进行初始化:
public NewsFRagment() {
// Required empty public constructor
arrayList1 = new ArrayList<NewsPOJO>();
}
或者您可以拥有一个特定的init方法,在首先在视图创建事件中执行所需的东西之后调用(如果您需要预先设置列表)
答案 1 :(得分:0)
@Override
public void onSuccess(ArrayList<NewsPOJO> arrayList) {
this.arrayList1 = arrayList;
Log.d("arraylist in onSuccess", String.valueOf(arrayList.size()));
// make sure ur fragment is done view loading before on success.
RecyclerView recyclerView= (RecyclerView) v.findViewById(R.id.rv_news);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
Log.d("Arraylist1 size", String.valueOf(+arrayList1.size()));
recyclerView.setAdapter(new MyRecyclerAdapter(this.getActivity(),arrayList1 ));
}
调用以下代码启动,显示进度对话框并取消成功
BackgroundTask backgroundTask= new BackgroundTask(this.getActivity(),this);
backgroundTask.execute();