I'm having some trouble with sending an Object from my Android app to my Java application. I have a serializable class that's exactly the same.
It works perfectly when I send the object from one java appliction to another one using this code on the receiver side:
@Override
public void run() {
super.run();
while(true){
try{
if(datagramSocket!=null)datagramSocket.close();
datagramSocket = new DatagramSocket(PORT);
buffer = new byte[4096];
inPacket = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(inPacket);
InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bais));
Song song = (Song) ois.readObject();
song.setClientIP(inPacket.getAddress());
dc.addSong(song);
datagramSocket.close();
}catch (IOException e) {
System.out.println("IOException on receiving song: " + e);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
but when I try to do the same in android (so sending the Song-object from android to java) I'm getting a ClassCastException:
[Lcom.audiobuddy.serializables.Song; cannot be cast to com.audiobuddy.serializables.Song
First I thought it was because the package name was different, so I changed it on both sides to "com.audiobuddy.serializables". But I look at my error, the Android app, changes the package adding "[L" in front and ";" in the back...
On both sides the Song-classes have the same serialVersionUID
The error message says that you try to cast Song[] ([L(...)Song
means an array of Song) to a Song.
You should probably change your ois.readObject();
-line with something like this:
Song[] songs = (Song[]) ois.readObject();
Song song = songs[0];