如何在活动之间传递二维2D数组?

时间:2013-04-08 16:16:46

标签: android arrays android-activity

我需要在活动之间传递一个二维的二维数组,这是我到目前为止写的: 在第一个活动(发件人)中:

Intent intent =new Intent(MapsActivity.this, RoutePath.class);
Bundle b = new Bundle();
b.putSerializable("other_locations", other_locations);
intent.putExtras(b);
startActivity(intent);

在第二个(接收者):

Intent intent = getIntent();
Bundle b = intent.getExtras();
double[][] other_locations=(double[][]) b.getSerializable("other_locations");

但是我得到了ClassCastException,我做错了吗?

2 个答案:

答案 0 :(得分:4)

双二维数组转换为字符串二维数组并像发送一样发送它:

发送:

b.putSerializable("array", other_locations_string);

获得:

String[][] value = (String[][]) b.getSerializable("array");

然后再次将其转换为双二维数组

这种行为的原因是因为Java(以及因此Android)不允许您将对象转换为基本类型或基本类型数组。为什么?因为Java认为有效的强制转换将超类对象转换为子类对象,反之亦然。 String[][]扩展Object,而双倍double[][]则不扩展。{/ p>

答案 1 :(得分:1)

试试这个

将2D数组转换为Hashmap,然后使用它

Map<Double, Double> map = new HashMap<Double, Double>(other_locations.length);
for (Double[] mapping : other_locations)
{
    map.put(mapping[0], mapping[1]);
}

将map设置为intent extra并在第二个活动中获取额外的