Gokul
Gokul

Reputation: 53

How to add multiple set of value in a same node for same User?

I am using realtime database. In that multiple users will give same set of data like shown in Snapshot1. Whenever the same user submitting other set of data, it is updating the old record but I want to add as a new record like a single user can save multiple set of data like in Snapshot2.

My Code is:

   Contribution cont = new Contribution(money, month, payment, date, tref, rem);
        FirebaseDatabase.getInstance().getReference("Contribution")
                .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                .setValue(cont).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Toast.makeText(ContributionDeclarationForm.this, "Successfully Submitted", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(ContributionDeclarationForm.this, DashboardActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(ContributionDeclarationForm.this, "Not Submitted", Toast.LENGTH_LONG).show();
            }
        });

Thanks in advance.

Snapshot1:

Snapshot1

Snapshot2:

Snapshot2

Upvotes: 2

Views: 428

Answers (2)

Gokul
Gokul

Reputation: 53

Final Output

For this i got a solution and my solution is:

// Declared in globally
DatabaseReference ref;
Contribution cont;
//declared inside a method
cont = new Contribution();
        ref = FirebaseDatabase.getInstance().getReference("Contribution")
                .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()){
                    snapshot.getChildrenCount();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        cont.setAmount(money);
        cont.setContribution_Month(month);
        cont.setMode_Of_Payment(payment);
        cont.setTransaction_Date(date);
        cont.setTransaction_RefNo(tref);
        cont.setRemarks(rem);

        ref.child(month).push().setValue(cont);
        Toast.makeText(ContributionDeclarationFormActivity.this, "Successfully Submitted", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(ContributionDeclarationFormActivity.this, DashboardActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138824

To achieve that, you can simply use DatabaseReference's push() method, which:

Creates a reference to an auto-generated child location.

So something like:

FirebaseDatabase.getInstance().getReference("Contribution")
        .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
        .push().setValue(cont).addOnCompleteListener(new OnCompleteListener<Void>() {
    ...

This means that you'll get a unique key for each child under (Contribution/$uid). So your new schema will look like this:

Firebase-root
  |
  --- Contribution
        |
        --- $uid
             |
             --- $pushedId
                    |
                    --- Amount: "369"
                    |
                    --- Contribution_Month: "5-2025"
                    |
                    --- //Other properties

If you want to get all children of a single user, you need to use a reference that points to the UID and loop through the results like in the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Contribution").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                String amount = task.getResult().child("Amount").getValue(String.class);
                Log.d("TAG", amount);
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

The result in the logcat will be the "amount" of each child that exists under the above reference.

If you need numbers, it's best to store them in the database as numbers and not as String values.

Upvotes: 2

Related Questions