Problem
Adapter data itself to use for GetView and GetCount, and the program is getcount in different methods of continuous getview, this brings a problem: After GetCount, the data is deleted by other threads, in the GetView when the cross-border
Solution Ideas
- Set up a concurrentadapter, the inside with two lists to store data, one is the external operation additions and deletions, a used for the actual drawing.
- When the external additions and deletions, temporarily do not change the internal list, so that there is no cross-border
- After the internal getcount again, if you find that the list has been modified externally, copy it again from the external.
Code
Public classconcurrentadapter<t> {//For external operation of list, external to its additions and deletions PrivateList<t> objectscached=NewArraylist<t> ();//For adapter internal calculations, from external copy. PrivateList<t> objects=NewArraylist<t> ();//For the number of cache list, when-1, indicates external modified list, need to update Private intcount=-1; Public int GetCount(){if(count==-1{synchronized (objectscached) {objects.clear (); Objects.addall (objectscached); Count=objects.size ();returnCount } }Else{returnCount } } PublicTGetObject(intPosition) {returnObjects.Get(position); } Public void AddObject(TObject) {synchronized (objectscached) {Objectscached.add (Object); count=-1; } } Public void addobjects(List<t> objects) {synchronized (objectscached) {Objectscached.addall (objects); count=-1; } } Public void setobjects(List<t> objects) {synchronized (objectscached) {objectscached.clear (); Objectscached.addall (objects); count=-1; } } Public void Removeobject(TObject) {synchronized (objectscached) {Objectscached.remove (Object); count=-1; } }}
Concurrency-Safe Adapter