Moving or Copying Data from One Node to Another in Firebase Database

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);
}

How to copy a record from a location to another in Firebase realtime database?

Actually, I answered that question, but at that time, I used a version of Firebase Android SDK that is now considered to be old. So for that, I recommend you to use the following method:

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);
}

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"); .

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) {

}
});
}

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