0

Is there any way to update this key in the Firebase? Seems like the value is updating but not the key itself.

Firebase Key Image

I've tried using hashmap with updateChildren and setValue as well, it is working but only the value of that key is Updating not the key itself like this: Key No Updating

This is the code of the update button in the dialog class:

        user = FirebaseAuth.getInstance().getCurrentUser();
        userId = user.getUid();
        reference = FirebaseDatabase.getInstance().getReference("Users").child(userId).child("Courses").child(addClassinput.getText().toString());
classBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
reference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if(!addClassinput.getText().toString().isEmpty()){
            Map<String, Object> map = new HashMap<>();
            map.put("getClassName", addClassinput.getText().toString());


            FirebaseDatabase.getInstance().getReference("Users") .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                    .child("Courses").child(getClass).updateChildren(map)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void unused) {
                            Toast.makeText(getContext(), "Updated Successfully", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(getContext(), "Error Updating!", Toast.LENGTH_SHORT).show();
                        }
                    });

        }
        else{
            Toast.makeText(getContext(), "Invalid Input!", Toast.LENGTH_SHORT).show();
        }
    }

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

    }
});
   }
 });

P.S This thing surely helps: How to copy a record from a location to another in Firebase realtime database?

Here is my update of the code and it is working fine:

 user = FirebaseAuth.getInstance().getCurrentUser();
        userId = user.getUid();
        reference = FirebaseDatabase.getInstance().getReference("Users").child(userId).child("Courses").child(getClass);

        classBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ref2 = FirebaseDatabase.getInstance().getReference("Users").child(userId).child("Courses").child(addClassinput.getText().toString());
                moveRecord(reference, ref2);
                FirebaseDatabase.getInstance().getReference("Users").child(userId).child("Courses").child(getClass).removeValue();

                reference.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        String key = snapshot.getKey();
                        if(!addClassinput.getText().toString().isEmpty()){
                            Map<String, Object> map = new HashMap<>();
                            map.put("getClassName", addClassinput.getText().toString());


                            FirebaseDatabase.getInstance().getReference("Users") .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                    .child("Courses").child(addClassinput.getText().toString()).updateChildren(map)
                                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void unused) {
                                            Toast.makeText(getContext(), "Updated Successfully!", Toast.LENGTH_SHORT).show();
                                        }
                                    })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Toast.makeText(getContext(), "Error Updating!", Toast.LENGTH_SHORT).show();
                                        }
                                    });

                        }
                        else{
                            Toast.makeText(getContext(), "Invalid Input!", Toast.LENGTH_SHORT).show();
                        }
                    }

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

                    }
                });

            }
        });
private void moveRecord(DatabaseReference fromPath, final DatabaseReference toPath) {
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                toPath.setValue(dataSnapshot.getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isComplete()) {
                            Log.d(TAG, "Success!");
                        } else {
                            Log.d(TAG, "Copy failed!");
                        }
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage()); //Don't ignore potential errors!
            }
        };
        fromPath.addListenerForSingleValueEvent(valueEventListener);
    }
compsci
  • 15
  • 4

1 Answers1

0

You cannot update the name of a key once it was set. If you need to change the key, then you need to copy that particular node to another location, provide the new name, and then delete the old record. There is no other solution for that. To copy a node from one location to another, please see my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Dang thanks! Actually, I've seen that solution but disregarded since it was on 2018 hoping by now that there would be a way rather than copying – compsci Dec 19 '22 at 12:43
  • Did my answer help? Can I help you with other information? – Alex Mamo Dec 19 '22 at 14:50
  • Oh surely it helps, In the DatabaseReference fromPath i just pass there the old class and and in "toPath" I passed the new class from the string input from the user. Then, called the method in the buttononlick event, after that I removed the value of the old class and changed the value of the new class so the new class will be synced will the recylerview. I've wrtitten an update to the question for reference. – compsci Dec 20 '22 at 01:00
  • So did my answer help you solve the problem? – Alex Mamo Dec 20 '22 at 07:48
  • Yeah it answers, but in my case I just added some code for it to change the the value of the key, cause if I use the code alone, the key changes but not the value of the key which is vital in my case cause the value is needed in the recyler view – compsci Dec 21 '22 at 01:35