skip to Main Content

I want to push my data (in key:value pair) into my Realtime Database. This is my code:

DatabaseReference pay_details = database.getReference("pay/0/0/");

pay_details.push(
    {
          "Actual amount":arr.get(i).get(9),
          "Current reading":arr.get(i).get(5),
          "Employee":arr.get(i).get(1),
          "Expected amount":arr.get(i).get(9),
          "Installment":arr.get(i).get(10),
          "Meter current date":arr.get(i).get(3),
          "Meter previous date":arr.get(i).get(2),
          "Previous reading":arr.get(i).get(4),
          "Start from":arr.get(i).get(8),
          "Total charge":arr.get(i).get(7),
          "Type":arr.get(i).get(0),
          "Unit consumed":arr.get(i).get(6)
    }
);

This is my table structure:

Click here to view

I keep getting multiple syntax errors in the push section. Where am I going wrong?

2

Answers


  1. The best way to send/store data in real-time database is to create an object of
    Hashmap. Below is the code to achieve this objective

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
     HashMap<String, Object> data = new HashMap<>();
     data.put("Actual amount", Your actual amount);
    data.put("Current reading", Your current reading);
    data.put("Employee", Employee name);
    
    databaseReference.child("The child name")
      .updateChildren(data)
      .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void unused) {
            Log.d("TAG", "Data added successfully");
    
        }
      }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d("TAG", "Failed " + e.getMessage());
        }
      });
    
    Login or Signup to reply.
  2. The add data to the Realtime Database you need to use setValue() method. In code

    DatabaseReference pay_details = database.getReference("pay/0/0/");
    HashMap<String, Object> map = new HashMap<>();
    map.put("fieldName", "fieldValue");
    pay_details.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "Data added successfully.");
            } else {
                Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
            }
        }
    });
    

    If you want to add multiple children, then you can also use push().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search