FirebaseDatabase如何熟悉Firestore

时间:2019-06-29 09:36:14

标签: android firebase firebase-realtime-database google-cloud-firestore

我对Firebase实时数据库有点熟悉,但是我从未使用过FireStore。我对消防站的工作方式感到困惑。我有以下代码:

mAdapter.setOnItemClickListener(new MealAdapter.OnItemClickListener() {
            @Override
    FirebaseFirestore.getInstance().collection("Users")
                            .document(currentUserUid)
                            .collection("Meal Planner")
                            .document(meals.get(position).getId()).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Toast.makeText(MealPlanner.this, "Meal has been removed", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            });

        }

    @Override
        protected void onStart() {
            super.onStart();

            FirebaseFirestore.getInstance().collection("Users")
                    .document(currentUserUid).collection("Meal Planner").addSnapshotListener(this, new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
                    if(e != null){
                        return;
                    }

                    for(DocumentChange dc : documentSnapshots.getDocumentChanges()){

                        Meal meal = dc.getDocument().toObject(Meal.class);

                        switch(dc.getType()){
                            case ADDED:

                                meals.add(meal);
                                mAdapter.notifyItemRangeInserted(dc.getNewIndex(), meals.size());

                                totalCalories();
                                break;

                            case REMOVED:
                                meals.remove(dc.getOldIndex());
                                mAdapter.notifyItemRemoved(dc.getOldIndex());
                                mAdapter.notifyItemRangeRemoved(dc.getOldIndex(), meals.size());
                                totalCalories();
                                break;

                        }
                    }
                }
            });

        }

该代码如何针对Firebase进行“翻译”?尚未尝试过,但就目前为止,据我了解,是这样的:

mAdapter.setOnItemClickListener(new MealAdapter.OnItemClickListener() {
            @Override
            public void onDeleteClick(int position) {

                FirebaseDatabase.getInstance().getReference().child( "Users")
                        .child(currentUserUid)
                        .child("Meal Planner")
                        .child(meals.get(position).getId()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(MealPlannerActivity.this, "Meal has been removed", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        });

    }

甚至不确定这部分是否正确。我完全不知道第二部分。有人熟悉这两种方法可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

此代码使用Firestore API:

FirebaseFirestore.getInstance().collection("Users")
        .document(currentUserUid).collection("Meal Planner").addSnapshotListener(this, new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
        if(e != null){
            return;
        }

        for(DocumentChange dc : documentSnapshots.getDocumentChanges()){

            Meal meal = dc.getDocument().toObject(Meal.class);

            switch(dc.getType()){
                case ADDED:

                    meals.add(meal);
                    mAdapter.notifyItemRangeInserted(dc.getNewIndex(), meals.size());

                    totalCalories();
                    break;

                case REMOVED:
                    meals.remove(dc.getOldIndex());
                    mAdapter.notifyItemRemoved(dc.getOldIndex());
                    mAdapter.notifyItemRangeRemoved(dc.getOldIndex(), meals.size());
                    totalCalories();
                    break;

            }
        }
    }
});

以上内容使用Realtime Database API转换为以下代码:

FirebaseDatabase.getInstance().getReference().child( "Users")
  .child(currentUserUid)
  .child("Meal Planner")
  .addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());

        Meal meal = dataSnapshot.getValue(Meal.class);
        meals.add(meal);

        mAdapter.notifyDataSetChanged();

        // TODO: to be able to notify the adapter more granularly, you'll have to keep track of the index yourself
        //mAdapter.notifyItemRangeInserted(dc.getNewIndex(), meals.size());

        totalCalories();    
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());

        // A meal has changed, use the key to determine if we are displaying this
        // meal and if so displayed the changed meal.

        // ...
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());

        // A mean has been removed, use the key to determine if we are displaying this
        // comment and if so remove it.
        String mealKey = dataSnapshot.getKey();

        // ...
    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());

        // A meal has changed position, use the key to determine if we are
        // displaying this meal and if so move it.

        // ...
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.w(TAG, "meals:onCancelled", databaseError.toException());
        Toast.makeText(mContext, "Failed to load meals.",
                Toast.LENGTH_SHORT).show();
    }
};

另请参阅listening for child events上的Firebase文档。