Clearing the global ArrayList also clears the other… here is a solution to the problem.
Clearing the global ArrayList also clears the other
I have a very strange bug.
I’m writing a generic class and in one of its methods, there’s a weird thing. Here is the class code (incomplete):
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();
}
}
When I call the function refreshData(),
the global ArrayList is cleared and the local ArrayList
is cleared. Here is the log:
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
I just want to clone a local array to a global array.
Edit:
The function is called in the subclass.
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);
}
});
Solution
In your refreshData(), the two lists you use are the same.
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();
}