-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecyclerViewCursorAdapter.java
109 lines (74 loc) · 2.53 KB
/
RecyclerViewCursorAdapter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.util.SortedList;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.util.SortedListAdapterCallback;
import android.view.View;
import java.util.HashSet;
import java.util.Set;
/** https://github.com/qvga/RecyclerViewCursorAdapter */
public abstract class RecyclerViewCursorAdapter<T, VH extends RecyclerViewCursorAdapter.ViewHolder> extends RecyclerView.Adapter<VH> {
private SortedList<T> sortedList;
private Set<T> previousCursorContent = new HashSet<>();
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
}
}
public RecyclerViewCursorAdapter() {
super();
}
/** If you just need a plain sortedlist */
public RecyclerViewCursorAdapter(@NonNull Class<T> klass, @Nullable Cursor cursor) {
setSortedList(new SortedList<>(klass, new SortedListAdapterCallback<T>(this) {
@Override
public int compare(T o1, T o2) {
return 0;
}
@Override
public boolean areContentsTheSame(T oldItem, T newItem) {
return false;
}
@Override
public boolean areItemsTheSame(T item1, T item2) {
return false;
}
}));
setCursor(cursor);
}
public void setCursor(Cursor cursor) {
switchCursor(cursor);
}
public void switchCursor(Cursor cursor) {
if (cursor == null) {
return;
}
Set<T> currentCursorContent = new HashSet<>();
sortedList.beginBatchedUpdates();
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
T item = fromCursorRow(cursor);
currentCursorContent.add(item);
sortedList.add(item);
}
for (T item : previousCursorContent) {
if (!currentCursorContent.contains(item)) {
sortedList.remove(item);
}
}
sortedList.endBatchedUpdates();
previousCursorContent = currentCursorContent;
}
abstract T fromCursorRow(Cursor cursor);
void setSortedList(SortedList<T> list) {
this.sortedList = list;
}
@Override
public int getItemCount() {
return sortedList.size();
}
public T getItem(int position) {
return sortedList.get(position);
}
}