繁体   English   中英

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

[英]how to pass a 2d array of ints between activities?

我正在尝试将2d整数数组传递给nextactivity。 我试图使用bundle.putSerializable(如发送字符串数组),但出现空指针异常。 有任何想法吗??

这是我的代码。 (发送)

Intent myIntent=new Intent(context,activityvogel.class);
                    Bundle mBundle = new Bundle();
                    mBundle.putSerializable("cost",cost);
                    myIntent.putExtras(mBundle);
                    startActivity(myIntent);}

(接受)

Bundle extras = getIntent().getExtras();
        final int cost[][]= (int[][]) extras.getSerializable("cost");

将int 2D数组转换为String 2D数组并像发送代码一样发送

要进行转换:您必须使用两层for()循环手动进行此操作:

String[][] converted = new String[cost.length][];
for(int index = 0; index < cost.length; index++) {
    converted[index] = new String[cost[index].length];
    for(int subIndex = 0; subIndex < cost[index].length; subIndex++){
        converted[index][subIndex] = Integer.toString(cost[index][subIndex]);
    }
}

发送:

mBundle .putSerializable("cost", converted);

要得到:

String[][] converted = (String[][]) mBundle.getSerializable("cost");

然后再次将其转换为int 2D数组。

String [] []扩展对象,而int和int [] []不扩展

希望这项工作能获取数据:

String[][] strCost = null;
Object[] objCost = (Object[]) getIntent().getExtras().getSerializable("cost");
if (objCost != null){
    strCost = new String[objCost.length][];
    for(int i = 0; i < objCost.length; i++){
        strCost[i] = (String[]) objCost[i];
    }
}

然后转回int ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM