根据Firebase-Android中存储的值计算总计

时间:2018-07-13 12:05:13

标签: java android firebase google-cloud-firestore

我正在尝试根据用户在Cloud Firestore数据库中存储的数字创建总计。值的数量会有所不同,具体取决于用户添加到子集合中的项目数量。

我似乎无法弄清楚的是如何“拾取值(数据库中的itemCost)并将它们加在一起,然后显示为总成本。有人能指出我正确的方向吗?

我已经包含了该活动的代码(当前正在编写数据库查询),为该活动提供服务的List适配器,生成视图的模型类,最后是firebase路径的屏幕截图。希望能对您有所帮助:

enter image description here

这是活动:

public class UsersMenuActivity extends AppCompatActivity {

private static final String TAG = "UserMenuActivity";
public static String finalId;
public static int totalCalsToPass;
public Context umContext;
public String venueId;
public Button myButton;
public int totalCalsData;
public int totalCals = 0;
Toolbar menuToolbar;
private FirebaseFirestore umFirestore;
private FirebaseAuth umFirebaseAuth;
private FirebaseAuth mAuth;
private RecyclerView umRecyclerView;
private List<UserMenu> userMenu;
private View.OnClickListener umClickListener;
private UserMenuListAdapter userMenuListAdapter;
private String getUserId;
private TextView passedCalContent;
//FOR THE CAL COUNT
private List<UserMenu> calsList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_users_menu );

    menuToolbar = findViewById( R.id.menu_toolbar );
    setSupportActionBar( menuToolbar );

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled( false );
        getSupportActionBar().setDisplayShowHomeEnabled( false );
    }

    myButton = findViewById( R.id.remove_button );

    userMenu = new ArrayList<>();
    userMenuListAdapter = new UserMenuListAdapter( getApplicationContext(), userMenu, umClickListener );

    umRecyclerView = (RecyclerView) findViewById( R.id.user_menu_recycler_view );
    umRecyclerView.setHasFixedSize( true );
    umRecyclerView.setLayoutManager( new LinearLayoutManager( this ) );
    umRecyclerView.setAdapter( userMenuListAdapter );

    passedCalContent = findViewById( R.id.users_menu_calories_set );
    passedCalContent.setText( valFromAct1 );

    umFirestore = FirebaseFirestore.getInstance();
    umFirebaseAuth = FirebaseAuth.getInstance();

    getUserId = Objects.requireNonNull( umFirebaseAuth.getCurrentUser() ).getUid();


    CollectionReference userMenuRef = umFirestore.collection( "AppUsers" )
            .document( getUserId )
            .collection( "UserMenu" );


    userMenuRef.limit( 100 ).addSnapshotListener( (documentSnapshots, e) -> {

        if (e != null) {
            Log.d( TAG, "Error: " + e.getMessage() );

        }
        assert documentSnapshots != null;
        for (DocumentChange doc : Objects.requireNonNull( documentSnapshots ).getDocumentChanges()) {
            UserMenu menu = doc.getDocument().toObject( UserMenu.class ).withId( doc.getDocument().getId() );

            Log.d( TAG, doc.getDocument().getId() + " => " + doc.getDocument() );

            finalId = doc.getDocument().getId();
            userMenu.add( menu );
            userMenuListAdapter.notifyDataSetChanged();
        }
    } );

//Method here to calculate the total cals value to show in header???
    calsList = new ArrayList<>();
    totalCalsData = calsList.size();
    totalCals = 0;


    Query calorieRef = umFirestore.collection( "AppUsers" )
            .document( getUserId )
            .collection( "UserMenu" ).whereEqualTo( "itemCals", true );

    calorieRef.limit( 15 ).addSnapshotListener( (QuerySnapshot documentSnapshots, FirebaseFirestoreException e) -> {

        if (e != null) {
            Log.d( TAG, "Error: " + e.getMessage() );
        }
        if (e == null) {
            Log.d( TAG, "Success: " + getUserId);
        }

        assert documentSnapshots != null;
        for (DocumentChange calDoc : Objects.requireNonNull( documentSnapshots ).getDocumentChanges()) {
            UserMenu mMenu = calDoc.getDocument().toObject( UserMenu.class ).withId( calDoc.getDocument().getId() );

            calsList.add( mMenu );

            for (int i = 0; i < calsList.size(); i++) {
                totalCals = totalCals + Integer.parseInt( String.valueOf( calsList.get( i ) ) );
            }
            totalCalsToPass = Integer.parseInt( String.valueOf( totalCals ) );

        }

    } );
}

这是适配器

import static com.melcolton.bite.UsersMenuActivity.finalId;

