无法获取节点的值

时间:2018-08-23 00:59:18

标签: android firebase firebase-realtime-database

我有以下数据库节点:

  "ButtonState" : {
    "payEnabled" : 0,
    "requestEnabled" : 1
  },

当驾驶员接受来自驾驶员的乘车请求时,“ payEnabled = 1”的值。在驱动程序接受请求后,我试图获取payEnabled的值,但是它出错了,我得到了:

 java.lang.NumberFormatException: For input string: "{payEnabled=0, requestEnabled=1}"

我用来获取数据的代码是:

 rootRef = rootRef.child("ButtonState");

    rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                int payEnabled = Integer.valueOf(dataSnapshot.getValue().toString());
                Log.e(TAG, "payEnabled = " + payEnabled);
                if (payEnabled == 1) {
                    pulseAnimation();
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

我在做错什么,如何才能获得“ payEnabled”的值?

1 个答案:

答案 0 :(得分:2)

您正在听ButtonState,并将其解释为数字。但是ButtonState是JSON对象,而payEnabledButtonState内部的属性。鉴于您只对payEnabled感兴趣,我将侦听器仅附加到该属性:

rootRef.child("payEnabled").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            int payEnabled = dataSnapshot.getValue(Integer.class);
            Log.e(TAG, "payEnabled = " + payEnabled);
            if (payEnabled == 1) {
                pulseAnimation();
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
});