我有这样的JSON数据(仅显示2个节点,但实际上有很多)
{
"Node1" : {
"-Kr20AYmoO5L2lbpMbka" : {
"cityName" : "New York",
"date" : "09-Aug-17"
},
"-Kr20_FZM_FBR7Ua2VoN" : {
"cityName" : "Moscow",
"date" : "09-Aug-17"
},
"-Kr22-yGRjXpW2aFq-u9" : {
"cityName" : "Astana",
"date" : "09-Aug-17"
}
},
"Node2" : {
"-Kr0GH7Wr-fN2ndCZgpS" : {
"cityName" : "Washington",
"date" : "08-Aug-17",
"typeOfIcon" : 1
},
"-Kr0UxxpvxgXxu2wCqyL" : {
"cityName" : "Chicago",
"date" : "08-Aug-17",
"typeOfIcon" : 1
}
}
}
我想做什么?从节点获取数据并在RecyclerView
上显示。如果发生了某些事情,我必须显示下一个节点的数据(在这种情况下它是Node2
)并将一些数据推送到上一个节点(在这种情况下它是Node1
)。
有什么问题?我可以轻松地显示每个节点的数据。但问题是,当我从某个节点获取数据并将数据推送到previous
节点时,我的RecyclerView
使用来自also
节点的数据更新自身previous
(但最后没有推送数据) )。为什么会这样?以下是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_just);
//all initializations are above
loadDataFromFirebase();
}
private void loadDataFromFirebase() {
//below is array used to fill recyclerView
cities = new ArrayList<>();
final Firebase firebase = new
Firebase(FirebaseConfig.URL);
//words array is {"Node1","Node2",.......};
firebase.child(words.get(index))//index = 0 for the first time
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
City city = d.getValue(City.class);
cities.add(city);
}
citiesRecyclerView.setAdapter(new CityAdapter(MainActivity.this,cities));//show recyclerView
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
public void ifSomethingHappened()
{
/*
I call this method when it is needed
*/
index++; //incerement index in order to go to next node
loadDataFromFirebase(); //load data again from another node
pushCity();
}
private void pushCity() {
int prevChildNodeIndex = index - 1 ; // get index of previous child(in this case it is Node1)
String prevChildNode = words.get(prevChildNodeIndex); // Node1
Firebase firebase = new Firebase(FirebaseConfig.URL);
City city = getUsersCity(); // it is method that returns city,it is ok
firebase.child(prevChildNode).push().setValue(city); //push to previous node
}
正如我之前所说,我可以成功地显示来自任何节点的数据。但是,当我转到下一个节点并显示来自此节点的数据时,会显示但是包含来自前一节点的所有数据,因为此后调用了push()
。我该如何解决这个问题?我不想显示前一节点的数据,我只想显示当前节点的数据,只推送到上一个节点。但是我已经了解push()
自动更新recyclerView
的数据用于推送数据。希望您了解我的问题。那怎么解决?