I'm using two fragments in my activity using ViewPager and TabLayout. I want to send and receive data between my Activity and my Fragments.
I don't prefer to use a class with static variables to fix this problem. Is there a better way to do this task with out loosing much memory and resources. Because static data members never die in the whole life cycle of app. So they never release any chunk of memory. Which is a big problem for app to run in Samsung devices or you can say non rooted devices who restrict the usage of RAM.
Use Interface. Here is an excerpt from Android doc which contains details with examples of how to communicate between Fragment and Activity and vice versa: Define an Interface.
To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.
This makes your Fragment modular and allows you to reuse the same Fragment in multiple activities. All you would need to do is implement the interface in the new Activity.
You can do it in 2 ways.
First method is define a interface. interface example
Second method is eventbus. eventbus library
My preference eventbus. Even if possible, learn rxjava and do it with the event logic there. Rxjava tutorial
Here is an example of Fragment to Activity communication:
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
}
Related
I have noticed that I can create a callback by using two methods:
Receive an interface at the constructor of the class implementing the callback.
Receive the activity itself at the constructor of the class implementing the callback.
First Approach
For example I could do this:
public MyClass(MyInterface listener) {
this.listener = listener;
}
And I could call myCallBackFunction() defined in MyActivity (which implements MyInterface) by writing listener.myCallBackFunction()
Second Approach
Or I could do this:
public MyClass(MyActivity activity) {
this.activity = activity;
}
And I could call myCallBackFunction() defined in MyActivity by writing activity.myCallBackFunction()
My concern: Is one approach better than the other? And if so, why?
Usually speaking, you'd better use first approach. The reason is here:
Suppose you have 4 classes, first is Vehicle, second is Bicycle, third is Bus and third is Subway. Bicycle, Bus and Subway are subclasses of Vehicle. There may be a method call drive(), which should have a parameter. Which one do you think best for parameter type? Bicycle, Bus, Subway, or Vehicle?
Apparently, passing Vehicle is best because you may want to add other kinds of vehicles in the future or you don't want to write nearly same code for different kinds of vehicles in your project. It is same to use Interface rather than specific class.
As a result, passing an interface to a method is always correct and better than passing a specific type of object to it. You can always implement the interface in other classes and they will also be parameter of that method. You don't need to think about actual type of the parameter, which will confuse you and make you think more about specific code for specific type. Instead, only one type, one piece of code macroscopically.
So the conclusion is: using MyActivity is good, but using MyInterface is better.
I think it can depend on what you're trying to achieve: the first approach may in general be better suited since MyClass is not required to know anything about the implementation of that interface method, so it's great for passing different objects (e.g. a RecyclerView Adapter being created with an OnItemClickedListener injected in the constructor can be re-used in different activities/fragments implementing the interface, whilst the adapter doesn't need to change). It helps to prevent coupling.
The second approach leaves one wondering: is MyClass tied to the activity lifecycle? It may still hold a reference to the activity after that activity has actually been destroyed by the system, which would leak memory as the Activity object is not garbage-collected. It's a matter of design, and can be seen as code smell, can you not achieve what you wanted within the activity itself, and rely on the lifecycle callbacks onCreate/.../onDestroy?
Is one approach better than the other? And if so, why?
Using Interface is the best way..
Assume that you are having
1) Activity MyActivity
2) class which extends Activity or View or Asynctask is Myclass.
Both MyActivity and Myclass are Implements MyInterface
If you are passing Activity you need to add one more constructor
public MyClass(MyActivity activity) {
this.activity = activity;
}
public MyClass(Myclass myclass) {
this.myclass= myclass;
}
If you are using interface
public MyClass(MyInterface listener) {
this.listener = listener;
}
that's it.
In one approach you are creating an instance of Interface and in another an instance of implementing activity. what is best is:
Interface interface;
public myClass(Activity acitivity)
{
interface = (Interface)activity;
}
i.e. typecast activity to interface. Now you can callback the overridden functions in Activity.
This way you can now loose information of Activity's functions and just access the overriden functions of interface from the activity.
You can avoid typecasting and create an object of Activity, if you need access to interface callbacks AND the activity's function/variables.
It depends on your needs.
I have a question about "proper programming" in Android.
I am currently developing an app using fragments. It involves dynamically added fragments to Activity, fragments inflated from XML, nested fragments from XML or dynamically added. Let's just say, a bit of everything.
The concept this question focuses on is the communication process involved with fragments. So, I've read the docs and this is not the first time I try to use fragments.
The common sense (and docs) tell that if a Fragment wants to speak or communicate with it's activity, we should use an interface.
Example:
TestFragment
public class TestFragment extends Fragment {
private TestFragmentInterface listener;
public interface TestFragmentInterface {
void actionMethod();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (getActivity() instanceof TestFragmentInterface) {
listener = (TestFragmentInterface) getActivity();
}
// sending the event
if (listener != null) listener.actionMethod();
}
}
TestActivity
public class Test implements TestFragmentInterface {
#Override
public void actionMethod() {
..
}
}
Everything fine here.
This improves re-usability, as my TestFragment this way can interact with any kind of Activity, given the Activity implements the interface I declare.
The other way around, the Activity can interact with the fragment by holding a reference and calling its public methods. This is also the suggested way to fragment-to-fragment communication, using the Activity as a bridge.
This is cool, but sometimes it feels like using an interface for this is just a bit "too much".
Question A
In the scenario the fragments I attach have a pretty focused role, meaning they are done for that particular activity and would not be used otherwise, is it conceptually wrong to ignore the interface implementation and just do something like
((TestActivity) getActivity().myCustomMethod();
?
This also goes to the scenario where (not my case, but just taking it as a "at its worst") my activity has to deal with a wide variety of these DIFFERENT fragments, meaning it should implement one method for every fragment it should handle. This brings the code to a big mess of "potentially not-needed lines".
Moving further on: still with the use of "focused" fragments, aimed to work only under certain way, what is with the use of nested fragments?
Added them like
public class TestFragment extends Fragment {
private void myTestMethod() {
NestedFragment nested = new NestedFragment();
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, nested)
.commit();
}
}
this binds NestedFragment to TestFragment. I say it again, NestedFragment, just like TestFragment, is to be used only in this way, it has no meaning to work otherwise.
Back to the question, how should I behave in this situation?
Question B
1) should I provide an interface in NestedFragment, and make so that TestFragments implements NestedFragmentInterface? In this case I would act as following
NestedFragment
public class NestedFragment extends Fragment {
private NestedFragmentInterface listener;
public interface NestedFragmentInterface {
void actionMethodNested();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (getParentFragment() instanceof NestedFragmentInterface) {
listener = (NestedFragmentInterface) getParentFragment();
}
// sending the event
if (listener != null) listener.actionMethodNested();
}
}
2) should (or could) I ignore interface, and just call
getParentFragment().publicParentMethod();
?
3) should I create the interface in NestedFragment, but let the activity implements it, so that the activity will call TestFragment ?
Question C
Regarding the idea of using the Activity as a bridge between fragments, I believe it is made so for proper handling lifecycle of all these objects. Is it still viable to do a direct fragment-to-fragment (using interface or directly call public methods) while trying to handle manually the exception the system might throw me?
Ill do my best to answer the wall of text here :)
Question A:
Fragments are designed to be reusable modules that can be plug and played with any activity. Because of this the only correct way way to interface with the activity is to have the activity inherit from a interface that the fragment understands.
public class MapFragment extends Fragment {
private MapFragmentInterface listener;
public interface MapFragmentInterface {
//All methods to interface with an activity
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// sending the event
if (listener != null) listener.anyMethodInTheAboveInterface();
}
}
Then have the activity implement the interface
public class MainActivity extends Activity implement MapFragmentInterface{
//All methods need to be implemented here
}
This allows your fragment to be used with any activity as long as the activity implements this interface. The reason why you need this interface is because the fragment can be used with any activity. Calling a method like
((TestActivity) getActivity().myCustomMethod();
relies on the fact that your fragment only can work within a test activity and therefore "breaks" the rules of fragments.
Question B and C:
Assuming that you are following the correct guidelines for fragments and that they are independent modules. Then you should never have a situation where fragments need to know about each other. 99% of the time that people think they need fragments to directly communicate they can re-factor their problem to the situation I gave above by using a MVC patten or something similar. Have the activity act like the controller and tell the fragments when they need to update and then create a separate data store.
I will try to clear it all a little bit.
First of all, consider you approach of setting listener for fragment. It is no good to set listener in onViewCreated method, because it leeds to excess reseting listener any fragment is created. It is enough to set it up into onAttach method.
I told about code lines. Take me to notice, it is good to have BaseFragment implemented common behavior in you app as setting FragmentListener creating view from resource.
And more than that to reduce code lines and to get part of code reuse you can use generic in BaseFragment. So look at next code snippet:
public abstract BaseFragment<T extends BaseFragmentListener> extends Fragment {
T mListener;
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Activity instanceof T)
mListener = (T) activity;
}
abstract int getLayoutResourceId();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(getLayoutResourceId(), null);
// you can use some view injected tools here, mb ButterKnife
return layout;
}
}
Answer A (For Question A):
If you have fragment only exactly one activity you need to decide: "Do you really need to use Fragment here?". But mb it is good to have fragment exactly for one activity to extract some view logic from activity and clearing base logic. But for clearing base architecture logic for your app use Listeners. This will make life easier for other developers
Answer B:
For nested fragments you need to solve, what they need to use exact activity or just fragments and use it as a bridge to other system. If you know that nested fragment will be nested all time you, you need to declare parent fragment as listener otherwise you have to use other approach.
Notice:
As the base approach to communicate between diff part of App you can use events, try too look at event bus for example. It gives you common approach for communication and you can extract logic of calling custom methods of listeners and more another, all logic will be situated into handling events and you will have one mediator system for cooperation.
Answer C:
I partially explain one of approaches to cooperating between fragments. Using one event dispatcher avoids you to have many listeners for all different communication. Some times it is very profitably.
Or I think it is more usable to use Activity, or other class lives in Activity, for a mediator for Fragments cooperation because there is many situation of Fragments changing during lifecycle both handling and system. And it focuses all this logic in one place and makes your code more clear.
Hope my considerations helps you.
I wonder what way to call for parent's(Activity) function is the proper way to go, I have a activity which starts a fragment, from this fragment I want to call aFunction() in MyActivity.
is:
((MyActivity) getActivity()).aFunction();
or simply create an interface:
public class aFragment extends Fragment {
OnExampleListener mCallback;
// MyActivity must implement this interface
public interface OnExampleListener{
public void aFunction();
}
}
the best way to go about doing this?
It's not per se wrong, but it's discouraged as it makes your fragment dependent of the activity, which isn't the case if you're using interfaces. Use it for testing purposes, if you're serious about writing apps, use an interface.
Read the section about Fragment to Activity communication here to use interfaces: http://developer.android.com/training/basics/fragments/communicating.html
The Android documentation suggests that to communicate from an activity to a hosted fragment, the fragment can define a callback interface and require that the host activity implement it. The basic pattern involves implementing onAttach in your fragment, and casting the activity to a callback inteface. See http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity.
Here's an example of providing a fragment some initialization data, as well as listening for a navigation callback.
public class HostActivity extends Activity implements FragmentHost {
#Override
UiModel getUiModel() {
return mUiModel;
}
#Override
FragmentNavListener getNavListener() {
return mNavListener;
}
...
}
public class HostedFragment extends Fragment {
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof FragmentHost) {
FragmentHost host = (FragmentHost) activity;
setUiModel(host.getUiModel());
setNavListener(host.getFragmentNavListener());
}
}
...
}
Compare this to using onAttachFragment in the host activity to explicitly initialize the fragment:
public class HostActivity extends Activity {
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
if (fragment instanceof HostedFragment) {
HostedFragment hostedFragment = ((HostFragment) fragment);
hostedFragment.setUiModel(mUiModel);
hostedFragment.setNavListener(mNavListener);
}
}
...
}
To me, it seems like the first pattern has some drawbacks:
It makes the fragment harder to use from different activities, since
since all of those activities must implement the required interface. I can imagine cases where a given fragment instance doesn't require being fully configured by the host activity, yet all potential host activities would need to implement the host interface.
It makes the code slightly harder to follow for someone unfamiliar with the pattern being used. Initializing the fragment in onFragmentAttached seems easier to follow, since the initialization code lives in the same class that creates the fragment.
Unit testing using a library like Robolectric becomes harder, since when calling onAttach, you must now implement FragmentHost rather than just calling onAttach(new Activity().
For those of you who've done activity to fragment communication, what pattern do you find preferable, and why? Are there drawbacks to using onAttachFragment from the host activity?
I cant speak personally with respect to testing but there is alternatives to fragment / activity callback interface communication.
For example you can use a event bus to decouple the fragments and your activity. An excellent event bus can be found here:
Otto - An event Bus by Square
It is actively being developed by some very talented engineers at Square.
You can also use the LocalBroadcastManager that is packaged in the Android Support Library.
LocalBroadcastManager
Eric Burke from square has a presentation where he mentions both which can be found here:
Android App Anatomy
Update : As per the latest guidelines we are supposed to use a sharedViewModel class to communicate between fragments and activities.
However if you don't use viewModels and use callbacks, you should still consider removing onAttachFragment callback as it is deprecated now.
Instead on onAttachFragment, the suggested way is to add a listener to your fragmentManager who is associated with that transaction using addFragmentOnAttachListener.
See the example below:
childFragmentManager.addFragmentOnAttachListener { _, fragment ->
if (fragment is RetryDialogFragment) {
//Do your work here.
}
}
You should also be mindful of where you add this listener. You most probably want to add this listener before you execute the fragment transaction and should make sure that you are not adding the listener more than once.
I have used the Fragment.onAttach(...) pattern in my last project. I see two advantages:
you can check early that the hosting activity implements the required interface and throw an exception if not
there's less risk of holding onto a reference of the hosting context after the fragment has been detached
In order to take advantage of 2., you must not store references to UiModel and NavListener, as you do in your code sample. Instead, whenever you want to interact with these instances, you should use code like ((FragmentHost) getActivity).getNavListener().onNav(this), or alternatively ((FragmentHost) getActivity).onNav(this). You could store the fragment host in a field which you set to null in onDetach(...) as a middle ground approach, if you want to avoid the constant casting.
I agree that initializing a fragment from the activity that creates it seems more intuitive.
Having said all that, I'm going to skip fragments altogether in my current project. The following post reflects the lessons learned from my last one pretty well: https://corner.squareup.com/2014/10/advocating-against-android-fragments.html
I'd like my activity to send the same event to multiple fragment. Instead of making my activity calling each individual fragment method : FragmentA.DoTask(), FragmentB.DoTask(), FragmentC.DoTask(), etc... I'd like rather make my activity send only one event and then make the fragment listening to this event.
On the developpers docs they make the activity "listen" to the fragment but then the activity calls the fragments' methods. Is it possible the other way around : to make the fragments "listen" to the activity.
Thanks
You could Use EventBus system.
Description on RRiBbit (though this library not related to Android) define it precisely:
An Eventbus is a mechanism that allows different components to
communicate with each other without knowing about each other. A
component can send an Event to the Eventbus without knowing who will
pick it up or how many others will pick it up. Components can also
listen to Events on an Eventbus, without knowing who sent the Events.
That way, components can communicate without depending on each other.
Also, it is very easy to substitute a component. As long as the new
component understands the Events that are being sent and received, the
other components will never know.
So what exactly is a component here? Well, a component could be
anything. In most Eventbuses, they are Java Objects. They send Events
and they also listen to Events.
In Android you can use EventBus.
I don't think there is a way around it. The word "listen" in the docs is more metaphorical. You have to call all fragments explicitly.
The closet thing you can get, is to have a list of Fragment maintained in your Activity class. e.g.: create a customized Fragment class:
public class MyFragment extends Fragment{
public abstract void doTask();
}
Have all your Fragments inherited from this class.
public class FragmentA extends MyFragment{
#Override
public void doTask(){
//exec code here
}
}
In your Activity class, each time you create a Fragment, add it to a List too. When the event occurs, call all Fragments.
public class MyActivity extends Activity{
List<myFragment> mFragmentList = new ArrayList<MyFragment>();
public void addFragment(MyFragment fragment){
mFragmentList.add(fragment);
}
public void onEvent(){
for(MyFragment fragment:mFragmentList){
fragment.doTask();
}
}
}
Note: If you don't have that many Fragments, this solution can be a overkill.