Android: how to pass ArrayList<object> from an activity to another

前端 未结 2 826
梦毁少年i
梦毁少年i 2021-01-21 18:11

The object in the arraylist is defined in an external library. The object contains some int values and also a float[].

How can I pass all the ArrayList from an activity

相关标签:
2条回答
  • 2021-01-21 18:54
    Intent intent = new Intent(this, TargetActivity.class);
    intent.putExtra("nameOfArray",YOUR_ARRAY_LIST);
    startActivity(intent);
    
    0 讨论(0)
  • 2021-01-21 19:06

    It depends on the type of object that's in the array list. If you have control over it and can have it implement Parcelable, then you can use Intent.putParcelableArrayListExtra.

    Another approach is to extend Application and store your ArrayList there. It then doesn't need to be passed in the Intent, and all activities in the application can access it by calling getApplication(). The Application object will persist for the life of the application, as will any data stored in it.

    EDIT:

    To use an Application object for this:

    1. Write a class (let's call it MyApplication) that extends android.app.Application. Declare a field (let's call it array) to hold your array list.
    2. Specify the name MyApplication in the manifest's <application> tag. An instance of MyApplication will be created by the system when it creates the process for your app.
    3. Any activity that wishes to access the field can use ((MyApplication) getApplication()).array. You initialize it in the first activity and retrieve it in the second.

    Another completely different approach is to declare a static singleton in some class. The docs actually recommend this over subclassing Application as being more modular. It's kind of a hack because it's basically declaring a global variable. But I suppose it's no more of a hack than putting random data in an Application object.

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