3

I have a really weird bug.

I am programming a generic class and in one of its method, there is a strange thing. Here the class code (not completely):

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

And when I call the function refreshData() the global ArrayList is cleared but also the local ArrayList. Here are the logs:

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 the local array to the global array.

EDIT:

The function is called in a child class.

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

});
Allan Pereira
  • 2,572
  • 4
  • 21
  • 28

3 Answers3

3

In your refreshData(), both the lists u are using are 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();
}
Dhruvi
  • 1,971
  • 2
  • 10
  • 18
1

Ok I finally debugged my code. I noticed that the function refreshData() was passing in parameters the global ArrayList.

0

Learn about Java memory model. List is reference type of data, so you work with the same list.