Firebase transaction returns ArrayList handling

允我心安 提交于 2021-01-29 12:25:01

问题


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:

current state

and expect the code will add second child "2":

expected result

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

error stacktrace

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!