0

我正在使用基于教程的 KSOAP2 库获取复杂对象的 ArrayList:

而且我能够接收对象的arrayList。问题是当信封只有一个对象时......当我这样做时:

//...Call webservice
Vector<SoapObject> vectorOfSoapObject = (Vector<SoapObject>)envelope.getResponse();
//pass Vector to ArrayList

ClassCastException当我在信封上只有一个对象时,它会在这条线上返回给我一个。当我有更多时,它工作正常(我进行了调试以看到这种情况发生)......

可能是什么问题呢?

4

2 回答 2

1

可能是当有多个记录时,服务返回Vector<SoapObject>,当只有记录时,它只返回SoapObject
您正在尝试转换SoapObjectVector<SoapObject>,所以ClassCastException.
这是服务实施的问题。但是,要在最后解决此问题,您应该首先获取envelope.getResponse()as Object,并在强制转换之前检查是否Object为实例Vector<SoapObject>SoapObject

Vector<SoapObject> vectorOfSoapObject = null;
Object response = envelope.getResponse();

if( response instanceof Vector){
   Vector<SoapObject> vectorOfSoapObject = (Vector<SoapObject>) response;       
}else if(response instanceof  SoapObject){
    //cast single object
   SoapObject soapObject = (SoapObject) response;
   //initialize vector
   vectorOfSoapObject = new Vector<SoapObject>();
   //add single object to vector. 
   vectorOfSoapObject.add(soapObject);
}

这样你就不必更改你可能已经编写的其他代码,假设你总是会得到列表

于 2012-06-01T18:16:05.960 回答
1

我能够解决这个问题。使用@Pranalee 的建议,我做了这个:

//call webservice
Object o1 = envelope.getResponse();
if(o1 == null){//no devices updated
    Log.d("GetUpdatesThread","o1==null");
} else if(o1.getClass().toString().equals(new SoapObject("", "").getClass().toString())){//one device updated
    Log.d("GetUpdatesThread","class -- soapObject");
    SoapObject result = (SoapObject) envelope.getResponse();
    Device d = convertToDevice(result);
    devicesUpdated.add(d);
} else if (o1.getClass().toString().equals(new Vector().getClass().toString())){//more than one device updated
    Log.d("GetUpdatesThread","class -- vector");
    Vector<SoapObject> vectorOfSoapObject2 = (Vector<SoapObject>)envelope.getResponse();
    for (SoapObject soapObject : vectorOfSoapObject2) {
         Device d = convertToDevice(soapObject);
         devicesUpdated.add(d);
    }  
}
于 2012-06-04T11:38:33.467 回答