Skip to content

Commit 69dc670

Browse files
committed
Fixed a bug and added another test that verifies it.
1 parent c2a62e2 commit 69dc670

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
@@ -22,6 +22,7 @@
2222

2323
import java.util.ArrayList;
2424
import java.util.HashMap;
25+
import java.util.ListIterator;
2526

2627
/**
2728
* This class implements an array-like collection on top of a Firebase location.
@@ -71,6 +72,16 @@ public int getIndexForKey(String key) {
7172
}
7273
}
7374

75+
private int scanArrayForKey(String key) {
76+
final ListIterator<DataSnapshot> it = mSnapshots.listIterator();
77+
while (it.hasNext()) {
78+
if (it.next().getKey().equals(key)) {
79+
return it.previousIndex();
80+
}
81+
}
82+
throw new IllegalArgumentException("Key not found");
83+
}
84+
7485
@Override
7586
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
7687
int index = 0;
@@ -101,9 +112,15 @@ public void onChildRemoved(DataSnapshot snapshot) {
101112
public void onChildMoved(DataSnapshot snapshot, String previousChildKey) {
102113
int oldIndex = getIndexForKey(snapshot.getKey());
103114
mSnapshots.remove(oldIndex);
104-
int newIndex = previousChildKey == null ? 0 : (getIndexForKey(previousChildKey) + 1);
115+
int newIndex = previousChildKey == null ? 0 : (scanArrayForKey(previousChildKey) + 1);
105116
mSnapshots.add(newIndex, snapshot);
106-
mSnapshotMap.put(snapshot.getKey(), newIndex);
117+
118+
// Rebuild the map of indices
119+
mSnapshotMap.clear();
120+
for (int i = 0; i < mSnapshots.size(); i++) {
121+
mSnapshotMap.put(mSnapshots.get(i).getKey(), i);
122+
}
123+
107124
notifyChangedListeners(OnChangedListener.EventType.MOVED, newIndex, oldIndex);
108125
}
109126

0 commit comments

Comments
 (0)