Firebase事务返回ArrayList处理 [英] Firebase transaction returns ArrayList handling
问题描述
我正在尝试检查子项是否已经具有值,如果没有,则增加子项值并在子项内部添加数据数组.例如:
I'm trying to check if a child already has a value or not, if not then increment a child value and add an array of data inside the child. ex:
,并期望代码将添加第二个子代"2":
and expect the code will add second child "2":
为此,我使用doTransaction检查历史记录/用户ID值中是否有任何值,
to do this I use doTransaction to check if there are any values within history/userId value,
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);
PlanHistory planHistory = new PlanHistory(formattedDate, plan.getPlan_key(), plan.getPlan_name(), plan.getLevel_name(), plan.getType_name(), plan.getPersonal_trainer_id(), plan.getUri());
mDatabase.child("history").child(user.getUid()).runTransaction(new Transaction.Handler() {
@NonNull
@Override
public Transaction.Result doTransaction(@NonNull MutableData mutableData) {
long value = 0;
if(mutableData.getValue() != null) {
String numQuestions = (String) mutableData.getValue();
value = Long.parseLong(numQuestions, 16);
}
value++;
String incHex = Long.toHexString(value);
mutableData.setValue(incHex);
mutableData.child(incHex).setValue(planHistory);
return Transaction.success(mutableData);
}
@Override
public void onComplete(@Nullable DatabaseError error, boolean committed, @Nullable DataSnapshot currentData) {
}
});
问题出在子节点中已经有一个值时,它返回ArrayList并且不能转换为String
the problem lies when there's already a value inside the child node, it returns ArrayList and cannot be cast to String
我该如何修复代码,以便它可以像预期的结果一样添加前一个子名称增加后的下一个节点?
How can I fix the code so it can add the next node with incremented child name from previous one just like the expected result?
推荐答案
拨打电话时
String numQuestions = (String) mutableData.getValue();
您获得 MutableData
对象的值,该对象包含 mDatabase.child("history").child(user.getUid())
下的所有数据您的数据库.因此,与单个字符串相比,这是更多数据的方式.我的猜测是您正在寻找:
You get the value of the MutableData
object, which contains all data under mDatabase.child("history").child(user.getUid())
from your database. So that is way more data than a single string. My guess is that you're looking for:
String numQuestions = (String) mutableData.getKey();
这篇关于Firebase事务返回ArrayList处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!