How to pass ArrayList using putStringArrayListExtra()

后端 未结 4 1600
無奈伤痛
無奈伤痛 2020-12-06 06:13

Hi I want to pass an Arraylist from one activity to another. I use putStringArrayListExtra(), but there shows an error : \"The m

相关标签:
4条回答
  • 2020-12-06 06:38

    You have to define ArrayList of type String. you can't pass Generic ArrayList in putStringArrayListExtra. Below is the correct code.

    -----
    ArrayList<String> al = new ArrayList<String>();
    ------
    -------
     list_bundle.putStringArrayListExtra("lists",al); 
    ------
    

    Now access this ArrayList in other activity like this.

    ArrayList<String> cl= new ArrayList<String>();
    cl =getIntent().getExtras().getStringArrayList("lists");
    
    0 讨论(0)
  • 2020-12-06 06:40

    try below one to pass 1-D array to Arraylist in extras

    ArrayList<String> al = new ArrayList<String>();
    String arr[] = {"Zero", "One", "Two"}; 
    //Convert string array to a collection 
    Collection l = Arrays.asList(arr);
    al.addAll(l); 
    i.putStringArrayListExtra("ar", al);
    
    0 讨论(0)
  • 2020-12-06 06:41

    First Activity :

     ArrayList<String> al = new ArrayList<String>();
        int ROWS = 2;
                            int COLS = 1;
                            String[][] a2 = new String[ROWS][COLS];
                            a2[0][0]="one";
                            a2[1][0]="two";
                            for(int i=0;i<ROWS;i++)
                            {
                                for(int j=0;j<COLS;j++)
                                {
                                    al.add(a2[i][j]);
                                }
                            }
         i.putStringArrayListExtra("ar", al);
                            i.putExtra("ROWS", ROWS);
                            i.putExtra("COLS", COLS);
    

    Second Activity :

    ArrayList<String> test = new ArrayList<String>();
    test=getIntent().getExtras().getStringArrayList("ar");
            int ROWS=getIntent().getExtras().getInt("ROWS");
            int COLS=getIntent().getExtras().getInt("COLS");
            String[][] a2 = new String[ROWS][COLS];
            int index=0;
            for(int i=0;i<ROWS;i++)
            {
                for(int j=0;j<COLS;j++)
                {
                    a2[i][j]=test.get(index++);
                }
            }
    
    0 讨论(0)
  • 2020-12-06 06:52

    Try this It worked for me

    1st Activity

    ArrayList<String> ar=new ArrayList<String>();
    ar.add("Apple");
    ar.add("Banana");
    
    Intent i=new Intent(this,Route.class);
    i.putStringArrayListExtra("list", ar);
    startActivity(i);
    

    2nd Activity

    ArrayList<String> ar1=getIntent().getExtras().getStringArrayList("list");   
    
    0 讨论(0)
提交回复
热议问题