接收ArraylistObject getParcelableExtra - NullPointerException

时间:2014-08-05 07:07:12

标签: android android-intent android-activity nullpointerexception

我无法弄清楚如何在android中的两个类别之间发送和接收以及arraylist-object。我在活动B中得到一个NullPointerException。

活动A

 private ArrayList <String[][]> stringObjects2D = new ArrayList <String[][]> () ; 
 Intent intent = new Intent(MainActivity.this, CalculationsActivity.class); 
 intent.putExtra("strObj2D", stringObjects2D );

活动B

 private ArrayList <String[][]> stringObjects2D;
 stringObjects2D = getIntent().getParcelableExtra("strObj2D");

 // just a check test if something is here. Here I get the NullPointerException
 System.out.println("size = " + stringObjects2D.size());

如果有人知道如何解决这个问题,那将非常有用。

感谢!!!

3 个答案:

答案 0 :(得分:1)

原因是String[][]不是Parcelable。请改用ArrayList<ArrayList<String>>

如果您认为嵌套类型太长,您还可以实现自己的Parcelable类来存储这些数据。请查看此question了解实施详情。

答案 1 :(得分:1)

您可以创建一个实现Parcelable的类,并使用该类传递意图以确保您传递parcelable object

<强>样品:

<强>更新

    public class Sample implements Serializable {
    private ArrayList<String[][]> stringObjects2D; 
    public Sample() {
                    stringObjects2D = new ArrayList <String[][]> ();
        String [][] s = {{"1","1"},{"1","1"},{"1","1"},{"1","1"},{"1","1"}};
        stringObjects2D.add(s);
        stringObjects2D.add(s);
        stringObjects2D.add(s);
        stringObjects2D.add(s);
    }
    public ArrayList <String[][]> getArray(){
        return this.stringObjects2D;
    }

}

用于:

Sample s2 = new Sample();
        Intent intent = new Intent(MainActivity.this, SecondActivity.class); 
        intent.putExtra("strObj2D", s2);
        startActivity(intent);

第二项活动:

 Sample stringObjects2D;
     stringObjects2D = (Sample) getIntent().getSerializableExtra("strObj2D");

     // just a check test if something is here. Here I get the NullPointerException
     System.out.println("size = " + stringObjects2D.getArray().get(0)[0]);

答案 2 :(得分:0)

使用

stringObjects2D = (ArrayList<String[][]>) getIntent().getSerializableExtra("strObj2D");

而不是

stringObjects2D = getIntent().getParcelableExtra("strObj2D");