This repository has been archived by the owner on Sep 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathRealmBasedRecyclerViewAdapter.java
636 lines (564 loc) · 23.9 KB
/
RealmBasedRecyclerViewAdapter.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
* Originally based on io.realm.RealmBaseAdapter
* =============================================
* Copyright 2014 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.tonicartos.superslim.GridSLM;
import com.tonicartos.superslim.LinearSLM;
import java.util.ArrayList;
import java.util.List;
import co.moonmonkeylabs.realmrecyclerview.LoadMoreListItemView;
import co.moonmonkeylabs.realmrecyclerview.R;
import co.moonmonkeylabs.realmrecyclerview.RealmRecyclerView;
import difflib.Chunk;
import difflib.Delta;
import difflib.DiffUtils;
import difflib.Patch;
import io.realm.internal.RealmObjectProxy;
import io.realm.internal.Row;
import io.realm.internal.TableOrView;
/**
* The base {@link RecyclerView.Adapter} that includes custom functionality to be used with the
* {@link RealmRecyclerView}.
*/
public abstract class RealmBasedRecyclerViewAdapter
<T extends RealmModel, VH extends RealmViewHolder>
extends RecyclerView.Adapter<RealmViewHolder> {
public class RowWrapper {
public final boolean isRealm;
public final int realmIndex;
public final int sectionHeaderIndex;
public final String header;
public RowWrapper(int realmIndex, int sectionHeaderIndex) {
this(true, realmIndex, sectionHeaderIndex, null);
}
public RowWrapper(int sectionHeaderIndex, String header) {
this(false, -1, sectionHeaderIndex, header);
}
public RowWrapper(boolean isRealm, int realmIndex, int sectionHeaderIndex, String header) {
this.isRealm = isRealm;
this.realmIndex = realmIndex;
this.sectionHeaderIndex = sectionHeaderIndex;
this.header = header;
}
}
private static final List<Long> EMPTY_LIST = new ArrayList<>(0);
private Object loadMoreItem;
private Object footerItem;
protected final int HEADER_VIEW_TYPE = 100;
private final int LOAD_MORE_VIEW_TYPE = 101;
private final int FOOTER_VIEW_TYPE = 102;
private Context context;
protected LayoutInflater inflater;
protected RealmResults<T> realmResults;
protected List ids;
private List<RowWrapper> rowWrappers;
private RealmChangeListener<RealmResults<T>> listener;
private boolean animateResults;
private boolean addSectionHeaders;
private String headerColumnName;
private long animatePrimaryColumnIndex;
private RealmFieldType animatePrimaryIdType;
private long animateExtraColumnIndex;
private RealmFieldType animateExtraIdType;
public RealmBasedRecyclerViewAdapter(
Context context,
RealmResults<T> realmResults,
boolean automaticUpdate,
boolean animateResults,
String animateExtraColumnName) {
this(
context,
realmResults,
automaticUpdate,
animateResults,
false,
null,
animateExtraColumnName);
}
public RealmBasedRecyclerViewAdapter(
Context context,
RealmResults<T> realmResults,
boolean automaticUpdate,
boolean animateResults) {
this(context, realmResults, automaticUpdate, animateResults, false, null);
}
public RealmBasedRecyclerViewAdapter(
Context context,
RealmResults<T> realmResults,
boolean automaticUpdate,
boolean animateResults,
boolean addSectionHeaders,
String headerColumnName) {
this(
context,
realmResults,
automaticUpdate,
animateResults,
addSectionHeaders,
headerColumnName,
null);
}
public RealmBasedRecyclerViewAdapter(
Context context,
RealmResults<T> realmResults,
boolean automaticUpdate,
boolean animateResults,
boolean addSectionHeaders,
String headerColumnName,
String animateExtraColumnName) {
if (context == null) {
throw new IllegalArgumentException("Context cannot be null");
}
this.context = context;
this.animateResults = animateResults;
this.addSectionHeaders = addSectionHeaders;
this.headerColumnName = headerColumnName;
this.inflater = LayoutInflater.from(context);
this.listener = (!automaticUpdate) ? null : getRealmChangeListener();
rowWrappers = new ArrayList<>();
// If automatic updates aren't enabled, then animateResults should be false as well.
this.animateResults = (automaticUpdate && animateResults);
if (animateResults) {
animatePrimaryColumnIndex = realmResults.getTableOrView().getTable().getPrimaryKey();
if (animatePrimaryColumnIndex == TableOrView.NO_MATCH) {
throw new IllegalStateException(
"Animating the results requires a primaryKey.");
}
animatePrimaryIdType = realmResults.getTableOrView().getColumnType(animatePrimaryColumnIndex);
if (animatePrimaryIdType != RealmFieldType.INTEGER &&
animatePrimaryIdType != RealmFieldType.STRING) {
throw new IllegalStateException(
"Animating requires a primary key of type Integer/Long or String");
}
if (animateExtraColumnName != null) {
animateExtraColumnIndex = realmResults.getTableOrView().getTable()
.getColumnIndex(animateExtraColumnName);
if (animateExtraColumnIndex == TableOrView.NO_MATCH) {
throw new IllegalStateException(
"Animating the results requires a valid animateColumnName.");
}
animateExtraIdType = realmResults.getTableOrView().getColumnType(animateExtraColumnIndex);
if (animateExtraIdType != RealmFieldType.INTEGER &&
animateExtraIdType != RealmFieldType.STRING &&
animateExtraIdType != RealmFieldType.DATE) {
throw new IllegalStateException(
"Animating requires a animateColumnName of type Int/Long or String");
}
} else {
animateExtraColumnIndex = -1;
}
}
if (addSectionHeaders && headerColumnName == null) {
throw new IllegalStateException(
"A headerColumnName is required for section headers");
}
updateRealmResults(realmResults);
}
public abstract VH onCreateRealmViewHolder(ViewGroup viewGroup, int viewType);
public abstract void onBindRealmViewHolder(VH holder, int position);
public VH onCreateFooterViewHolder(ViewGroup viewGroup) {
throw new IllegalStateException("Implementation missing");
}
public void onBindFooterViewHolder(VH holder, int position) {
throw new IllegalStateException("Implementation missing");
}
public RealmViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
View view = inflater.inflate(R.layout.header_item, viewGroup, false);
return new RealmViewHolder((TextView) view);
}
public void onBindHeaderViewHolder(RealmViewHolder holder, int position) {
String header = rowWrappers.get(position).header;
final GridSLM.LayoutParams layoutParams =
GridSLM.LayoutParams.from(holder.itemView.getLayoutParams());
holder.headerTextView.setText(header);
if (layoutParams.isHeaderInline()) {
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
} else {
layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
public Context getContext() {
return context;
}
/**
* DON'T OVERRIDE THIS METHOD. Implement onCreateRealmViewHolder instead.
*/
@Override
public final RealmViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == HEADER_VIEW_TYPE) {
return onCreateHeaderViewHolder(viewGroup);
} else if (viewType == LOAD_MORE_VIEW_TYPE) {
return new RealmViewHolder(new LoadMoreListItemView(viewGroup.getContext()));
} else if (viewType == FOOTER_VIEW_TYPE) {
return onCreateFooterViewHolder(viewGroup);
}
return onCreateRealmViewHolder(viewGroup, viewType);
}
/**
* DON'T OVERRIDE THIS METHOD. Implement onBindRealmViewHolder instead.
*/
@Override
@SuppressWarnings("unchecked")
public final void onBindViewHolder(RealmViewHolder holder, int position) {
if (getItemViewType(position) == LOAD_MORE_VIEW_TYPE) {
holder.loadMoreView.showSpinner();
} else if (getItemViewType(position) == FOOTER_VIEW_TYPE) {
onBindFooterViewHolder((VH) holder, position);
} else {
if (addSectionHeaders) {
final String header = rowWrappers.get(position).header;
final GridSLM.LayoutParams layoutParams =
GridSLM.LayoutParams.from(holder.itemView.getLayoutParams());
// Setup the header
if (header != null) {
layoutParams.isHeader = true;
onBindHeaderViewHolder(holder,position);
} else {
onBindRealmViewHolder((VH) holder, rowWrappers.get(position).realmIndex);
}
layoutParams.setSlm(LinearSLM.ID);
if (header != null) {
layoutParams.setFirstPosition(position);
} else {
layoutParams.setFirstPosition(rowWrappers.get(position).sectionHeaderIndex);
}
holder.itemView.setLayoutParams(layoutParams);
} else {
onBindRealmViewHolder((VH) holder, position);
}
}
}
public Object getLastItem() {
if (addSectionHeaders) {
return realmResults.get(rowWrappers.get(rowWrappers.size() - 1).realmIndex);
} else {
return realmResults.get(realmResults.size() - 1);
}
}
@Override
public int getItemCount() {
int extraCount = loadMoreItem == null ? 0 : 1;
extraCount += footerItem == null ? 0 : 1;
if (addSectionHeaders) {
return rowWrappers.size() + extraCount;
}
if (realmResults == null) {
return extraCount;
}
return realmResults.size() + extraCount;
}
@Override
public int getItemViewType(int position) {
if (loadMoreItem != null && position == getItemCount() - 1) {
return LOAD_MORE_VIEW_TYPE;
} else if (footerItem != null && position == getItemCount() - 1) {
return FOOTER_VIEW_TYPE;
} else if (!rowWrappers.isEmpty() && !rowWrappers.get(position).isRealm) {
return HEADER_VIEW_TYPE;
}
return getItemRealmViewType(position);
}
public int getItemRealmViewType(int position) {
return super.getItemViewType(position);
}
/**
* Ensure {@link #close()} is called whenever {@link Realm#close()} is called to ensure that the
* {@link #realmResults} are invalidated and the change listener removed.
*/
public void close() {
updateRealmResults(null);
}
/**
* Update the RealmResults associated with the Adapter. Useful when the query has been changed.
* If the query does not change you might consider using the automaticUpdate feature.
*
* @param queryResults the new RealmResults coming from the new query.
*/
public void updateRealmResults(RealmResults<T> queryResults) {
if (listener != null && realmResults != null) {
realmResults.removeChangeListener(listener);
}
realmResults = queryResults;
if (listener != null && realmResults != null) {
realmResults.addChangeListener(listener);
}
updateRowWrappers();
ids = getIdsOfRealmResults();
notifyDataSetChanged();
}
/**
* Method that creates the header string that should be used. Override this method to have
* a custom header.
*/
public String createHeaderFromColumnValue(Object columnValue) {
String result = null;
if (columnValue instanceof Boolean) {
result = columnValue.toString();
} else if (columnValue instanceof String) {
result = ((String) columnValue).substring(0, 1);
} else if (columnValue instanceof Long) {
result = columnValue.toString();
} else {
throw new IllegalStateException("columnType not supported");
}
return result;
}
public String getHeaderAtPosition(int position) {
for (int i = rowWrappers.size() - 1; i >= 0; i--) {
RowWrapper rowWrapper = rowWrappers.get(i);
if (!rowWrapper.isRealm) {
if (rowWrapper.sectionHeaderIndex <= position) {
return rowWrapper.header;
}
}
}
return null;
}
private List getIdsOfRealmResults() {
if (!animateResults || realmResults == null || realmResults.size() == 0) {
return EMPTY_LIST;
}
if (addSectionHeaders) {
List ids = new ArrayList(rowWrappers.size());
for (int i = 0; i < rowWrappers.size(); i++) {
final RowWrapper rowWrapper = rowWrappers.get(i);
if (rowWrapper.isRealm) {
ids.add(getRealmRowId(rowWrappers.get(i).realmIndex));
} else {
ids.add(rowWrappers.get(i).header);
}
}
return ids;
} else {
List ids = new ArrayList(realmResults.size());
for (int i = 0; i < realmResults.size(); i++) {
ids.add(getRealmRowId(i));
}
return ids;
}
}
private Object getRealmRowId(int realmIndex) {
Object rowPrimaryId;
RealmObjectProxy proxy = (RealmObjectProxy) realmResults.get(realmIndex);
Row row = proxy.realmGet$proxyState().getRow$realm();
if (animatePrimaryIdType == RealmFieldType.INTEGER) {
rowPrimaryId = row.getLong(animatePrimaryColumnIndex);
} else if (animatePrimaryIdType == RealmFieldType.STRING) {
rowPrimaryId = row.getString(animatePrimaryColumnIndex);
} else {
throw new IllegalStateException("Unknown animatedIdType");
}
if (animateExtraColumnIndex != -1) {
String rowPrimaryIdStr = (rowPrimaryId instanceof String)
? (String) rowPrimaryId : String.valueOf(rowPrimaryId);
if (animateExtraIdType == RealmFieldType.INTEGER) {
return rowPrimaryIdStr + String.valueOf(row.getLong(animateExtraColumnIndex));
} else if (animateExtraIdType == RealmFieldType.STRING) {
return rowPrimaryIdStr + row.getString(animateExtraColumnIndex);
} else if (animateExtraIdType == RealmFieldType.DATE) {
return rowPrimaryIdStr + row.getDate(animateExtraColumnIndex).getTime();
} else {
throw new IllegalStateException("Unknown animateExtraIdType");
}
} else {
return rowPrimaryId;
}
}
private void updateRowWrappers() {
if (realmResults == null) {
return;
}
if (addSectionHeaders) {
String lastHeader = "";
int headerCount = 0;
int sectionFirstPosition = 0;
rowWrappers.clear();
final long headerIndex = realmResults.getTableOrView().getTable().getColumnIndex(headerColumnName);
int i = 0;
for (RealmModel result : realmResults) {
Object rawHeader;
RealmFieldType fieldType = ((RealmObjectProxy) result)
.realmGet$proxyState().getRow$realm().getColumnType(headerIndex);
if (fieldType == RealmFieldType.STRING) {
rawHeader = ((RealmObjectProxy) result)
.realmGet$proxyState().getRow$realm().getString(headerIndex);
} else if (fieldType == RealmFieldType.BOOLEAN) {
rawHeader = ((RealmObjectProxy) result)
.realmGet$proxyState().getRow$realm().getBoolean(headerIndex);
} else if (fieldType == RealmFieldType.INTEGER) {
rawHeader = ((RealmObjectProxy) result)
.realmGet$proxyState().getRow$realm().getLong(headerIndex);
} else {
throw new IllegalStateException("columnValue type not supported");
}
String header = createHeaderFromColumnValue(rawHeader);
if (!TextUtils.equals(lastHeader, header)) {
// Insert new header view and update section data.
sectionFirstPosition = i + headerCount;
lastHeader = header;
headerCount += 1;
rowWrappers.add(new RowWrapper(sectionFirstPosition, header));
}
rowWrappers.add(new RowWrapper(i++, sectionFirstPosition));
}
}
}
public List<RowWrapper> getRowWrappers() {
return rowWrappers;
}
private RealmChangeListener<RealmResults<T>> getRealmChangeListener() {
return new RealmChangeListener<RealmResults<T>>() {
@Override
public void onChange(RealmResults<T> element) {
if (animateResults && ids != null && !ids.isEmpty()) {
updateRowWrappers();
List newIds = getIdsOfRealmResults();
// If the list is now empty, just notify the recyclerView of the change.
if (newIds.isEmpty()) {
ids = newIds;
notifyDataSetChanged();
return;
}
Patch patch = DiffUtils.diff(ids, newIds);
List <Delta> deltas = patch.getDeltas();
ids = newIds;
if (deltas.isEmpty()) {
// Nothing has changed - most likely because the notification was for
// a different object/table
} else if (addSectionHeaders) {
// If sectionHeaders are enabled, the animations have some special cases and
// the non-animated rows need to be updated as well.
Delta delta = deltas.get(0);
if (delta.getType() == Delta.TYPE.INSERT) {
if (delta.getRevised().size() == 1) {
notifyItemInserted(delta.getRevised().getPosition());
} else {
final Chunk revised = delta.getRevised();
notifyItemRangeInserted(revised.getPosition(), revised.size());
}
} else if (delta.getType() == Delta.TYPE.DELETE) {
if (delta.getOriginal().size() == 1) {
notifyItemRemoved(delta.getOriginal().getPosition());
} else {
// Note: The position zero check is to hack around a indexOutOfBound
// exception that happens when the zero position is animated out.
if (delta.getOriginal().getPosition() == 0) {
notifyDataSetChanged();
return;
} else {
notifyItemRangeRemoved(
delta.getOriginal().getPosition(),
delta.getOriginal().size());
}
}
if (delta.getOriginal().getPosition() - 1 > 0) {
notifyItemRangeChanged(
0,
delta.getOriginal().getPosition() - 1);
}
if (delta.getOriginal().getPosition() > 0 && newIds.size() > 0) {
notifyItemRangeChanged(
delta.getOriginal().getPosition(),
newIds.size() - 1);
}
} else {
notifyDataSetChanged();
}
} else {
for (Delta delta : deltas) {
if (delta.getType() == Delta.TYPE.INSERT) {
notifyItemRangeInserted(
delta.getRevised().getPosition(),
delta.getRevised().size());
} else if (delta.getType() == Delta.TYPE.DELETE) {
notifyItemRangeRemoved(
delta.getOriginal().getPosition(),
delta.getOriginal().size());
} else {
notifyItemRangeChanged(
delta.getRevised().getPosition(),
delta.getRevised().size());
}
}
}
} else {
notifyDataSetChanged();
ids = getIdsOfRealmResults();
}
}
};
}
/**
* Adds the LoadMore item.
*/
public void addLoadMore() {
if (loadMoreItem != null || footerItem != null) {
return;
}
loadMoreItem = new Object();
notifyDataSetChanged();
}
/**
* Removes the LoadMoreItems;
*/
public void removeLoadMore() {
if (loadMoreItem == null) {
return;
}
loadMoreItem = null;
notifyDataSetChanged();
}
/**
* Adds the Footer item.
*/
public void addFooter() {
if (footerItem != null || loadMoreItem != null) {
return;
}
footerItem = new Object();
notifyDataSetChanged();
}
/**
* Removes the Footer;
*/
public void removeFooter() {
if (footerItem == null) {
return;
}
footerItem = null;
notifyDataSetChanged();
}
/**
* Called when an item has been dismissed by a swipe.
*
* Only supported with type linearLayout and thus the realmResults can be accessed directly.
* If it is extended to LinearLayoutWithHeaders, rowWrappers will have to be used.
*/
public void onItemSwipedDismiss(int position) {
final BaseRealm realm = realmResults.realm;
realm.beginTransaction();
realmResults.deleteFromRealm(position);
realm.commitTransaction();
}
}