putStringArray() using String 2-Dimensional array (String[][] )

后端 未结 3 1189
失恋的感觉
失恋的感觉 2021-01-07 08:00

I want to pass a 2-D String Array to another activity. My S2-D String Array (String[][]) is \'selected_list\'.

code is :

     Bundle list_bundle=new         


        
3条回答
  •  鱼传尺愫
    2021-01-07 08:44

    As Matthew said, you can put the string array in the bundle like this

    Bundle list_bundle=new Bundle();
    list_bundle.putStringArray("lists",selected_list);
    

    This works very well, but when you try to get the array via (String[][]) bundle.getSerializable("lists"); it gives a

    java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.util.String
    

    So what you have to do is this :

        Object[] objectArray = (Object[]) getIntent().getExtras().getSerializable("lists");
        int horizontalLength = 0;
        if (objectArray.length > 0)
            horizontalLength = ((Object[]) objectArray[0]).length; // See explanation to understand the cast
        String[][] my_list = new String[objectArray.length][horizontalLength];
        int i = 0;
        for(Object row : objectArray)
        {
            my_list[i][0] = ((String[])row)[0];
            my_list[i++][1] = ((String[])row)[1];
        }
    

    Explanation :

    When you get the array as I Serializable object it doesn't behave the same way a simple String array does, instead it considers every row as a separate array, so what you have to do is to read the Serializable object as a one dimensional array, and then cast every row of it to a String[] array. Et voila !

提交回复
热议问题