开发者

How to use data in different activities?

开发者 https://www.devze.com 2023-01-21 16:31 出处:网络
I have two activities A & B. In A i have three ArrayLists. I want to access these ArrayLists in activity B . How can I do that? These two activities are in sa开发者_JAVA百科me package.To answer yo

I have two activities A & B. In A i have three ArrayLists. I want to access these ArrayLists in activity B . How can I do that? These two activities are in sa开发者_JAVA百科me package.


To answer your question - which you could have easily found the answer to by searching stackoverflow - if you need to pass an ArrayList you can do like this:

ArrayList<String> list = new ArrayList<String>();
list.add("hello");

Bundle b = new Bundle();
b.putSerializable("myList", list);

Intent myIntent = new Intent(this, ActivityB.class);
myIntent.putExtras(b);
startActivity(myIntent);

And in ActivityB:

Intent myIntent = this.getIntent();
ArrayList<String> list = (ArrayList<String>) myIntent.getSerializableExtra("myList");


You probably can't access them directly. Usually only 1 Activity can be in the foreground. Trying to access elements in a background Activity (so like you lists in A from the acitve B) is a bad design choice.

I think you need to store the data from those lists in some shared location:

  • make them parcelable and store them in you app's preferences
  • store them in a SQLite db
  • pass them to Activity B via the starting Intent

Also, maybe you don't need to pass the whole lists to B, maybe you need only a part of them, consider that too.


* make them parcelable and store them in you app's preferences
* store them in a SQLite db
* pass them to Activity B via the starting Intent

It's wrong. Wrong I mean in a sense that no need to store Parcelable object in persistent storage, since as soon as you make object Parcelable - another Activity can get access to object without serialization (moreover serialization is not recommended). Android docs read:

Container for a message (data and object references) that can be sent through an IBinder. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC (using the various methods here for writing specific types, or the general Parcelable interface), and references to live IBinder objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel.

Parcel is not a general-purpose serialization mechanism. This class (and the corresponding Parcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport. As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.

0

精彩评论

暂无评论...
验证码 换一张
取 消