I've started to write a small app for android. It looks very nice, but there is one thing I don't understand.
I've created a new intent in the activity A and I've added a serialized vector intent.putExtra("key", vector)
. On the called activity B I'm doing this: Vector<ItemModel> items = (Vector<ItemModel>) getIntent().getExtras().getSerializable("key")
. This line causes a ClassCastException
. Does anyone know why? Please help me :-)
Here is the source of the two activities and of the ItemModel
:
ItemModel:
public class ItemModel implements java.io.Serializable {
private static final long serialVersionUID = -1772392719565658730L;
public int id;
public String name;
public String quantity;
public int status;
}
ShoppingListActivity (A):
public void onClickItems(final View v){
final Intent intent = new Intent(this,ItemListActivity.class);
Vector<ItemModel> v1 = new Vector<ItemModel>();
ItemModel item = new ItemModel();
item.name = "Tomaten";
item.quantity = "400g";
item.id = 12;
item.status = 0;
v1.add(item);
item = new ItemModel();
item.name = "Bohnen";
item.quantity = "150g";
item.id = 13;
item.status = 0;
v1.add(item);
item = new ItemModel();
item.name = "Schokolade";
item.quantity = "5 Tafeln";
item.id = 17;
item.status = 0;
v1.add(item);
intent.putExtra("ShoppingList", v1);
startActivity(intent);
ItemListActivity (B):
public class ItemListActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
ListView list = (ListView) findViewById(R.id.ITEMSLIST);
final Bundle extras = getIntent().getExtras();
Vector<ItemModel> items = (Vector<ItemModel>) extras.getSerializable("ShoppingList");
ArrayList<HashMap<String, Object>> itemsList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> itemMap = new HashMap<String, Object>();
}
bit confused... but sure you didn't need
Vector<ItemModel>
instead ofVector
for your class cast?Which type is returned by
getIntent().getExtras().getSerializable("key")
?Anything that implements List and Serializable is internally turned into an ArrayList. So it might go in as a Vector but it comes out as an ArrayList. It's probably better to treat it as just a List<> at both ends in the putter and getter.
As a general rule, don't use Vector either. All the methods are synchronized which makes it less efficient than an ArrayList.
Give this a try: replace
with
and
with
Declaring v1 and items as List objects should be enough, the change to
ÁrrayList
would just show if there was some strange issue with the Vector classes.According to the doc I see no reason why it shouldn't work with the
Vector
class too. Maybe, by chance, you imported different Vector classes, so you could double check your import statements if all classes importjava.lang.Vector
only.