在反序列化DataMap时磨损 - java.lang.IndexOutOfBoundsException

时间:2014-07-25 21:14:08

标签: android wear-os

转换包含long和Asset的DataMap时,我得到以下异常:

E/JavaBinder( 1634): *** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
E/JavaBinder( 1634): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
E/JavaBinder( 1634):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
E/JavaBinder( 1634):    at java.util.ArrayList.get(ArrayList.java:308)
E/JavaBinder( 1634):    at com.google.android.gms.internal.bm.a(Unknown Source)
E/JavaBinder( 1634):    at com.google.android.gms.internal.bm.a(Unknown Source)
E/JavaBinder( 1634):    at com.google.android.gms.wearable.DataMap.fromByteArray(Unknown Source)

代码:

@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    for (DataEvent dataEvent : dataEvents) {
        final DataItem dataItem = dataEvent.getDataItem();
        byte [] data = (dataItem.isDataValid() ? dataItem.getData() : new byte[]{});
        Log.d(TAG, "Received data updates on URI: " + dataItem.getUri() + " " + data.length + " bytes");
        if (!dataItem.isDataValid() || data.length == 0) {
            Log.w(TAG, " - got invalid data on: " + dataItem.getUri());
            continue;
        }
        final DataMap dataMap = DataMap.fromByteArray(data); // <-- exception :(

这是一个已知问题吗?如果我在同一个URI上获取数据项,它可以正常工作,因此数据肯定存在。

2 个答案:

答案 0 :(得分:1)

更改DataEvent - &gt; DataItem - &gt; DataMap来自:

final DataItem dataItem = dataEvent.getDataItem();
byte [] data = dataItem.getData();
final DataMap dataMap = DataMap.fromByteArray(data);  <-- throws exception

为:

final DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
final DataMap dataMap = DataMap.fromByteArray(data);  <-- works!

结束问题。

答案 1 :(得分:-1)

问题可能出在这行代码中,你没有给字节数组一个大小

byte [] data = (dataItem.isDataValid() ? dataItem.getData() : new byte[]{});

你可以尝试用

替换这一行吗?
byte [] data = (dataItem.isDataValid() ? dataItem.getData() : new byte[0]);