公共类UserMenuListAdapter扩展了RecyclerView.Adapter实现了View.OnClickListener {

private static final String TAG = "Adapter Log";
private View.OnClickListener myClickListener;
private FirebaseFirestore fbFirestore;
private FirebaseAuth fbAuth;

public String fbUserId;
public List<UserMenu> userMenu;
public Context context;

public UserMenuListAdapter(Context context, List<UserMenu> userMenu, View.OnClickListener myClickListener) {
    this.myClickListener = myClickListener;
    this.userMenu =  userMenu ;
    this.context = context;
}

@NonNull
@Override
public UserMenuListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    Context context = parent.getContext();
    View menuView = LayoutInflater.from( context ).inflate( R.layout.item_confirm_list_element, parent, false );
    return new ViewHolder( menuView, myClickListener );
}

@Override
public void onBindViewHolder(@NonNull UserMenuListAdapter.ViewHolder holder, int position) {

    fbAuth = FirebaseAuth.getInstance();
    fbFirestore = FirebaseFirestore.getInstance();
    fbUserId = fbAuth.getCurrentUser().getUid();

    if (holder instanceof ViewHolder) {

        ViewHolder viewHolder = holder;

        holder.userMenuName.setText( userMenu.get( position ).getItemName() );
        holder.userMenuDesc.setText( userMenu.get( position ).getItemDesc() );
        holder.userMenuCals.setText( userMenu.get( position ).getItemCals().toString() );
        holder.userMenuCost.setText( userMenu.get( position ).getItemCost().toString() );

        holder.deleteButton.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText( context, "Removed", Toast.LENGTH_SHORT ).show();


                fbFirestore.collection( "AppUsers" ).document(fbUserId).collection( "UserMenu" ).document(finalId)
                        .delete().addOnSuccessListener( new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                        userMenu.remove( position );
                        notifyItemRemoved( position );
                        notifyItemRangeChanged( position, userMenu.size() );
                        notifyDataSetChanged();
                        holder.menuView.setVisibility( View.GONE );

                    }
                } );

            }

        });
    }
}

@Override
public int getItemCount() {

    return userMenu.size();
}

public void onEvent (QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
    if (e !=null) {
        Log.w( TAG, "onEvent error: ",e );
        onError (e);
    }
}

private void onError(FirebaseFirestoreException e) {
    Log.w( TAG, "onEvent error: ",e );
}

@Override
public void onClick(View v) {

}

public class ViewHolder extends RecyclerView.ViewHolder {

    public CardView userMenuCardView;
    public TextView userMenuName;
    public TextView userMenuDesc;
    public TextView userMenuCals;
    public TextView userMenuCost;
    public Button deleteButton;
    View menuView;


    public ViewHolder(View itemView, View.OnClickListener myClickListener) {
        super( itemView );
        itemView.setOnClickListener( myClickListener );
        menuView = itemView;

        userMenuCardView = menuView.findViewById( R.id.user_menu_cardview );
        userMenuName = menuView.findViewById( R.id.txt_cart_item_name );
        userMenuDesc = menuView.findViewById( R.id.txt_cart_item_desc );
        userMenuCals = menuView.findViewById( R.id.txt_cart_item_cals );
        userMenuCost = menuView.findViewById( R.id.txt_cart_item_cost );
        deleteButton = menuView.findViewById( R.id.remove_button );
    }
}

}

最后是模型类

import com.google.firebase.firestore.IgnoreExtraProperties;

@IgnoreExtraProperties 公共类UserMenu扩展了UserId {

private String ItemName;
private String ItemDesc;
private Long ItemCals;
private Double ItemCost;
private String itemId;

public UserMenu() {

}

public UserMenu(String itemName, String itemDesc, Long itemCals, Double itemCost) {
    ItemName = itemName;
    ItemDesc = itemDesc;
    ItemCals = itemCals;
    ItemCost = itemCost;
}

public String getItemName() {
    return ItemName;
}

public void setItemName(String itemName) {
    ItemName = itemName;
}

public String getItemDesc() {
    return ItemDesc;
}

public void setItemDesc(String itemDesc) {
    ItemDesc = itemDesc;
}

public Long getItemCals() {
    return ItemCals;
}

public void setItemCals(Long itemCals) {
    ItemCals = itemCals;
}

public Double getItemCost() {
    return ItemCost;
}

public void setItemCost(Double itemCost) {
    ItemCost = itemCost;
}

}

1 个答案:

答案 0 :(得分:0)

要获取您正在谈论的总数,请使用以下代码:

userMenuRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            double total = 0;
            for (QueryDocumentSnapshot document : task.getResult()) {
                double itemCost = document.getDouble("itemCost");
                total = total + itemCost;
            }
            Log.d("TAG", String.valueOf(total));
        }
    }
});

输出将是文档中所有itemCost属性的总和。

另一种方法是随着时间的流逝保持总计,因为每个新价格都是已知的。然后,您可以在需要时在另一个文档中查询该运行总计。