如何添加不同项目的数据?

时间:2018-04-26 04:36:01

标签: java android firebase firebase-realtime-database

大家好我有问题。我需要加上不同商品的价格,但我不知道怎么做?我正在使用Firebase和Android Studio。

我有下一个数据库结构:

a/myCart
    a
       --- name: Pizza
       ---price: 5
       ---image: https://im...

    b
       ---name: Soup
       ---price: 12
       ---image: https://im...

我需要在TextView中显示我的购物车总数,在此示例中:$ 17.00

我正在使用Firebase用户界面。

我的代码就像:

public class Cart extends AppCompatActivity {
    FirebaseRecyclerAdapter<MyData, myViewHolder3> adapter = null;
    int total;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

/////I need to show the total here

        final TextView txtTotal = (TextView) findViewById(R.id.total);

        RecyclerView r = (RecyclerView) findViewById(R.id.listaCart);
        final FirebaseDatabase database = FirebaseDatabase.getInstance();

        final String user = "a";
        final DatabaseReference myRef1 = database.getReference("users/"+user+"/myCart");

        r.setHasFixedSize(true);

        ////
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        r.setLayoutManager(layoutManager);

           adapter = new FirebaseRecyclerAdapter<MyData, myViewHolder3>(
                MyData.class, R.layout.cart_list, myViewHolder3.class, myRef1
        ) {
            @Override
            protected void populateViewHolder(final myViewHolder3 viewHolder, final MyData s, final int position) {
                // 

          final String key = adapter.getRef(position).getKey();

            viewHolder.setPrice(["$"+price+".00");


            viewHolder.setName(s.getName());
            viewHolder.setImageProduct(s.getImage());

            }
        };
        r.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
}

这是我购物车活动的一部分,请帮助我!

1 个答案:

答案 0 :(得分:2)

假设myCart节点是Firebase根目录的直接子节点且price属性的类型为Integer,为了汇总所有这些价格,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference myCartRef = rootRef.child("myCart");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int total = 0
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int price = ds.child("price").getValue(Integer.class);
            total = total + price;
        }
        Log.d("TAG", "total = " + total);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
myCartRef.addListenerForSingleValueEvent(valueEventListener);

输出结果为:total = 17