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

后端 未结 3 1185
失恋的感觉
失恋的感觉 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:33

    This finally works well for me : Thanks to Matthew and Mehdiway

    To start a new activity (sending String[][] and String):

    String[][] arrayToSend=new String[3][30];
    String stringToSend="Hello";
    Intent i = new Intent(this, NewActivity.class);
    
    i.putExtra("key_string",stringToSend);
    
    Bundle mBundle = new Bundle();
    mBundle.putSerializable("key_array_array",  arrayToSend);
    i.putExtras(mBundle);
    
    startActivity(i);
    

    To access in NewActivity.onCreate:

    String sReceived=getIntent().getExtras().getString("key_string");
    
    String[][] arrayReceived=null;
    Object[] objectArray = (Object[]) getIntent().getExtras().getSerializable("key_array_array");
    if(objectArray!=null){
        arrayReceived = new String[objectArray.length][];
        for(int i=0;i<objectArray.length;i++){
            arrayReceived[i]=(String[]) objectArray[i];
        }
    }
    
    0 讨论(0)
  • 2021-01-07 08:34

    You can use putSerializable. Arrays are serializable, provided their elements are.

    To store:

    list_bundle.putSerializable("lists", selected_list);
    

    To access:

    String[][] selected_list = (String[][]) bundle.getSerializable("lists");
    
    0 讨论(0)
  • 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 !

    0 讨论(0)
提交回复
热议问题