简体   繁体   中英

Share data between fragments in android

What is the best solution to deal with an "AdapterA of a RecyclerViewA which is inside a FragmentA" that want to use data from another "AdapterB of a RecyclerViewB which is inside a FragmentB" ?

在此处输入图片说明

I am stuck,i tried to :
1- Make the data static in the adapter (no garbage collector)
2- Duplicate data that i need (waste of memory)
(it works but may be there is a better solution)

Thank you in advance. (plz ask for details if you need)

If you, in MainActivity, create a new instance of a class where you contain whatever you want both fragments to access. If you implement Serializable or Parcelable, you can also send it to each fragment using Bundle/Intent.

Then, as you have the same instance in two different fragments, if you edit data in fragment X, fragment Y will be able to access it.

See this:

   |---MainActivity---|
   |         |        |
   V         V        V
 Frag A <->Data <->Frag B

MainActivity creates a new class(data) which it sends to each of the fragments. The fragments can update the data in the class. Please note, that you have to use class if any given data type isn't supported.

If you don't feel like using Serializable or parcelable, if possible, send MainActivity as an instance to each of the fragments. From each fragment you then get the MainActivity instance and find the data you need.

If you can't pass MainActivity to either of the fragments, and cannot use Serializable/Parcelable and the data type isn't supported by bundle.putExtra or intent.putExtra, you have to use a static import.

Those are your only options.

Alternatively, you can create a class that extends "Application". Then you write:

MyApplicationClass mac = (MyApplicationClass) getApplicationContext();

Then you access the data in the application-extending class(here: the mac instance)

Final words

If you do not want to use static instance, send a parcelable/serializable class with the contents, or use a class extending Application, there is no way you can transfer the data(considering you are using a HashMap which you claim cannot be sent by Intent or Bundle). If you had a data type or class that was possible to send using Intent or Bundle, you wouldn't have to use static instance or parcelable/serializable class. But with the position you are in, I have presented all the options you have. There are basically no other ways than using a class containing the hashmap, using a static instance or utilizing the Application class.

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