这是Emanuelet的自定义FirebaseListAdapter,我已经通过它创建了FirebaseRecyclerAdapter。
public abstract class FirebaseRecyclerAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH > implements Filterable {
private static final String LOG_TAG = "FirebaseListAdapter";
private Query mRef;
private Class<T> mModelClass;
private int mLayout;
private LayoutInflater mInflater;
protected Class<VH> mViewHolderClass;
private List<T> mModels;
private List<T> mFilteredModels;
private List<String> mKeys = new ArrayList<>();
private Map<String, T> mModelKeys;
private Map<String, T> mFilteredKeys;
private ChildEventListener mListener;
private FirebaseRecyclerAdapter.ValueFilter valueFilter;
public FirebaseRecyclerAdapter(Query mRef, Class<T> mModelClass, int mLayout, Activity activity, Class<VH> viewHolderClass) {
this.mRef = mRef;
this.mModelClass = mModelClass;
this.mLayout = mLayout;
this.mViewHolderClass = viewHolderClass;
mInflater = activity.getLayoutInflater();
mModels = new ArrayList<>();
mModelKeys = new HashMap<>();
mListener = this.mRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
T model = dataSnapshot.getValue(FirebaseRecyclerAdapter.this.mModelClass);
mModelKeys.put(dataSnapshot.getKey(), model);
if (previousChildName == null) {
mModels.add(0, model);
} else {
T previousModel = mModelKeys.get(previousChildName);
int previousIndex = mModels.indexOf(previousModel);
int nextIndex = previousIndex + 1;
if (nextIndex == mModels.size()) {
mModels.add(model);
mKeys.add(dataSnapshot.getKey());
} else {
mModels.add(nextIndex, model);
mKeys.add(dataSnapshot.getKey());
}
}
notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.d(LOG_TAG, "onChildChanged");
String modelName = dataSnapshot.getKey();
T oldModel = mModelKeys.get(modelName);
T newModel = dataSnapshot.getValue(FirebaseRecyclerAdapter.this.mModelClass);
int index = mModels.indexOf(oldModel);
mModels.set(index, newModel);
mModelKeys.put(modelName, newModel);
notifyDataSetChanged();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(LOG_TAG, "onChildRemoved");
String modelName = dataSnapshot.getKey();
T oldModel = mModelKeys.get(modelName);
mModels.remove(oldModel);
mKeys.remove(dataSnapshot.getKey());
mModelKeys.remove(modelName);
notifyDataSetChanged();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(LOG_TAG, "onChildMoved");
String modelName = dataSnapshot.getKey();
T oldModel = mModelKeys.get(modelName);
T newModel = dataSnapshot.getValue(FirebaseRecyclerAdapter.this.mModelClass);
int index = mModels.indexOf(oldModel);
mModels.remove(index);
if (previousChildName == null) {
mModels.add(0, newModel);
mKeys.add(dataSnapshot.getKey());
} else {
T previousModel = mModelKeys.get(previousChildName);
int previousIndex = mModels.indexOf(previousModel);
int nextIndex = previousIndex + 1;
if (nextIndex == mModels.size()) {
mModels.add(newModel);
mKeys.add(dataSnapshot.getKey());
} else {
mModels.add(nextIndex, newModel);
mKeys.add(dataSnapshot.getKey());
}
}
notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError error) {
Log.e("FirebaseListAdapter", "Listen was cancelled, no more updates will occur");
}
});
}
public void cleanup() {
mRef.removeEventListener(mListener);
mModels.clear();
mModelKeys.clear();
mKeys.clear();
}
@Override
public int getItemCount() {
return mModels.size();
}
public T getItem(int position) {
return mModels.get(position);
}
@Override
public void onBindViewHolder(VH holder, int position) {
T model = getItem(position);
populateViewHolder(holder, model, position, mKeys);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public int getItemViewType(int position) {
return mLayout;
}
public void remove(String key) {
T oldModel = mModelKeys.get(key);
mModels.remove(oldModel);
mKeys.remove(key);
mModelKeys.remove(key);
notifyDataSetChanged();
}
@Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
try {
Constructor<VH> constructor = mViewHolderClass.getConstructor(View.class);
return constructor.newInstance(view);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
protected abstract void populateViewHolder(VH viewHolder, T model, int position, List<String> mKeys);
public void addSingle(DataSnapshot snapshot) {
T model = snapshot.getValue(FirebaseRecyclerAdapter.this.mModelClass);
mModelKeys.put(snapshot.getKey(), model);
mModels.add(model);
mKeys.add(snapshot.getKey());
notifyDataSetChanged();
}
public void update(DataSnapshot snapshot, String key) {
T oldModel = mModelKeys.get(key);
T newModel = snapshot.getValue(FirebaseRecyclerAdapter.this.mModelClass);
int index = mModels.indexOf(oldModel);
if (index >= 0) {
mModels.set(index, newModel);
mModelKeys.put(key, newModel);
notifyDataSetChanged();
}
}
public boolean exists(String key) {
return mModelKeys.containsKey(key);
}
@Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new FirebaseRecyclerAdapter.ValueFilter();
}
return valueFilter;
}
protected abstract List<T> filters(List<T> models, CharSequence constraint);
private class ValueFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new Filter.FilterResults();
if (mFilteredModels == null) {
mFilteredModels = new ArrayList<>(mModels);
mFilteredKeys = new HashMap<>(mModelKeys);
}
if (constraint != null && constraint.length() > 0) {
List<T> filtered = filters(mFilteredModels, constraint);
results.count = filtered.size();
results.values = filtered;
mModelKeys = filterKeys(mModels);
} else {
results.count = mFilteredModels.size();
results.values = mFilteredModels;
mModelKeys = mFilteredKeys;
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
Log.d(LOG_TAG, "filter for " + constraint + ", results nr: " + results.count);
mModels = (List<T>) results.values;
notifyDataSetChanged();
}
}
protected abstract Map<String, T> filterKeys(List<T> mModels);
}
使用FirebaseRecyclerAdapter扩展PostsQueryAdapter
public class FirebasePostsQueryAdapter extends FirebaseRecyclerAdapter<Feeds, PostViewHolder> {
Activity mActivity;
Query query;
public FirebasePostsQueryAdapter(Query mRef, int mLayout, Activity activity, Class<PostViewHolder> viewHolderClass) {
super(mRef, Feeds.class, mLayout, activity, viewHolderClass);
this.query = mRef;
this.mActivity = activity;
}
@Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Feeds model, final int position, final List<String> mKeys) {
viewHolder.setPhoto(model.getThumb_url());
viewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString(
(long) model.getTimestamp()).toString());
viewHolder.setAuthor(model.getUser().getFull_name(), model.getUser().getUid());
viewHolder.setIcon(model.getUser().getProfile_picture(), model.getUser().getUid());
viewHolder.setText(model.getText());
viewHolder.mPhotoView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mActivity, SingleVideoView.class);
intent.putExtra(Constants.INTENT_VIDEO,model.getVideo_url());
intent.putExtra(Constants.KEY, mKeys.get(position));
mActivity.startActivity(intent);
}
});
ValueEventListener likeListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
viewHolder.setNumLikes(dataSnapshot.getChildrenCount());
if (dataSnapshot.hasChild(FirebaseUtil.getCurrentUserId())) {
viewHolder.setLikeStatus(PostViewHolder.LikeStatus.LIKED, mActivity);
} else {
viewHolder.setLikeStatus(PostViewHolder.LikeStatus.NOT_LIKED, mActivity);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseUtil.getLikesRef().child(mKeys.get(position)).addValueEventListener(likeListener);
viewHolder.mLikeListener = likeListener;
}
@Override
protected List<Feeds> filters(List<Feeds> models, CharSequence constraint) {
return null;
}
@Override
protected Map<String, Feeds> filterKeys(List<Feeds> mModels) {
return null;
}
}
在哪里将数据填充到FirebasePostsQueryAdapter中
@Override
public void onCreate() {
super.onCreate();
mFirebaseRef = FirebaseDatabase.getInstance().getReference(POSTS_STRING);
mFirebaseRef.keepSynced(true);
this.geoFire = new GeoFire(FirebaseDatabase.getInstance().getReference(GEO_POINTS));
mItemListAdapter = new FirebasePostQueryAdapter(mFirebaseRef.equalTo(GEOFIRE_CHILD), getActivity(), R.layout.list_item_items);
}
@Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
center = new GeoLocation(MainActivity.mLastLocation.getLatitude(), MainActivity.mLastLocation.getLongitude());
if (!mActiveGeoQuery) {
center = new GeoLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
startGeoQuery();
mAdapter.notifyDataSetChanged();
}
center = new GeoLocation(MainActivity.mLastLocation.getLatitude(), MainActivity.mLastLocation.getLongitude());
if (center.latitude != 0 && center.longitude != 0 && !mActiveGeoQuery) {
startGeoQuery();
} else if (mActiveGeoQuery) {
Log.d(TAG, "geoquery already active");
} else {
Log.d(TAG, "center not setted");
if (Double.isNaN(mCurrentLocation.getLatitude()) && mCurrentLocation.getLatitude() != 0) {
center = new GeoLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
startGeoQuery();
}
}
fragment.checkForItems();
}
private void startGeoQuery() {
query = geoFire.queryAtLocation(center, 2);
Log.d(TAG, "center: " + center.toString() + ", radius: " + 2);
query.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
Log.d(TAG, "Key " + key + " entered the search area at [" + location.latitude + "," + location.longitude + "]");
DatabaseReference tempRef = mFirebaseRef.child(key);
tempRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
String key = snapshot.getKey();
if (!mAdapter.exists(key)) {
Log.d(TAG, "item added " + key);
mAdapter.addSingle(snapshot);
mAdapter.notifyDataSetChanged();
} else {
Log.d(TAG, "item updated: " + key);
mAdapter.update(snapshot, key);
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onKeyExited(String key) {
Log.d(TAG, "deal " + key + " is no longer in the search area");
mAdapter.remove(key);
fragment.isListEmpty();
}
@Override
public void onKeyMoved(String key, GeoLocation location) {
Log.d(TAG, String.format("Key " + key + " moved within the search area to [%f,%f]", location.latitude, location.longitude));
DatabaseReference tempRef = mFirebaseRef.child(key);
tempRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
String key = snapshot.getKey();
if (!mAdapter.exists(key)) {
Log.d(TAG, "item added " + key);
mAdapter.addSingle(snapshot);
mAdapter.notifyDataSetChanged();
} else {
Log.d(TAG, "item updated: " + key);
mAdapter.update(snapshot, key);
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onGeoQueryReady() {
Log.d(TAG, "All initial data has been loaded and events have been fired!");
fragment.isListEmpty();
mActiveGeoQuery = true;
}
@Override
public void onGeoQueryError(DatabaseError error) {
Log.e(TAG, "There was an error with this query: " + error);
mActiveGeoQuery = false;
}
});
fragment.bindRecyclerView();
}