Skip to content

Commit 0e04c76

Browse files
committed
Fixed a bug and added another test that verifies it.
1 parent 08ee0bc commit 0e04c76

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayTest.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ public Boolean call() throws Exception {
112112
}
113113

114114
@Test
115-
public void testChangePriorities() throws Exception {
115+
public void testChangePriorityBackToFront() throws Exception {
116116
runAndWaitUntil(mArray, new Runnable() {
117117
public void run() {
118118
mArray.getItem(2).getRef().setPriority(0.5);
@@ -123,4 +123,17 @@ public Boolean call() throws Exception {
123123
}
124124
});
125125
}
126+
127+
@Test
128+
public void testChangePriorityFrontToBack() throws Exception {
129+
runAndWaitUntil(mArray, new Runnable() {
130+
public void run() {
131+
mArray.getItem(0).getRef().setPriority(4);
132+
}
133+
}, new Callable<Boolean>() {
134+
public Boolean call() throws Exception {
135+
return isValuesEqual(mArray, new int[]{2, 3, 1});
136+
}
137+
});
138+
}
126139
}

database/src/main/java/com/firebase/ui/database/FirebaseArray.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import java.util.ArrayList;
2323
import java.util.HashMap;
24+
import java.util.ListIterator;
2425

2526
/**
2627
* This class implements an array-like collection on top of a Firebase location.
@@ -65,6 +66,16 @@ public int getIndexForKey(String key) {
6566
}
6667
}
6768

69+
private int scanArrayForKey(String key) {
70+
final ListIterator<DataSnapshot> it = mSnapshots.listIterator();
71+
while (it.hasNext()) {
72+
if (it.next().getKey().equals(key)) {
73+
return it.previousIndex();
74+
}
75+
}
76+
throw new IllegalArgumentException("Key not found");
77+
}
78+
6879
@Override
6980
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
7081
int index = 0;
@@ -95,9 +106,15 @@ public void onChildRemoved(DataSnapshot snapshot) {
95106
public void onChildMoved(DataSnapshot snapshot, String previousChildKey) {
96107
int oldIndex = getIndexForKey(snapshot.getKey());
97108
mSnapshots.remove(oldIndex);
98-
int newIndex = previousChildKey == null ? 0 : (getIndexForKey(previousChildKey) + 1);
109+
int newIndex = previousChildKey == null ? 0 : (scanArrayForKey(previousChildKey) + 1);
99110
mSnapshots.add(newIndex, snapshot);
100-
mSnapshotMap.put(snapshot.getKey(), newIndex);
111+
112+
// Rebuild the map of indices
113+
mSnapshotMap.clear();
114+
for (int i = 0; i < mSnapshots.size(); i++) {
115+
mSnapshotMap.put(mSnapshots.get(i).getKey(), i);
116+
}
117+
101118
notifyChangedListeners(OnChangedListener.EventType.MOVED, newIndex, oldIndex);
102119
}
103120

0 commit comments

Comments
 (0)