Last active
May 22, 2020 19:46
-
-
Save xingrz/95e4aa31e386b3629bc5 to your computer and use it in GitHub Desktop.
A RecyclerView.Adapter-like Adapter that binds RealmResults to ListView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.BaseAdapter; | |
import io.realm.RealmObject; | |
import io.realm.RealmResults; | |
public abstract class RealmAdapter<E extends RealmObject, VH extends RealmAdapter.ViewHolder> | |
extends BaseAdapter { | |
public static class ViewHolder { | |
public final View itemView; | |
public ViewHolder(View itemView) { | |
this.itemView = itemView; | |
this.itemView.setTag(this); | |
} | |
} | |
private RealmResults<E> results; | |
public abstract VH onCreateViewHolder(ViewGroup parent, int viewType); | |
public abstract void onBindViewHolder(VH holder, int position); | |
public void onViewRecycled(VH holder) { | |
} | |
public void setResults(RealmResults<E> results) { | |
this.results = results; | |
notifyDataSetChanged(); | |
} | |
@Override | |
public int getCount() { | |
return results == null ? 0 : results.size(); | |
} | |
@Override | |
public E getItem(int position) { | |
return results == null ? null : results.get(position); | |
} | |
@Override | |
public long getItemId(int position) { | |
return -1; | |
} | |
@Override | |
public View getView(int position, View convertView, ViewGroup parent) { | |
if (convertView == null) { | |
convertView = onCreateViewHolder(parent, getItemViewType(position)).itemView; | |
} else { | |
onViewRecycled(getViewHolder(convertView)); | |
} | |
onBindViewHolder(getViewHolder(convertView), position); | |
return convertView; | |
} | |
@SuppressWarnings("unchecked") | |
private VH getViewHolder(View view) { | |
return (VH) view.getTag(); | |
} | |
} |
sorry noob question, what is the main benefit using this Realm adapter?
Read this answer here from Pirate App for an even more sophisticated realm adapter that can add items remove items, swipe to delete, section the recyclerview http://stackoverflow.com/questions/28995380/best-practices-to-use-realm-with-a-recycler-view
thank u
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage