ASyncTask, hidden fragments, retaining instances, and screen orientation changes - android

My setup is as follows.
I have a FragmentPagerAdapter called from my Activity which loads two fragments. This is setup within onCreate.
In onResume I call an ASyncTask which loads data from a database, and then calls a callback in my activity onLoadComplete via a load data listener.
#Override
public void onLoadComplete(JSONArray data) {
// TODO Auto-generated method stub
LocalFragment fragmentB = (LocalFragment)getSupportFragmentManager().findFragmentByTag(ListTag);
fragmentB.setList(data);
LMapFragment fragmentA = (LMapFragment)getSupportFragmentManager().findFragmentByTag(MapTag);
GoogleMap our_map = fragmentA.getMap();
fragmentA.plotP(myLocation,data);
}
The fragments are initialized by the Pager, and within each fragments code I set the respective tag e.g in LocalFragment
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
String myTag = getTag();
((PagerTest) activity).setListTag(myTag);
Log.d("what",myTag);
}
This allows me to access the fragment, call a function within it which populates a list or populates a map. It works.
What I am now trying to do is account for screen orientation changes.. If while the ASyncTask is running the orientation is changed, the app crashes.
As suggested here: Hidden Fragments I have been trying to implement a hidden fragment which saves the state of my ASyncTask. So what I have done is set it up so in onResume of my Activity i call a function
static LoadDataFromURL the_data = null;
static JSONArray pub_data = null;
private static final String TAG = "RetainFragment";
public RetainFragment() {}
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new RetainFragment();
fm.beginTransaction().add(fragment, TAG).commit(); // add this
}
return fragment;
}
which essentially saves my data.
Basically what this means is that if i rotate my screen i dont call my ASyncTask again.. the screen just rotates.. it works perfectly.
If however I go back to the main menu and then click on the activity again the screen returns blank (but does not crash). My understanding is that the data is retained as an object in the fragment, but on reloading the activity afresh the data needs to be set again.. I.E onLoadComplete needs to be called to populate the list/map..
So i concluded that if initially after the ASyncTask completes i save the returned data in my hidden fragment onRetainInstance, then i could simply call onLoadComplete and pass it..
The problem is, in this situation seemingly the fragment has not been called yet, as such the tags are null, and calling the callbacks within onLoadComplete crashes the app.
I have been banging my head over this for ages.
My ASyncTask is in a seperate class: LoadDataFromURL
What i want to achieve is as follows - a fragmentviewpager whereby on screen rotate the ASyncTask is retained on rotate/attached to the new activity, and if it has completed before it shouldn't be run again..
Could anyone advise.
Many Thanks
EDIT
Having changed the variables in my secret fragment to public variables, everything has seemingly come together.. BUT because im not 100% sure how/when things are called, I dont fully understand WHY it works..
So.. I call findOrCreateRetainFragment and it either creates a new 'secret' fragment or returns the current instance.
If it is returning a current instance, i dont call my async task again. If it is not, I call my asynctask and load the data.
With this setup, when i load the activity and rotate the screen, it rotates as expected woop.
Now, when i go back to the main menu and then click the activity again, it calls the async task.
My understanding is that on rotate the async task is not called again, and the viewpager is somehow saving the fragments.
On the other hand, when i go back my activity is destroyed, as is my secret fragment, and as such when i click on it again it loads the data. THis is essentially what i want..
Have i understood this correctly?
Thanks

