如何从firebase数据库中的所有子项中获取特定值,然后添加它?

时间:2017-07-24 05:01:38

标签: android firebase firebase-realtime-database

Price存储在orders中,如图所示。而我想做的就是从每个孩子那里得到代价。即使该方法被调用的次数与orders中的子项数一样多,但for循环也不起作用。 total出错了。

Toast显示的是53和25然后25和15以及15和80的加法。它应该显示总共25,15,80,53。

UI of the layout

Firebase Database Structure

    @Override
    public void onStart() {
        super.onStart();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<ShowDataItems, 
  CheckoutActivity.ShowDataViewHolder>(ShowDataItems.class, 
  R.layout.show_data_items_checkout, ShowDataViewHolder.class, myRef) {

        public void populateViewHolder(final ShowDataViewHolder viewHolder, 
    final ShowDataItems model, final int position) {
            viewHolder.ItemName(model.getItemName());
            viewHolder.Price(model.getPrice());
            viewHolder.Image_Count(model.getItemCount());



            viewHolder.delete.setOnClickListener(new View.OnClickListener() 
             {
                @Override
                public void onClick(View view) {


   myRef.child(viewHolder.ItemName(model.getItemName())).child("ItemName")
   .setValue(null);

   myRef.child(viewHolder.ItemName(model.getItemName())).child("ItemCount")
   .setValue(null);
                    myRef.child(viewHolder.ItemName(model.getItemName())).child("Price").setValue(null);

                }
            });

            //OnClick Item
            viewHolder.itemView.setOnClickListener(new 
    View.OnClickListener() {

                @Override
                public void onClick(final View v) {
                    int s = position;
                    mFirebaseAdapter.getRef((s));

                }
            });

            calling++;

            for(int i = 0; i<calling; i++)
            {

                total = temp +price;
                temp = price;
                Toast.makeText(getApplicationContext(),""+ total, 
    Toast.LENGTH_LONG).show();

            }
        }
    };

1 个答案:

答案 0 :(得分:0)

只是一些逻辑错误,这是你应该如何计算。我添加了“toast shows checker”以确保每次只显示一个toast。

... class' variable

private Toast toast;
private int total = 0;

... inside the populateViewHolder method

total = total + price;
if (toast != null) {
    toast.cancel();
}
toast = Toast.makeText(getApplicationContext(), ""+ total, Toast.LENGTH_LONG);
toast.show();

希望这会有所帮助:)