简体   繁体   中英

How to update the data of an adapter correctly?

Is there a difference between:

@Override void onPostExecute(ArrayList<Items> rows) {  
   this.dataset.clear();  
   this.dataset.addAll(rows);  
   this.dataAdapter.notifyDataSetChanged();  
}  

and

@Override void onPostExecute(ArrayList<Items> rows) {  
   this.dataset.clear();  
   this.dataset = rows;  
   this.dataAdapter.notifyDataSetChanged();  
}  

Both seem to work correctly but most of the examples I have seen about this use the first pattern.
Is the second wrong?

i found answer on Doc Oracle,
+ addAll(Collection c): Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator + this.dataset = rows: just tell data in dataset will remove and fill all data from "rows" into dataset.

The difference between addAll() and the variable assignment is that addAll() according to the docs :

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

This means should a List be non-null, any objects added using the addAll() method would be appended to the end.

The variable assignment on the other hand would replace the current List stored in this.dataset with the List rows . This would therefore not append anything to the previous List.

However , as the method uses this.dataset.clear() which according to the docs :

Removes all of the elements from this list. The list will be empty after this call returns.

The functionality of the two methods is the same , as the list is empty before being appended to or overwritten.


Please note, to avoid a NullPointerException it would probably be best to add some sort of if-statement to check if this.dataset is null before calling this.dataset.clear();

In the second example, the this.dataset.clear() is also redundant, as the variable is overwritten immediately afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM