问题
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:
and expect the code will add second child "2":
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) {
}
});
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?
回答1:
When you make this call:
String numQuestions = (String) mutableData.getValue();
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();
来源:https://stackoverflow.com/questions/65306100/firebase-transaction-returns-arraylist-handling