There are a few issues here that you're experiencing (I think).
First of all, the reason your callbacks crash is because they're attached to an old Activity that no longer "exists" after a screen orientation and/or Activity push. If you use onAttach() to attach a callback to your fragment, you must use onDetach() to detach that callback when the Fragment is removed from the Activity. Then, whenever you call the callback, check for a null so you don't send data to a dead object.
Basically, the logic you're trying to use here is:
Start Activity.
Check if your Fragment exists. If it does, grab it. Else, create it.
Retrieve the data if it exists. If not, wait for the callback.
Because of the nature of callbacks (depending on your implementation), you will not receive data until the event fires. However, if the Activity is gone and the event has already fired, the callback won't execute. Thus, you have to retrieve the data manually. When using setRetainInstance(), it's helpful to think of it as this entity detatched from your Activity. It will exist as long as you don't pop the current Activity or push a new Activity. However, your current Activity will be destroyed upon screen orientation changes while the Fragment won't. As such, the Fragment shouldn't rely on the existence of the Activity.
A much more elegant solution to the problem that you may want to look in to is implementing the Android Loader API. Loaders are handy tools that are handled by the system that work is roughly the same way but are more in-tune with asynchronously retrieving data. They work effectively the same way. You simply start your loader and the system with either create one if it doesn't exist or re-use one that already exists. It will remain in the system by the LoaderManager upon configuration changes.
EDIT:
To answer your edit, I guess I'll explain what's happening. It's convoluted, so just tell me if anything needs clarification.
Fragments aren't technically speaking part of your currently running Activity. When you create an instance of the Fragment, you have to call beginTransation() and commit() on the FragmentManager. The FragmentManager is a singleton that exists within the realm of your application. The FragmentManager holds on to the instance of the Fragment for you. The FragmentManager then attaches the Fragment to your Activity (see onAttach()). The Fragment then exists within the FragmentManager which is why you never really have to hold a reference to it within your application. You can just call findFragmentByTag/Id() to retrieve it.
Under normal circumstances, when your Activity is being destroyed, the FragmentManager will detach the instance of your Fragment (see onDetach()) and just let it go. The Java garbage collect will detect that no reference to your Fragment exists and will clean it up.
When you call setRetainInstace(), you're telling the FragmentManager to hold on to it. Thus, when your Activity is being destroyed on a configuration change, the FragmentManager will hold on to the reference of your Fragment. Thus when your Activity is rebuilt, you can call findFragmentByTag/Id() to retrieve the last instance. So long as it didn't keep any context of the last Activity, there shouldn't be any problems.
Traditionally, one would use it to keep references to long standing data (as you are) or to keep connection sockets open so a phone flip doesn't delete it.
Your ViewPager has nothing to do with this. How it retrieves the Fragments is completely dependent on how you implement that Adapter that it's attached to. Usually, retained Fragments don't have Views themselves because Views hold Context data of the Activity they were created in. You would just basically want to make it a data bucket to hold on to the data for the Views to pull from when they're being inflated.

Related

Android Fragment isAdded returns false and getActivity is null after posting thread in the onResume method

So i am using Navigation in my main activity of my app and i have a fragment which is my start navigation fragment.
In this fragment, after it is created, in my presenter i post a thread to fetch data from the network.
After data have been fetched, i am using the main thread to show the data to my screen.
The first time that the app runs, this is working fine.
However if user opens the drawer and selects again THIS fragment and not another one, fragment is recreated again meaning that it gets destroyed and created from scratch as Navigation Component is designed to do.
However this time, when my presenter posts thread fetching-data-thread and this gets finished and sends the results to the UI, fragment's isAdded() method returns false as well as getActivity is null.
Having that, means that i can't use the Activity Context (getActivity() is null or requireActivity() throws an illegal state exception) and consequently i cannot load images etc since i don't have the context available.
I highlight that this happens when user opens the drawer while this fragment is visible and selects again to navigate to this fragment from the drawer. In case that user navigates to another fragment and then presses the back button everything is ok.
Any idea how to handle this problem?
Fragments are meant to be destroyed, as well as activities.
You can never rely on android framework component lifecycle state, and because of it android architecture components were made. ViewModel, for example, can outlive it's host fragment.
But - viewmodel/presenter/controller is not a right place to perform network request and handle app logic, just because it's not their job (SOLID's S-single responsibility).
There is official guide to app architecture. Simply speaking, you have a layer for android-related code, where you update UI, layer for handling app logic (which is java/kotlin and android framework independent) and layer for requesting/holding data.
So, during creation of your ui class you obtain viewmodel, which has reference to class that handle logic and exposes result to render in ui. Inner layers are persisted - view is not.
So, after testing and searching i found out the origin of the problem i described above.
I am nullifying my presenter's view in onDestroy/onDetach method of my Fragment.
However when the replacement Fragment gets created, this new Fragment is firstly attached to the calling Activity and then, the old one gets destroyed.
Having in mind, that i inject my presenter into the Fragment instance, my presenter will be never null at the time that new Fragment gets attached and consequently, and considering that i create a new instance of my Presenter when it is null, the presenter instance that is being injected into the fragment is not aware of the new 'View' object.
As a result, when the results reach the UI thread through the callback this view object is 'not Added'.

In which situation we want to add fragment without container?

Fragment transaction has method add(Fragment fragment, String tag), which does not place fragment to container, so it cannot have view. For what it can be used?
From the Android Documentation:
However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.
How about this purpose ?
Simple example: an Activity starts an AsyncTask, but when device rotated activity restarts, causing AsyncTask to lose connection with the UI Thread. But this Activity can hold a Fragment (invisible, with no UI at all) that can handle all the AsyncTask work. When Activity recreated the Android OS takes care reattaching the Fragment, thus no data loss will occur.
For Dialogs you don't have any container on normal app layer. It is directly added on Window with WindowManager(See WindowManager.LayoutParams for various types of layers).
DialogFragment has an API like DialogFragment.html#show(android.app.FragmentManager, java.lang.String) which corresponds to this.
You can use fragments without UI (container) as a background worker (one benefit is that you can retain it during rotations etc) and for retaining data during rotations and other changes.
Reading http://developer.android.com/guide/components/fragments.html is strongly recommended.
Example of instance retaining: https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/app/FragmentRetainInstance.java
Also, here are similar questions (so this questions seems to be a duplicated but cannot be flagged due to bounty):
What is the use case for a Fragment with no UI?
Android non-UI Fragment usage
As #Lucius Hipan mentions, it can be used to prevent data loss.
Almost always this king of fragments are used as Retained container ( setRetainInstance(true) called in onCreate method), then after device configuration changes (e.g. orientation changing) fragment will not be recreated but remembers previous state.
It's recommended way to use asynctask.
Here is an example:
There is login activity. The user enters their credentials and presses the Login button. After that configuration change occurs (user rotates phone). So, network task was completed, but your handlers was not listening for it now. If you show any login animation, it can be stored via savedInstance, but listeners not. And instead of creating service you can simply create new retained fragment with persistant asynctask and interface to communicate with activity.
This method is a good compromise for small projects where using bus libraries is overstatement.
By calling the method add(Fragment fragment, String tag) internally calls add(int containerId, Fragment fragment, String tag) with a 0 containerId.That will be add(0, fragment, tag).
If 0 is supplied as containerId, it will not be placed the fragment in a container.

Fragmentation, onRestart(), and Null Pointers -- What am I doing wrong?

I have 3 fragments that are contained within the main activity via a ViewPager. What I'm trying to do is allow myself to call methods on objects of those fragment classes from different lifecycle callbacks in the main activity, namely onRestart(), so that I can refresh their content via a backend call. To be more specific, one of the fragments contains a "live feed" of images that people are posting, and the user gets to this posting activity via one of the fragments.
Right now, the problem I'm trying to solve is that when a user goes to this posting activity and puts up a picture, the live feed in the fragment they come back to isn't getting refreshed. To do this, I would need to call my backend and UI update methods in that fragment from the main activity's onRestart().
But I'm running into these null pointer exceptions -- here's what the code looks like in the fragment:
public void refreshUI(){
activity = getActivity();
appContext = ThisApp.appContext();
view = getView();
peopleHeader = (TextView) view.findViewById(R.id.people_header);
peopleLinearLayout = (LinearLayout) view.findViewById(R.id.local_people_linearlayout);
..... (various other instantiations)... }
The NPEs are coming either from getActivity() or some of the UI instantiations. I call this code from onActivityCreated() and it works as expected. However, if I try to call this code again on my fragment object from onRestart(), I crash.
What's happening? Can't figure out why this would go bad on me.
Thanks so much.
When your Activity is destroyed and recreated, your Fragments are also destroyed and recreated with it. You can have a look at the Fragment/Activity lifecycle explanation here.
What this means is that the reference you keep disappears, the Fragment is there but it is another object. You need to get a reference to this new object.
You can check this answer on how to do that. It explains getting references to Fragments created by a ViewPager adapter.

