我正在编写一个通用类,在其中一种方法中,有一件奇怪的事.这里的类代码(不完全):
public abstract class GenericFragment<M extends BaseModel, A extends BaseAdapter> extends HtmlFragment {
private ArrayList<M> datas = new ArrayList<>();
private A adapter;
protected abstract String getUrl();
protected abstract A setAdapter();
protected A getAdapter() {
if(adapter == null) {
adapter = setAdapter();
}
return adapter;
}
protected ArrayList<M> getDatas() {
return datas;
}
protected void refreshData(ArrayList<M> datas) {
Log.d("before glob", String.valueOf(this.datas.size()));
Log.d("before loc", String.valueOf(datas.size()));
this.datas.clear();
Log.d("clear glob", String.valueOf(this.datas.size()));
Log.d("clear loc", String.valueOf(datas.size()));
this.datas.addAll(datas);
Log.d("after glob", String.valueOf(this.datas.size()));
Log.d("after loc", String.valueOf(datas.size()));
getAdapter().notifyDataSetChanged();
}
}
当我调用函数refreshData()时,将清除全局ArrayList,但也会清除本地ArrayList.以下是日志:
D/niviel: before glob: 5
D/niviel: before loc: 5
D/niviel: clear glob: 0
D/niviel: clear loc: 0
D/niviel: after glob: 0
D/niviel: after loc: 0
我只想将本地数组克隆到全局数组.
编辑:
requestData(activity, new requestDataCallback() {
@Override
public ArrayList<? extends BaseModel> parseDatas(Document document) {
return RecordProvider.getRecord(activity, document);
}
@Override
public void runOnUIThread(ArrayList<? extends BaseModel> datas) {
refreshData((ArrayList<Record>) datas);
}
});
解决方法:
在您的refreshData()中,您正在使用的两个列表相同.
protected void refreshData(ArrayList<M> datas) {
Log.d("before glob", String.valueOf(this.datas.size()));
Log.d("before loc", String.valueOf(datas.size()));
//here you are clearing datas
this.datas.clear();
//so Now your datas size will be 0
Log.d("clear glob", String.valueOf(this.datas.size()));
Log.d("clear loc", String.valueOf(datas.size()));
//here you are adding it to datas again whose size is already 0
this.datas.addAll(datas);
Log.d("after glob", String.valueOf(this.datas.size()));
Log.d("after loc", String.valueOf(datas.size()));
getAdapter().notifyDataSetChanged();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。