I have an array containing serializable objects and am trying to use Intent's putExtra() and Bundle's getSerializable(). However, I am getting a class cast exception and don't understand why.
Below is the code. UserInfo is my own class which implements Serializable, and I have been able to pass individual UserInfo objects between activities. I've only ran into this problem when attempting to use an array.
Code sending the serializable:
Intent intent = new Intent( JOIN_GROUP ); //JOIN_GROUP is a constant string
String user_ids[] = packet.userIDs();
int length = user_ids.length;
UserInfo users[] = new UserInfo[length];
for ( int i = 0; i < length; ++i )
users[i] = getUserByID( user_ids[i] );
intent.putExtra( USERS_IN_GROUP, users );
Code retrieving the serializable:
Bundle extra = intent.getExtras();
String action = intent.getAction();
if ( action.equals(IMService.JOIN_GROUP) )
{
//CLASS CAST EXCEPTION
UserInfo users[] = (UserInfo[]) extra.getSerializable( IMService.USERS_IN_GROUP );
}
Here is the error:
Question
I'm aware I could probably just use a different data structure, but I would like to understand why the array does not work since arrays are serializable?
EDIT: SnyersK was able to get a simpler but similar scenario to work.
So I tried the same thing, and I still get the same exception. It turned my array of Tests into an Object when retrieving the array, which results in the casting exception.
My Test object:
package types;
import java.io.Serializable;
public class Test implements Serializable {
private static final long serialVersionUID = 1L;
private String hello = "hello";
}
Code to pass the array of Test objects:
Test myArray[] = new Test[] { new Test(), new Test() };
Intent i = new Intent( this, Login.class );
i.putExtra( "key", myArray );
Code to retrieve the array of Test objects:
Bundle extras = getIntent().getExtras();
Test array[] = (Test[]) extras.getSerializable( "key" ); //Class Cast Exception
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…