Hope you guys can clarify something for me.
I've been using Android for about 6 months now and I'm still confused about the best way to communicate between Activity and Fragments. I've already read the the info on the android developer site.
Fragment to Activity
Right now I know with 100% absolute certainty that an interface is the best way to communicate from Fragment to Activity. I.e. creating an interface in your Fragment and letting your Activity implement it. This way you can call the method from your interface inside your Fragment and have it handled by the Activity (which implements the interface).
Activity to Fragment
Here's were I'm not sure. The android developer site says that in order to communicate with a Fragment you have to put your objects in a Bundle.
Bundle bundle = new Bundle();
bundle.putInt(SOME_IDENTIFIER, myInt);
Now I've been know to use a Singleton class every now and then when I have quite some functionality that I can separate. Say I have a Singleton called PersistenceService where I handle all of the persistence related stuff, e.g. saving something in the SharedPreferences. The PersistenceService will then hold methods like putMyString(String key, String myString) or putSomeObject(String key, SomeObject someObj). This way a class doesn't have to handle persistence itself but can just call the PersistenceService to do it.
Now say I have to update something in my Fragment, a TextView or something.
This is what I do:
String myString = PersistenceService.getInstance(getActivity()).getMyString(someKey);
textView.setText(myString);
I pass in a context (getActivity()) because I need it to get the SharedPreferences.
Now my actual question is:
Do I retrieve my data in the Activity and pass it to the desired Fragment through its Bundle? Or do I simply reference my Singleton right in my Fragment and access the data there directly.
I'm not stuck or anything, but I'd like to know what you guys would recommend.
Any advice, remarks, info etc. is greatly appreciated.
This is a very broad question, and as the pragmatic thinking and learning book says, the answer to most questions in software is "It all depends!".
And it really does, it really all depends, there's no hard rule in software, "always" and "never" are very powerful words that shouldn't be used in software, so, saying always go for "Bundle" info or Never go for a Singleton is a little bit stupid specifically in software, so, instead of telling you exactly what to use, ask your self what would fit better in your needs taking on count things like, scalability, extensibility manageability, etc. For example:
If you go for Bundle, you give some flexibility to your fragment, you are creating some kind of independent component ready to work with whatever information you provide, on the other hand, if you know that you need that fragment only in that place, and the information you will pass is somehow complex(can't be passed using a bundle), why complicating so much? Just go for the Singleton if it does the job simple and clean.
I hope my point is well explained here, there's no hard rules for one way or another, just be as diligent as possible and don't go one way or another just because of laziness or negligence, instead be analyst if it's worth going one way or another based on your needs, and always take on count that not because you went that way this time it will be true for ALL your scenarios.
Hope it Helps!
Regards!
I use bundle when I want send data from fragment to fragment (from fragment to activity by interface, from activity to fragment by bundle).
If data is used in all fragments singleton is the best way, sometime I use also a istance of data objcet in activity that I manipulate in fragment by public methods of activity but I don't think that this is a best pratic.
Please understand that 2 fragments can’t directly communicate with each other, They will need help of the activity under the context of which they are created. Using an interface :).
Implement the interface in a fragment
interface StartCommunication
Define the interface in the activity whose context fragment is using
public class MainActivity extends Activity implements
SendFragment.StartCommunication
Related
May be its simple question, may be its repeated question, this question s not for upvote and all.
I just want to pass my object from one activity to second and second to third activity. I know there are a lot of ways using shared preferences, Intent bundle from one to another activity.
The reason I want to know that why I can't use an object globally for all my activities and if I can how it is possible?
Thanks
There is a handful of ways in which you can achieve this.
Using a bus/listener:
https://github.com/greenrobot/EventBus
https://square.github.io/otto/
Using the application class (ready the first answer carefully, there are caveats):
How to declare global variables in Android?
And using utility classes with static methods.
Also, if you are have more than one fragment running at the same time, you can create your own interfaces and implement them where you need to receive the information.
I'm trying to access a function in one Fragment (f1) from another Fragment (f2). It seems that i have to make my function in f1 public and static to be able to access it from f2.
I've read that it's not a good idea to access one Fragment from another, so i've tried to make f2 access my Activity, which then connects to the function in f1. Although, even doing it this way, i still have to make my function in f1 public and static.
I don't reuse the Fragments, i simply have them in a ViewPager for swiping back and forth through the Fragments.
At the moment i have a lot of static variables because i have to make my functions static to access them from other Fragments.
Am i going about this the wrong way? Is there a better way?
Thanks in advance.
You're going down a road of much pain unless you are very controlled about what you do.
First of all, sharing state through static methods and variables is a fairly awful way of doing things, and static members won't be able to access anything in the instance of the fragment. If you really think you need to use static methods, don't bother putting them in the fragment classes. They don't provide an advantage there. Put them in a common class that they all reference.
Second of all, if you're using a ViewPager with fragments, you can't be guaranteed that any given fragment's view hierarchy even exists at any moment in time. This is because ViewPager typically only keeps fragment views alive that are on the current page or on +/- 1 offset from the visible page. So if you need to tell a fragment at offset +2 from the current fragment, you won't be able to make visible changes to it.
Instead, the easiest thing to do is create an object that maintains whatever state you want to share between the fragments, and have them all make changes to that one object. If you need instant changes to other fragments, you can use something like an event bus to have those changes communicated to other active fragments.
What you're trying to do is in general fairly complex. Expect to spend a lot of time designing a correct solution, and be sure to learn how fragments and ViewPager works very well.
You got two questions
1. Am i going about this the wrong way?
Yes, its not recommended to have the methods & variables declared static just to make them used to access from outside of your class.
2. Is there a better way?
Yes, declare the methods as public (but not static) inside its fragments.
From the activity (which is hosting the fragments) get the reference to the fragments using FragmentManager classes methods findFragmentById() or findFragmentByTag() then call the methods.
Sample :
Fragment fragment =
fragmentManager.findFragmentByTag.findFragmentById
(R.id.fragment);
or
Fragment currentFragment =
fragmentManager.findFragmentByTag("fragmentTag");
If you really require both of your functions to be isolated, you can use Broadcasts. Just send a Broadcast from one fragment and have the Broadcast receiver in the other fragment.
Most the app so far I had created, I fetch the data from Network and store it in a singleton class to share data between Activities, when I'm done with those data, I usually clear those setting it to NULL, its work perfectly well
My Question is which approach is better ??
Use parcelable
Writing in database and Query for it
Singleton classes
When exactly we need to use Loaders ?? Why we can't share the data through Loaders ??
If question is repeated ... Please ignore ??
Answer to first part
Parcelable:
The best way to pass data between Activitys or Fragments is by using Parcelable objects. It is said to be more optimised than Serializable. There are couple of libraries/plugins which can help you create Parcelable objects. Lately I was referred to Parceler, created by John Carl. However, I personally use Android Parcelable code generator by Michal Charmas, plugin for IntelliJ IDEA and Android Studio.
DataBase or SharedPreferences:
Using DataBase or SharedPreferences to pass data between Activitys or Fragments sounds weird, and since they are not designed to be used this way, it will only create a mess.
Singletons:
Read this very informative post Singletons are Pathological Liars.
Conclusion:
I recommend Parcelable or if you want to be real lazy then go for Serializable (it's not terrible but it's not great either, according to most).
Don't mess up your code by using singletons, DataBases, static fields, etc. They will come back and haunt you.
Answer to second part:
When exactly we need to use Loaders
Loaders, which will be AsyncTaskLoader when you use, are basically used for situations where we want to retrieve data from the server (via web API), or doing something in background. It is similar to using Thread or AsyncTask but is very powerful as it isn't destroyed on screen rotation, unlike those two.
You should read How to Use Loaders in Android and Alex Lockwood's posts on Loaders (this is a series of 4 posts. Very detailed and great).
It all depends on the way you want to use the data.If you want to use the data in future, as in after the application is killed and re launched you should save it in a database.
I would prefer parcelable over a singleton as I don't have to bother about clear the data.
According to the Documentation we generally use loaders to load data asynchronously and to monitor a the data source for change. To my understanding you aren't doing either of them, hence loaders are not required in this case.
1.Database: If you are going to use the network data in future or you are going to do some query operation to perform filtration according to requirement,it is preferable to go with db.
2.Singleton Class: Most of the developer use this because it is more efficient,the values can be changed and retrieve easily with the help of getters and setters.
Here is a very cool way of passing data to another activity I read this somewhere else on Stackoverflow and always use it now. It may not fit your use-case but it sounds like it will.
For example, say you want to pass a parcelable "DataModel" from ActivityA to ActivityB.
Inside ActivityB create a public static method called 'start' like this.
private static final String DATAMODEL_KEY = "datamodel_key";
public static void start(Context context, DataModel dataModel) {
Intent intent = new Intent(context, ActivityB.class);
intent.putExtra(DATAMODEL_KEY, dataModel);
context.startActivity(intent);
}
To start ActivityB simply call the 'start' method above like this
ActivityB.start(this, datamodel);
Use 'this' if called from an activity, or 'getActivity()' from with a fragment.
This will contain the code for starting ActivityB inside ActivityB, like the private static final DATAMODEL_KEY field and such. To answer your question though, go with option 1 and use parcelables and try out the code I posted above to help with starting the Activity with the data.
I have faced with the problem. My Activity is fragment container, so to communicate between activity and fragments I used common Callback approach. In this case my activity has to implement tons of callback interfaces depending on fragment count.
I don't like to hardcode and unreadable code. In my case my class declaration can take several lines to list all interfaces.
I am trying to get rid of this.
There is another approach is to use EventBus pattern.
In activity
EventBus.getDefault().register(this);
In fragment
EventBus.getDetault().post(new MyEvent(description));
And handle several event types in activity.
Maybe there will be better to use EventBus here instead default Callback approach ??
Or maybe there is my fault that my activity is holding a lot of fragments (God Object) and it is better to use activities instead Fragment ?
Please suggest which approach is better ?
For simple one Activity to one Fragment hierarchy, callback is simplest decision to go. But think about Activity containing a Fragment, and the Fragment contains swipe-able ViewPager, and each tab of ViewPager has Fragments A,B,C.
The Fragment A,B,C will go to long journey to send event to mother Activity, and it can be lost interface connectivity between Activity and children when they are restored during crazy complex Android Activity-Fragment lifecycle dances. In this case, eventbus like otto can be a good choice.
The drawback of event bus approach is, it is hard to maintain where the event is come from. So, keeping a few sender is recommended.
Your interface approach is awesome, just keep up with them, and maybe try and slice/make your interface static and add all the little little voids and return methods to that interface so you can just implement one and call the functions.
EventBus? how about LocalBroadcastReceiver ? its a matter of preference and which one you feel will suit you better, after all if you handle 10,000 request and hate having 100 interfaces, you will end up using 1 and nesting 99.
& just forgot, it is better to hold alot Fragment instead of Activity because at the end of the day the Activity lifecycle is pretty hard to maintain second of all you can not really control Activityies well all as compared to Fragments and Fragment is a good slave, serves you better
hope its valuable
I am new to Android Fragment and trying to learn Fragment to Activity communications.
What is the better approach(best practice) in Android for Fragment to Activity communication?
Lets say I have FragmentA and ActivityA.
After my screen popups FragmentA, I would like to perform somemethod(probably UI related) in ActivityA
Here are two(pattern) possible
Solutions:
In FragmentA getActivity and cast the Activity to ActivityA and then call somemethod.
In FragmentA create an interface callback and then implement that callback in ActivityA. Then on the callback, call somemethod.
Which pattern is more common/perfer in Android development and why. Or do you have an even better way to communicate from fragment to activity in Android to share with me?
Any comments, opinions, and suggestions is highly appreciated and welcome. ^^ .
The second solution is the preferred one, because it allows your fragment to be more independent of its hosting activity.
If in the future you decide to put your fragment on a different activity, there are no changes needed on the fragment, and you will only need to implement the interface on your activity.
I'll add a third solution which is using an event bus (Otto for instance), which also works, although some might argue that it makes your code a little less readable.
First method will be a bad practice. Second method will work fine but your fragment is going to be tightly coupled with your activity.
There is one more better approach is to use some event bus library like otto
Using this you can communicate effectively with loose coupling in your activity & fragment.
Your second approach is more flexible. You might not see a huge benefit in one activity and one fragment case. If you have to use the same fragment in another activity, it will most likely break by casting your activity like that. That said, there is nothing wrong with the first approach, but it is just a little restricted.
First pattern is best when your fragment is used only by one activity.
Second approach is needed if you want your fragment to communicate with some other objects not the activity that hosts fragment. If you always want to communicate with hosting activity callback is not needed. Just create an interface and implement it on as many activities as needed. Then in your fragment cast activity returned by getActivity().
MyInterface myInteface = (MyInterface) getActivity();
myinterface.somemethod();
You can even check if activity implements needed interface(s) etc.
The interface approach works fine and is more flexible in so far as it doesn't tie your fragment to the activity directly. One thing you should also consider is how much work the activity might need to do, that is it may end up managing several fragments. This has a tendency to lead to 'fat fragments' as my question here asked when I started using them