我使用Firebase创建了一个应用程序。有一个我无法解决的问题,并没有在这里讨论。Android - onDataChange()奇怪的行为
在这种方法中,我想检查一些数据是否已经在服务器中。如果没有 - 我想添加它(添加代码的效果很好,Firebase数据库正在根据需要进行更改)。所以我使用onDataChange方法如下:
public boolean insertNewList(String title)
{
System.out.println("start: ");
final boolean[] result = new boolean[1];
result[0]=false;
final String group = title;
mRootRef = some reference...
mRootRef.addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
System.out.println(0);
if (dataSnapshot.child(group).getValue() != null)
{
System.out.println(group + " is already exist");
System.out.println(1);
}
//write the data.
else
{
mRootRef=mRootRef.child(group);
mRootRef.push().setValue("some data");
System.out.println(2);
result[0]=true;
}
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
});
System.out.println(3);
return result[0];
}
但是真的发生是这样的输出:
begin:
3 (just skip on onDataChange method and return false).
some print after calling the function
0 (goes back to function and enter to onDataChange method)
2 (finally goes where I want it to go)
0 (for some reason enters twice :( )
1
正因为如此我接受这个功能错误的结果。 你能帮忙吗?
对不起,我用“开始”取代了“开始”,但没关系。 – ayelet