Monday, 3 May 2021

Cannot get sum of values from firebase Realtime properly outside the recycler view

I am making an android app based on firebase Realtime. I am able to get sum of child nodes in my recycler view. But I also need the grand total of those SUM values outside the recycler view. The required Grand Total is available but is not exact (true). Furthermore the Grand Total is not correct until we scroll to the bottom. It also keeps changing when we scroll the recycler view up and down. This is the code of my activity:--


public class LookIncomeActivity<SharedPreference> extends AppCompatActivity {
    FirebaseDatabase myfire;
    DatabaseReference myRef;
    private FirebaseRecyclerOptions<category> options1;
    int earned = 0;
    int saved = 0;

    @Override
    public void onBackPressed() {
        Intent o;
        o = new Intent(LookIncomeActivity.this, MainActivity.class);
        startActivity(o);
        finish();
    }
    private String getUID() {
        FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
        if (mUser != null) {
            String strUID = mUser.getUid();
            if (!TextUtils.isEmpty(strUID)) {
                return strUID;
            }
        }

        return "";

    }
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_income);
        final TextView tvTopic = (TextView) findViewById(R.id.idTitle);
        final TextView tvEarned = (TextView) findViewById(R.id.idEarned);
        final TextView tvSpent = (TextView) findViewById(R.id.idSpent);
        final RecyclerView userlist = (RecyclerView) findViewById(R.id.idRecycle);
        Button btnCreate= (Button) findViewById(R.id.idCreate);
        Button btnDelete = (Button) findViewById(R.id.idDelete);
        myfire = FirebaseDatabase.getInstance();
        userlist.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        //------------------------------------------
        final String strUID = getUID();
        if (TextUtils.isEmpty(strUID)) {
            //handle case of null UID
        }
        //-------------------------------
        btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent o;
                o = new Intent(LookIncomeActivity.this, BudgetIncomeActivity.class);
                startActivity(o);
                finish();

            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



            }
        });



        //-------------------------------
        myRef = myfire.getReference().child("Data").child(strUID).child("Budget_Income");

//------------------------------------------
        Toast.makeText(LookIncomeActivity.this, "Please Wait a While !", Toast.LENGTH_LONG).show();

//-------------------------
        options1 = new FirebaseRecyclerOptions.Builder<category>()
                .setQuery(myRef, category.class)
                .build();

        final FirebaseRecyclerAdapter<category, holder1> adapter = new FirebaseRecyclerAdapter<category, holder1>(options1) {

            @SuppressLint("SetTextI18n")
            @Override
            protected void onBindViewHolder(final holder1 holder, final int i, @NotNull final category passage) {
                final String title = getRef(i).getKey();

                assert title != null;

                holder.btnAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent o;

                        o = new Intent(LookIncomeActivity.this, EntryIncomeActivity.class);
                        o.putExtra("Title", title);


                        startActivity(o);
                        finish();
                    }
                });

                myRef = myfire.getReference().child("Data").child(strUID).child("Budget_Income");
                myRef.child(title).addValueEventListener(new ValueEventListener() {

                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        int budget = 0;

                        if (dataSnapshot.getValue() == null) {
                            Toast.makeText(getApplicationContext(), "Data Not Available", Toast.LENGTH_LONG).show();
                        } else {


                            final String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
                            final String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
                            final String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
                            final String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();


                            category basic = new category(stData1, stData2, stData3, stData4);
                            holder.tvOne.setText("Title"+"("+stData1+")");
                            holder.tvTwo.setText("Budget"+"("+stData4+")");
                            int amount = 0;
                            amount = (Integer.parseInt(stData4));
                            budget = amount;

                            myRef = myfire.getReference().child("Data").child(strUID).child("Entry_Income").child(title);
                            final int finalBudget = budget;

                            myRef.addValueEventListener(new ValueEventListener() {

                                @Override
                                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                    int sum = 0;


                                    for (DataSnapshot data : dataSnapshot.getChildren()) {
                                        String value = data.child("stData4").getValue(String.class);
                                        assert value != null;
                                        int total = 0;
                                        total = (Integer.parseInt(value));
                                        sum = sum + total;
                                    }
                                    holder.tvThree.setText("Earned"+"("+String.valueOf(sum)+")");
                                    holder.tvFour.setText("Target"+"("+String.valueOf(finalBudget - sum)+")");
                                    earned = (earned + sum);
                                    saved=(saved-sum);
                                    tvTopic.setText("Total:"+ "["+String.valueOf(earned)+ "]");

                                }


                                @Override
                                public void onCancelled(@NonNull DatabaseError databaseError) {
                                    throw databaseError.toException(); // never ignore errors
                                }
                            });

                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        throw error.toException(); // never ignore errors
                    }

                });

            }

            @NonNull
            @Override
            public holder1 onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item1, parent, false);
                return new holder1(v);
            }

        };



      //===============================================================================================

        userlist.setAdapter(adapter);
        adapter.startListening();

    }

}

In short I want:- 1-Grand total outside the recycler view without scrolling to the bottom. 2-The grand total should not change on scrolling up and down.

Please correct me with an example.



from Cannot get sum of values from firebase Realtime properly outside the recycler view

No comments:

Post a Comment