Saving state on List Data when App Resumes

Here is my set up.
I have a Main SherlockFragmentActivity. It swaps many ListFragments back and forth with FragmentTransaction's. To indicate loading, anytime a ListFragment loads the data I call:
setSupportProgressBarIndeterminateVisibility(true);
The problem:
When the main Activity mentioned above first starts, or the user leaves and goes to other apps and then restarts this one after an extended period of time, the SherlockFragmentActivity seemingly reloads, there is no progress dialog in the ActionBar, the screen is white for a few seconds, and then the list data repairs (The length depends on the data connection).
Here is some supplemental code: When the main/base Activity first loads, this is one of the first things I do in the onCreate():
// Set up Main Screen
FragmentTransaction t2 = this.getSupportFragmentManager().beginTransaction();
SherlockListFragment mainFrag = new FollowingFragment();
t2.replace(R.id.main_frag, mainFrag);
t2.commit();
FollowingFragment is the one that will always load in this instance. It contains a ListView and an AsyncTask pulling data from a MySQL database.
My question: How do I prevent this delay? And how do I handle maintaining the data when user leaves for extended periods of time?
This is the normal behavior, it happens because your activity has been killed to save memory for other apps, when your app was in the background. And when it comes back to the foreground, the system recreate your activity, which will recreate your fragment.
But if your really want to avoid recreating your fragment, you can use setRetainInstance in your fragment's onCreate method:
public void setRetainInstance (boolean retain)
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:
onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
onCreate(Bundle) will not be called since the fragment is not being re-created.
onAttach(Activity) and onActivityCreated(Bundle) will still be called.
And use something like this in your FragmentActivity's onActivityCreated method:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getFragmentManager();
// Check to see if we have retained the worker fragment.
mRetainableFragment = (RetainedFragment)fm.findFragmentByTag("fragmentTag");
// If not retained (or first time running), we need to create it.
if (mRetainableFragment == null) {
mRetainableFragment = new RetainedFragment();
// Tell it who it is working with.
mRetainableFragment.setTargetFragment(this, 0);
fm.beginTransaction().add(mRetainableFragment, "fragmentTag").commit();
}
}
But be aware that, this should only be use for headless fragment (fragment without UI, i.e return null in onCreateView, aka worker fragment). You can still use this method for UI fragment though but it is not recommanded by google, in that case the data must be stored as member (field) in your activity. If the data which should be stored is supported by the Bundle class, you can use the onSaveInstanceState() method to place the data in the Bundle, and retrieve that data in the onActivityCreated() method.
Moreover this only works if the fragments is not added to the backstack.
According to the Android developer reference page on Activity, you have to request the progress bar feature before calling setSupportProgressBarIndeterminateVisibility():
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
setSupportProgressBarIndeterminateVisibility(true);
The other issue, reloading the fragments, is due to Android killing your ListFragment so that they have to reload could be resolved by overriding onSaveInstanceState(Bundle outState) and caching your data there to be retrieved in your ListFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(savedInstanceState != null) {
// retrieve data from Bundle here
} else {
// no data, we need to reload from network
}
// initialize your View here
}
This method is not guaranteed to run all the time, however (it's not in the Fragment lifecycle). As such, you should also make sure you cache the data in onPause() and use it instead of always loading from a network connection.
#Override
public void onPause() {
super.onPause();
SharedPreferences prefs = getActivity().getSharedPreferences();
SharedPreferences.Editor editor = prefs.edit();
// put your data here using editor
editor.commit();
}
Then you can load this data in your onCreateView() by retrieving an instance of SharedPreferences and using prefs.getString(String key) and other methods.
When your app get killed, you lose your activity state and data! There are two scenarios that I can assume about your AsyncTask:
1. you are pulling some data from a Webserver. In this case I personally think caching your data which you retrieved from webserver is a better solution than implementing serializable.
2. You are pulling lots of data from local database (which causes retrieving data to take some time). In this scenario I suggest retrieving only as much data as you need, not more! (for example you can retrieve 20 items, and when user scrolling to the end of ListView retrieve next 20 items).
This solution helps your application retrieve data faster.
PS: To give you a clue how to implement the WebserviceModule with cache capability, which I assume is located in your AsyncTask, you can save every response from webserver in the SDCard and every time you trying to retrieve some resource from webserver, you should check the SDCard to see if your request already sent and cached! For every request, your should make a unique signature base on url and post parameters to recognize cached files.
When you return to activity after extending period of time, the whole app being restarted. So You can't rely on object variables to save data.
So You could avoid delay You've mentioned with saving data to some local storage in activity onStop() method. For example, shared preferences.
And when You call onCreate(), check whether You have data saved and use it if exists (and clean up to have "clean" start next time), otherwise start asynctask.

Restoring Fragment Instance with references

Short version: I would like to know how i can recreate a fragment state (e.g. after screen-rotation) when this fragment contains a reference to an object that cannot be serialized or duplicated and needs to stay in memory.
Long version:
In my app i use a ViewPager connected to a custom FragmentPagerAdapter that instantiates a number of fragments which display data (a schedule) contained in a ListView. All this is contained inside a parent fragment. When instantiated by the adapter, each page fragments is passed a reference to one single object (the "ScheduleManager") that does several things:
Contains the data to be displayed
Holds a reference to a Context object (in order to access SharedPreferences)
Holds a reference to the parent fragments LoaderManager so it can reload the data
Implements OnClick- and ActionMode callback listeners (to be able to create and handle an action mode that works across all pages; Page Fragments add the object as a listener to their ListViews)
Defines a callback interface to notify listeners of state changes or when data is reloaded (Page Fragments register themselves as listeners).
Essentially, the ScheduleManager holds everything together and implements the main logic of this ("schedule") part of my app, i.e. loading and providing the data, and the means to modify and relaod it via an ActionMode. I don't know whether this is good design...
My question is how am I supposed restore the Fragments instance state under these circumstances? I cannot serialize the ScheduleManager to a bundle, since it would loose its references to the Context and the LoaderManager (otherwide, of course I would use setArguments / getArguments). Also, all the page fragments must have a reference to the same instance of the ScheduleManager, otherwise the shared action mode won't work. Aside from that I don't want to duplicate the entire schedule data each time a fragment is restored. I want to keep this object in memory and let the page fragments reclaim a reference to it when they are restored.
I guess I could let the containing activity hold the ScheduleManager and have the PageFragment query it for a reference. But I would prefer to keep the everything inside the parent fragment self-contained and modular if this is possible (there can be different schedules for different items). While writing this though I get the feeling there will be no way around this.
Of course, when the parent fragment is recreated it can also recreate the ScheduleManager and feed to it the references it needs (Context + LoaderManager). The problem is there can be no more than one instance of ScheduleManager for each instance of the parent fragment, so how to make the nested page fragments reconnect to it.
Here is what I ended up doing:
public void onCreate(Bundle savedInstanceState)
{
Fragment fragment = this.getActivity().getFragmentManager().findFragmentByTag("SCHEDULE");
if (fragment instanceof ScheduleMasterFragment)
{
ScheduleMasterFragment master = (ScheduleMasterFragment) fragment;
this.scheduleManager = master.getScheduleManager();
}
else
{
throw new RuntimeException("SchedulePageFragment must be " +
"the child of a ScheduleMasterFragment with Tag set to 'schedule'");
}
super.onCreate(savedInstanceState);
}
The ScheduleManager is the reference I wanted to keep. At least this way I keep all the code inside the fragment itself, except for getScheduleManager in ScheduleMasterFragment which makes sense because the ScheduleMasterFragment somehow is the owner of the ScheduleManager instance.
Any better solutions are still welcome...

Categories

Resources