简体   繁体   中英

Passing Arraylist<CustomObject> using Parcelable, passing null

Github: https://github.com/jjvang/PassIntentDemo

I've been following this tutorial about passing object by intent: https://www.javacodegeeks.com/2014/01/android-tutorial-two-methods-of-passing-object-by-intent-serializableparcelable.html

I understand from the tutorial how to send an Arraylist implementing Parcelable if you have only 1 set of values like this:

  public void PacelableMethod(){  
        Book mBook = new Book();  
        mBook.setBookName("Android Developer Guide");  
        mBook.setAuthor("Leon");  
        mBook.setPublishTime(2014);  
        Intent mIntent = new Intent(this,ObjectTranDemo2.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putParcelable(PAR_KEY, mBook);  
        mIntent.putExtras(mBundle);  

        startActivity(mIntent);  
    }

I have arranged the code so I can continue to add to the ArrayList to size 2 or greater but notice that the ArrayList I pass to the next activity is null.

I would like to understand if I would have to add to the ArrayList differently or if I am just sending/catching the Arraylist incorrectly.

Trying code change like this:

public void PacelableMethod(){
    ArrayList<Book> words = new ArrayList<Book>();
    words.add(new Book("red", "yes", 1));
    words.add(new Book("mustard", "yes", 1));
    Toast.makeText(this, "" + words, Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(this,ObjectTranDemo2.class);
    intent.putExtra("Contact_list", words);
    Bundle mBundle = new Bundle();
    intent.putExtras(mBundle);
    startActivity(intent);
}

public class ObjectTranDemo2 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayList<Book> myList = getIntent().getParcelableExtra("Contact_list");
        Toast.makeText(this, "" + myList, Toast.LENGTH_SHORT).show();
    }
}

Please advise, thank you!

I believe you need to add your array list to the intent extras using putParcelableArrayListExtra : intent.putParcelableArrayListExtra(Contact_list", words)

then receive it with getParcelableArrayListExtra

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM