How to Move Firebase Child from One Node to Another in Android

How to move Firebase child from one node to another in Android?

I recommend using this :

public void moveFirebaseRecord(Firebase fromPath, final Firebase toPath)
{
fromPath.addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
toPath.setValue(dataSnapshot.getValue(), new Firebase.CompletionListener()
{
@Override
public void onComplete(FirebaseError firebaseError, Firebase firebase)
{
if (firebaseError != null)
{
System.out.println("Copy failed");
}
else
{
System.out.println("Success");
}
}
});
}

@Override
public void onCancelled(FirebaseError firebaseError)
{
System.out.println("Copy failed");
}
});
}

This come from this source : https://gist.github.com/katowulf/6099042 . I used it several times in my JavaEE code and also in my android app.

You pass your fromPath and toPath. This is a copy tought and not a move, so the original will remain at his original place too. If you would like to delete, you can do a set value on the fromPath just after the System.out.println("Success"); .

How to move Firebase realtime database child value into another child value in an android studio?

As I said in comment, something like this.

FirebaseDatabase.getInstance().getReference().child("Users").child(userUid).child("points").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
long points = dataSnapshot.getValue(Long.class);
//transfer the value
FirebaseDatabase.getInstance().getReference().child("wFinal").child(userUid).child("totalpoints").setValue(points);
//set the value at Users to 0
FirebaseDatabase.getInstance().getReference().child("Users").child(userUid).child("points").setValue(0);
}
}

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

}
});

Copying Firebase node with multiple children to another node

Though not a very good approach but this approach get the work done.

public void copyFirebaseData() {
DatabaseReference questionNodes = FirebaseDatabase.getInstance().getReference().child("questions");
final DatabaseReference toUsersQuestions = FirebaseDatabase.getInstance().getReference().child("users").child(uid).child("questions");

questionNodes.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
String correctAnswerString = questionCode.child("correctAnswer").getValue(String.class);
String imageUrlString = questionCode.child("imageUrl").getValue(String.class);
toUsersQuestions.child(questionCodeKey).child("imageUrl").setValue(imageUrlString);
toUsersQuestions.child(questionCodeKey).child("correctAnswer").setValue(correctAnswerString);

}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}

How to copy a child of a node to another node Firebase & Android

A better approach

I chose to use Cloud Function and it works great!

Thank's guys for the support.

const functions = require('firebase-functions');

const admin = require('firebase-admin'); //Importar o Admin SDK para escrever dados na database
admin.initializeApp(functions.config().firebase);

exports.copiarEmpresas = functions.database.ref('/Categorias/{categoria}/{empresa}')
.onWrite((change, context) => {
var snapshot = change.after;
return admin.database().ref('AllEmpresas').child(snapshot.key).set(snapshot.val());
});

How to move a child in firebase with flutter?

There is no API to move or rename a node. You will have to

  1. Read the node from its old location,
  2. Write it to the new location,
  3. Delete it from the old location.

If atomicity is important, you can combine #2 and #3 in a single multi-path write operation by setting the old location to null (which is an alternative way to delete a node).

Also see:

  • Change keys in Firebase Realtime Database
  • How to move a child node under another child?
  • Move data in Firebase Realtime Database on Android (copy and then delete)

Moving or copying data from one node to another in firebase database

To solve this, I recommend you use the following lines of code:

public void copyRecord(Firebase fromPath, final Firebase toPath) {
fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
toPath.setValue(dataSnapshot.getValue(), new Firebase.CompletionListener() {
@Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
if (firebaseError != null) {
Log.d(TAG, "Copy failed!");
} else {
Log.d(TAG, "Success!");
}
}
});
}

@Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("TAG", firebaseError.getMessage()); //Never ignore potential errors!
}
});
}

This is a copy and not a move operation as you probably see, so the original record will remain at its original place. If you would like to delete, you can use the removeValue() method on the from path just after the System.out.println("Success");.

Edit: (03 May 2018).

Here is the code for using the new API.

private void copyRecord(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()); //Never ignore potential errors!
}
};
fromPath.addListenerForSingleValueEvent(valueEventListener);
}

Firebase Moving one item to another node

Ok i've checked your code and changed it, just edit my default strings and it should work Hope it helps...

The errors were:
1) The path was adding an extra key date
2) In the toMap() we were adding an extra key

ok Here is the main Activity

    public class MainActivity extends AppCompatActivity {
    private DatabaseReference waypointRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String mTravelType = "Private";
        final String year = "2016";
        final String month = "06";
        final String dateKey = "2016-06-01 23:40:08";
        String mUserId = user.getUid();

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("users");

        waypointRef = myRef.child(mUserId).child("waypoints");
        Log.e("ref",waypointRef.toString());

        waypointRef.child(mTravelType).child(year).child(month).child(dateKey).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.e("data",dataSnapshot.toString());

                MyClass node = dataSnapshot.getValue(MyClass.class);
                node.setKey(dataSnapshot.getKey());

                Map<String, Object> nodeValues = node.toMap();

                Map<String, Object> childUpdates = new HashMap<>();

                String work_path = "/Work/" + year + "/" + month + "/" + "/" + dateKey + "/";
                String private_path = "/Private/" + year + "/" + month + "/" + dateKey + "/";

                childUpdates.put(work_path, nodeValues);
                childUpdates.put(private_path, null);

                waypointRef.updateChildren(childUpdates);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }
}

And here is the Class

@IgnoreExtraProperties
public class MyClass {
    private String key;
    private String destination, distance;

    public MyClass() {
    }

    @Exclude
    public String getKey() {
        return key;
    }

    @Exclude
    public void setKey(String key) {
        this.key = key;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public String getDistance() {
        return distance;
    }

    public void setDistance(String distance) {
        this.distance = distance;
    }

    @Exclude
    public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("destination", destination);
        result.put("distance", distance);

        return result;
    }

}


Related Topics



Leave a reply



Submit