简体   繁体   English

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

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

I am trying to pass a 2d array of ints to nextactivity. 我正在尝试将2d整数数组传递给nextactivity。 i tried to use bundle.putSerializable(like sending a string array) but i got null pointer exception. 我试图使用bundle.putSerializable(如发送字符串数组),但出现空指针异常。 Any ideas?? 有任何想法吗??

here is my code. 这是我的代码。 (tosend) (发送)

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

(toreceive) (接受)

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

Convert int 2D array to String 2D array and send it just like you did 将int 2D数组转换为String 2D数组并像发送代码一样发送

To convert: you would have to do so manually with a two-layer for() loop: 要进行转换:您必须使用两层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]);
    }
}

To send: 发送:

mBundle .putSerializable("cost", converted);

To get: 要得到:

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

And then again convert it into int 2D array. 然后再次将其转换为int 2D数组。

String[][] extends Object, while int and int[][] do not String [] []扩展对象,而int和int [] []不扩展

Hope this work for get data: 希望这项工作能获取数据:

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];
    }
}

Then turn back into int ... 然后转回int ...

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

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