The right way to pass an object to fragments? - android

I want to pass an object to fragments
when the object shouldn't or can't recreate in a fragment (e.g. LruCache).
Is it possible without using static variable?
since passing variable may not always same object
Edit:
To make it clear I don't want the object to be null when activity recreated

For passing object to fragment you should use interface have a look at this link.
You can pass object via constructor and getter and setter also but in case of app resume object might be null that will cause NullPointerException on app resume.
Edited
If you are working with LruCache and want to share its data within fragments. I will suggest you to create a fragment without a onCreateView() method, means it will be invisible fragment. Implement a LruCache object in fragment and have getters and setters to get and set desired objects from LruCache.
Fragments have a characteristics of re-usability in contrast to a simple class. You can find a fragment by its tag.
For example: To add a fragment-
activity.getFragmentManager().beginTransaction().add(fragment, TAG).commitAllowingStateLoss();
and to get a fragment-
activity.getFragmentManager().findFragmentByTag(TAG);
In contrast to normal class Fragment class is removed from memory only when device is in sort of memory. Whenever fragment is null you will have to re-initialize it.
To know more about its implementation details visit this link

Related

What is difference in 2 ways transfer data to fragment from activity using getArgument() and getActivity.getXXX()

I wonder the difference between two ways of transfering data from activity to fragment.
One is using getArgument() and setArgument(). I can transfer data using these methods at Fragment's contruction time.
Another is using getActivity() method. Like this way
((HostActivity)getActivity()).getXXX()
After declaring getter method of data Fragment may use, call this method in fragment through getActivity() and Type casting.
I think second one is easier and convenient. Because get/setArgument() can be called only Fragment's contruction time.
So, How to apply these 2 way to sending and getting data between Activity and Fragment?
A Fragment represents a behavior or a portion of user interface in an
Activity. You can combine multiple fragments in a single activity to
build a multi-pane UI and reuse a fragment in multiple activities.
Because fragment can reuse in multiple activity, if you use getActivity() with type casting, you must check instanceOf activity before call method. And each of activity use that fragment, you must implement method getXXX().
Use newInstance method in fragment, you only pass require parameter for it.
If you create fragment for individual activity, you can apply 2 ways transfer data.
The fragment has an independent lifecycle from activity with specific threads, functions and handlers. So you can use getters/setters Activity variables like a global variables and bundle data (arguments) to independent fragment variables.

Share Headless Fragment Between Activities

For some reason my understanding was that a headless Fragment lives for the duration of your application. With this understanding, in my attempt to persist an object between startActivityForResult() I put the object in a Headless Fragment like this
private HeadlessFragment modelFragment;
modelFragment = (HeadlessFragment)
getSupportFragmentManager().findFragmentByTag(Constants.HEADLESS_FRAGMENT_TAG);
if (modelFragment == null){
modelFragment = new HeadlessFragment();
}
modelFragment.setInvoice(invoice);
I can confirm that the custom object was set, however when I go to the next activity and try to get the same object by calling findFragmentByTag with same tag the object is null.
Does a Headless Fragment survive between two Activities life cycle? I did set setRetainInstance(true) on that Headless Fragment. I was hoping that I will not have to implement Parceable on my custom object.
For some reason my understanding was that a headless Fragment lives for the duration of your application.
No. Fragments are owned by activities and are not application-wide constructs.
I can confirm that the custom object was set, however when I go to the next activity and try to get the same object by calling findFragmentByTag with same tag the object is null.
There are at least two reasons for this:
First, at least in the code that you are showing, you never add the fragment to the FragmentManager via a FragmentTransaction. As such, the activity that created the fragment will not be able to find the fragment via findFragmentByTag(), because the FragmentManager does not know about it.
Second, each activity has its own FragmentManager, and fragments from one activity are not accessible in another activity.
I was hoping that I will not have to implement Parceable on my custom object.
Then don't pass the object. Pass the information (e.g., a key or ID) by which the other activity can retrieve the object (from a singleton POJO cache, by querying the database, etc.).
Or, do not make them separate activities, but have them as separate (regular) fragments in one activity.
Or, implement Serializable, though Parcelable executes more quickly.

What's the difference between 'this' and 'getActivity()'?

I have an idea they both get the 'context' so that functions know how they fit into the scheme of things, is this right?
Any clues for the evolving ape?
this is a reference to the current class you are. It can be an Activity, Fragment, Adapter, View, etc. And when you use it what you are doing is just passing a reference of the current object of that class.
Let's say you are working on a custom View. Anywhere in the code of that view where you call this will be interpreted as the View itself, so the value of this changes depending on what class you are.
The method getActivity() is defined only in the Fragment class and any other class extending Fragment and this method returns and Object of the type Activity.
On Android development is very common mixing those two because most of the applications code is in Activity classes, and calling this on an Activity class will return an Activity object but as you can see they are not the same thing.
You can read more here

Android : Accessing container activity object from fragment using putExtra?

I am building a tab interface using Action bar and fragment. I would need assistance in sending data from container activity to the fragment.
To elaborate, I have job object in container activty. And I have created few tabs based on the information in job object (like company details, experience details etc). I need to pass the job object to these fragments so that it can display respective information.
I have created container activity and tab fragments. I would need an example on how to pass the object across them. I cannot use intent.putExtra. Can I access parent container's object from fragment?
Any help shall be appreciated.
Thanks.
Make the method in your activity, e.g getJob that will return the Job object and its information
MyActivity extends Activity{
Job mJob;
public Job getJob(){
return this.mJob;
}
}
then in your Fragment you do this:
MyFragment extends Fragment{
#Override
public void onActivityCreated(){
super.onActivityCreated();
((MyActivity)this.getActivity()).getJob();
}
}
use getActivity and the method getJob(); to get the object
There are multiple ways of achieving this.
Make a static variable to hold your data and access that data from inside the fragments - this is the most fast but it creates bad design patterns if used improperly.
A way of Fragment-to-Fragment communication possible through the parent Activity is posted here: http://developer.android.com/training/basics/fragments/communicating.html You can use the sample code to just do a Activity - Fragment data send.
The top voted answer here: Accessing instance of the parent activity? mentions a way to avoid using static data (1.) and contains source code examples using ActivityGroup
"If you need access to some values in your First activity without
making a static reference to it, you could consider putting your
activities in an ActivityGroup."
What you choose is your preference, these are just a few options!
Edit: I'm not sure if number 3 will work with fragments since I haven't tested a method similar to it, the example is Activity - Activity communication.

How to save lot of object in onRetainNonConfigurationInstance() in android

How do I save a lot of objects in onRetainNonConfigurationInstance() in android like textview with value and webview with value, and then return the object?
Can anybody provide an example?
Thanks
How to save lot of object in onRetainNonConfigurationInstance() in android like textview with value and webview with value .
Your example is invalid. Never pass widgets between activity instances yourself, as you will create memory leaks.
For stuff like WebView, use fragments, and call setRetainInstance(true) on the WebView-hosting fragment. Android will then handle all of the details to keep that WebView in its fragment alive and attach it to the activity created after a configuration change.
For cases where you have more than one object to return from onRetainNonConfigurationInstance(), and they will not introduce memory leaks, use a static inner class, or a java.util collection class, or something as the container for all those objects, and return the container from onRetainNonConfigurationInstance().

Categories

Resources