Passing ArrayLists in Android

2019-02-17 20:33发布

问题:

I'm trying to pass array lists between activities in Android. The lists contains strings. I've read a lot about Parcelable. Would I need to create a Parcelable to pass a String array list? As of now I am using putStringArrayListExtra() and getSringArrayListExtra() to pass the lists through intents.

Here is some of my code.

Intent load = new Intent(getApplicationContext(), HelloTabWidget.class);
        load.putStringArrayListExtra("albums", albums);  
        load.putStringArrayListExtra("songs", songs);  
        load.putStringArrayListExtra("artists", artists); 
        load.putStringArrayListExtra("fileName", fileName);  

This is my onCreate method for the acticity which obtains the array list.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.songlist); 

    Bundle extras = getIntent().getExtras();
    isArtists = extras.getBoolean("artists");   
    isAlbums = extras.getBoolean("albums"); 
    isSongs = extras.getBoolean("songs");   

        Intent get = getIntent();  
        songs = get.getStringArrayListExtra("songs"); 
        artists = get.getStringArrayListExtra("artists");
        albums = get.getStringArrayListExtra("albums");
        fileName = get.getStringArrayListExtra("fileName"); 



    if(isArtists == true)       
        updateArtistsList(); 
    else if(isAlbums == true) 
        updateAlbumsList();  
    else if(isSongs == true) 
        updateSongList();    
}

The class which retrieves the list is supposed to create a listView from the data in the lists. Whenever I run the code i get nullPointerExceptions when trying to make the lists. I know that my listView code works, so I have narrowed down the problem to the intents which pass the array lists.

Thanks in advance.

EDIT: Here are the first few lines from the logcat.

12-28 03:03:42.313: E/AndroidRuntime(873): FATAL EXCEPTION: main
12-28 03:03:42.313: E/AndroidRuntime(873): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adam.mediaplayer/com.adam.mediaplayer.HelloTabWidget}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adam.mediaplayer/com.adam.mediaplayer.MakeListActivity}: java.lang.NullPointerException

回答1:

It depends on the type of arraylist

  • putIntegerArrayListExtra(String name, ArrayList<Integer> value)

  • putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)

  • putStringArrayListExtra(String name, ArrayList<String> value)

  • putCharSequenceArrayListExtra(String name, ArrayList<CharSequence> value)

Then you can read from you next activity by replacing put with get with key string as argument,eg

myIntent.getStringArrayListExtra("arrayListName");


回答2:

Here is how you can pass an ArrayList :

MyListClass.java - Custom class

public class MyListClass implements Parcelable{

private int test;

public MyListClass()
{}

public MyListClass(Parcel read){
    test = read.readInt();
}

public int getTest() {
    return test;
}

public void setTest(int test) {
    this.test = test;
}

public static final Parcelable.Creator<MyListClass> CREATOR = 
    new Parcelable.Creator<MyListClass>() {

        @Override
        public MyListClass createFromParcel(Parcel source) {
            return new MyListClass(source);
        }

        @Override
        public MyListClass[] newArray(int size) {
            return new MyListClass[size];
        }
    };

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeInt(test);
}

}

MyParcelable.java

public class MyParcelable implements Parcelable {

private List<MyListClass> arrList = new ArrayList<MyListClass>();
private int myInt = 0;
private String str = null;

public String getStr() {
    return str;
}

public void setStr(String str) {
    this.str = str;
}

public List<MyListClass> getArrList() {
    return arrList;
}

public void setArrList(List<MyListClass> arrList) {
    this.arrList = arrList;
}

public int getMyInt() {
    return myInt;
}

public void setMyInt(int myInt) {
    this.myInt = myInt;
}

MyParcelable() {
    // initialization
    arrList = new ArrayList<MyListClass>();
}

public MyParcelable(Parcel in) {
    myInt = in.readInt();
    str = in.readString();
    in.readTypedList(arrList, MyListClass.CREATOR);
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel outParcel, int flags) {
    outParcel.writeInt(myInt);
    outParcel.writeString(str);
    outParcel.writeTypedList(arrList);
}

public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {

    @Override
    public MyParcelable createFromParcel(Parcel in) {
        return new MyParcelable(in);
    }

    @Override
    public MyParcelable[] newArray(int size) {
        return new MyParcelable[size];
    }
};

}

MainAcitivty.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    arrList.add(new MyListClass());
    arrList.get(0).setTest(200);

    MyParcelable object = new MyParcelable();
    object.setMyInt(100);
    object.setArrList(arrList);

    Intent intent = new Intent(MainActivity.this,ReceiverParcel.class);
    intent.putExtra("parcel", object);
    startActivity(intent);
}

ReceiverParcel.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle b = getIntent().getExtras();
    MyParcelable object = b.getParcelable("parcel");

    System.out.println(object.getArrList().get(0).getTest());
    System.out.println(object.getMyInt());

}