k_dev
k_dev

Reputation: 97

Firebase Database update data deletes old children

I want to add nested children in my firebase database. The structure of my json is

{
    "Users": {

    "user1": {
        "courses": {
            "science": {
                "maxMarks": 100,
                "teacher": "Andrew",
                "title": "Amazing Science",
                "status": "cleared"

            },
            "maths": {
                "maxMarks": 100,
                "teacher": "Simon",
                "title": "Elementary Mathematics",
                "status": "cleared"
            },
            "history": {
                "maxMarks": 80,
                "teacher": "Sarah",
                "title": "History",
                "status": "cleared"
            }
        }

    }
}

}

As soon as I add a new course, it is overwriting my whole course child instead of adding a new child inside.

I have also tried updateChildren but no success.. Please help.

FirebaseDatabase mDatabase = FirebaseDatabase.getInstance().getReference("Users");


DatabaseReference newPostRef = mDatabase.child("user1").child("courses").child("Calculus").push();

                            Map<String, Object> newPost = new HashMap<String, Object>();
                            newPost.put("title", "Calculus");
                            newPost.put("teacher", "Mishal");
newPost.put("maxMarks", 100);
newPost.put("status", "cleared");
                            newPostRef.setValue(newPost);

Upvotes: 2

Views: 1407

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

I recommend you using instead of the names of the courses, the unique ids that are generated by the push() method. This means that the your database structure might look like this:

"user1": {
    "courses": {
        "-Kdfqjidfiqifnqifn": {
            "courseName": "science",
            "maxMarks": 100,
            "teacher": "Andrew",
            "title": "Amazing Science",
            "status": "cleared"

        },
        "-Kdfqjidfwefwty34d": {
            "courseName": "maths",
            "maxMarks": 100,
            "teacher": "Simon",
            "title": "Elementary Mathematics",
            "status": "cleared"
        },
        "-Kdfqjidfwer3t4yhdg": {
            "courseName": "history",
            "maxMarks": 80,
            "teacher": "Sarah",
            "title": "History",
            "status": "cleared"
        }
    }

}

You'll need to use this method directly on your reference like this:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("User").child(userId).child("courses");
DatabaseReference keyReference = databaseReference.push();
keyReference.setValue(yourMap)

In which userId is the id of the user.

In this way, you won't update the existing data, you'll add new one.

Hope it helps.

Upvotes: 3

Related Questions