簡體   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