ListFragment is empty after navigating back - android

Okay, I know there is a lot of discussion according to this topic, but I couldn't find any answer.
My problem is the following:
I have an Activity with NavigationDrawer, so the Fragments are added from code. The first fragment is a ListFragment, witch reads data from an SQLite DB stored in the SD card. The data loading is kind of slow, because I load the nearest n place based on location. So I don't want to load the list every time.
Now, if the user clicks an item, a second Activity shows the details. The first strange stuff is the first activity is destroyed almost every time a leave it, witch is awful, but still I could save the state.
The discussions that I rad so far indicated that the Activity should retain the last displayed Activity, and it kind of does, because if I change the content of the first activity from the Drawer before navigation the correct Fragment is created.
The problem is that even if the ListFragment is being re-used its contents will be missing (since I create a new View in the onCreateView() because of custom layout). I guess I should use the Bundle provided as a parameter in onCreateView(), but I just couldn't figure it out.
So summed up: what is the proper way of saving the items of a ListFragment, even if its parent activity is destroyed?

It turned out that I had a developer option turned on that killed all Activities that I navigate from. I didn't know that because I use my phone in Hungarian (guess it'll change from now), and for some reason they felt like they had to translate the word "Activity", making the whole option description not understandable. Sorry about that, now my first Activity is kept in the memory, so the whole issue is not present...

Related

How to wipe history on looping in Android with activities?

I have a page that list a current list. The user then clicks the floating + to add an item to this list and go through a wizard and then when they are complete, it redirects them back to the current list. I noticed that if I hit the back button, I go straight through the wizard again and back to an outdated list(instead of a current list).
I am wondering how people deal with user experience. If they land on the main page, I would simply (I think) like to just wipe the history as it is not useful at that point and more confusing than anything.
I am curious on
How to wipe the entire history
Is there other UX options that make sense to users
Check out this question and answer. Android: Clear the back stack. It will help you with your "history" (referred to as the back stack).
It should also fix your issue if the outdated list, however, I'm also questioning your method of adding an element to a list that results in an outdated list being shown when going back in the stack. If your data is properly managed, that shouldn't happen ever. To me it sounds like you are passing a list as an extra to an activity and setting a member variable in the activity class with that list. Or you have a static list somewhere and you only loop over it to create elements to display in the onCreate of the activity. Either way, it is a bad practice. The view should be notified of updates to the model. Look into the MVVM (model–view–viewmodel) design pattern or the MVP (model-view-presenter) design pattern for ideas of what this means. Ideally if you are displaying dynamic data in a list, you should be using either a list view or a recycler view both of which need to be notified of changes to update.

Android: Reduce BackStack memory usage

I'm creating an app that takes the user through a fairly long, linear, process of data capturing. Each activity leads to a new one for a new topic for which the data needs to be entered. The problem is that some of the activities have many or large bitmaps, or many imageButtons. When the user goes to the next activity, the current one is placed one the backstack and the memory does not get cleaned up.
I am considering calling 'finish()' when the user goes to the next activity and then overriding 'onBackPressed()' to recreate the previous activity if the user needs to go back and change a value there. Is there any better suggestions than to do this?
The solution you consider is certainly on the right track.
My only addition to that (recreating the activities when you need to go back to them) is that you don't necessarily need many activities.
From what I understand you need many layouts, each with its relevant resources. What I'd do is:
create your Stage data class, holing a layout, bitmap id's, etc
create a List<Stage> with the full story
create one activity that knows how to display a stage from the list, and traverse to other stages. Here you can override the back button to act as stage traversal.
Check out The Transitions Framework to see how you can animate views when traversing between the above stages. If you use the same id for at least some of your views - they will move around independently, while other views will fade out or in.

How to update controls in all tabs created using FragmentPagerAdapter?

I have created a tabbed android application using android.support.v4.view.PagerAdapter.
There are about seven tabs in the application and I plan to add more. Each tab contains a lot of controls (TextView, Spinners, Toggle buttons, Check boxes etc.)
On the first tab there is a drop down to select a profile. The user can 'Load' or 'Save' a profile he wants.
A profile contains data for all the controls in the tabs and I need to update the UI controls in all the tabs.
I have all the data loaded from the profile but the UI controls are not getting updated.
There is a 'UpdateUI' function which calls 'set' functions (setText, setChecked etc. for individual controls after finding its view by ID).
I was informed that only three tabs (Previous, Current and Next) are kept in memory so I wrote the application such that the 'UpdateUI' function is called to set UI data only when user swipes to that particular tab (figuring out the active fragment).
Using DDMS logs I saw that the data loaded was proper but the 'setText' or 'setXXXXX' function does not update the fragment tab.
I have also checked several possible issues:
Possibility of 'OnTextChanged' or an 'OnListener' updating the data again.
Made sure 'UpdateUI' is called from UI thread.
Using notify data change and redrawing UI to make sure UI is updated.
I am a novice Java/Android programmer. Please point me in the right direction.
viewpager.setOffscreenPageLimit(size);
you can instantiate all your fragments by setting limit then you can update all widgets inside other fragments.
If my understanding of Android Fragment management is right, once the fragment becomes invisible for user (say some other fragment completely overlayed it or in your case you change tabs) Fragment goes through onPause and possible onStop lifecycle stages, this mean it's kind of hybernated and can't be changed before it get's visible. viewpager.setOffsetPageLimit(size) tells the fragment manager (or rather pageAdapter) how many fragments should be kept hybernated, and I doubt it playing with this will change anything, but let me know if it's, because otherwise the solution may be more complicated.
What I'd do is recreate a fragment every time user gets to see it and pass your profile data to it's constructor (or following better practice newInstance() static method), it will in fact save memory since keeping many fragments there may be overwhelming. Alternatively you can check what profile is chosen everytime fragment is calling it's onResume, and update your controls there.

Getting data (asynchronous) and populating ViewPager's fragments

I have an activity with a ViewPager with a variable number of fragments (tabs).
Upon start the activity checks if the associated (complex) data has been loaded. If it hasn't it shows a progress bar view and starts an AsyncTask which fetches the data. Depending on the data the activity creates a number of fragments (tabs) and gives each fragment a sub set of the data.
I currently hold references to the fragments (I know that it is discouraged) and I run into all sorts of problems when the fragments gets reused - I'm giving the data to the wrong instance of the fragment.
So, is there an "android way" of solving this problem?
I run into all sorts of problems when the fragments gets reused
Fragments usually don't get reused in a ViewPager. This is not like an AdapterView where rows get recycled. Using FragmentPagerAdapter or FragmentStatePagerAdapter, a fragment represents one and only one page.
I re-instantiate the ViewPager each time (but the fragments get reused?)
Ah. That's a slightly different problem.
The stock implementations of FragmentPagerAdapter and FragmentStatePagerAdapter make a couple of assumptions:
They are in complete control over the fragments, particularly in terms of running the transactions to add and remove them from the UI
That those fragments will only ever be used by one "logical" ViewPager (IOW, recreating that ViewPager for a configuration change is fine, but that' pretty much it)
Complicating matters is that these adapters store the fragments under certain tags, and therefore if those fragments still exist in those tags, those existing ones will get used, instead of new ones being created.
So, is there an "android way" of solving this problem?
It's unclear from your question why you even need to "re-instantiate the ViewPager". I'm assuming that this is tied to some sort of refresh operation, or something else that is forcing you to go through the process described in your second paragraph.
You could give my ArrayPagerAdpater a try, as it is friendlier about external agents mucking about with the fragments. Since you control the fragments' tags, you can always be certain that you are working with the right fragment -- rather than caching them yourself, just retrieve the right one and manipulate it.

Why is my fragment onCreate being called extensively whenever I page through my applications viewPager?

I'm not quite understanding this fragment lifecycle business.
I have a pretty standard 3 page horizontal slider view Pager layout for a "view details" section of my app. I start my app on the middle page of the three. My FragmentActivity sets the page to page 1.
mPager.setCurrentItem(1); //default to center page, current data view fragment
I've been using the FragmentStatePagerAdapter because using the FragmentPagerAdapter crashed my app at times, when coming back from a suspended state for example, and this was the quickest way to work around that for now. Seems to work but I suspect the State aspect is what might be the cause of my problem here, maybe.
So at first I thought that I would have each fragment do the work of getting data from a rest service and then showing it in a list, but I'm not so sure any more.
I tried running a unique async task to fetch data in each of the fragments onCreateView events.
Then after reading more on the fragment lifecycle I switched to onCreate, having noticed that the onCreateView was being called quite heavily, which in turn made for a greedy app that too often requested data over the wire.
Switching to onCreate hasn't changed anything. OnCreate is still geting called just as much as onCreateView for the 2 adjacent fragments.
The odd thing is that the fragment that I set to be the first one to display in Fragment Activity only gets the onCreate called the one time.
Something doesn't feel right here.
Right now I'm thinking that I should have the parent fragment activity declare and call all the async tasks to fetch the data that I need to display in the fragments.
Set the results of the async calls in an object owned by the parent fragment activity and then have the fragments use the object contained by the parent to create the list view etc.
But what if the async tasks started by the parent activity don't finish before each fragments onCreateView is called and the object contained by the parent isn't ready yet.....
signed, confused and frustrated
ViewPager is quite zealous in shutting down things it isn't currently using, and this is exactly what is happening here. The default behaviour is for ViewPager to "keep around" one page either side of the page being viewed, and destroy the rest. Hence in your 3-page view, page 3 gets destroyed when selecting page 1, then when page 2 is reselected page 3 is recreated. As you've noticed, page 2 only has onCreate(..) called once because it is always adjacent to, or is, the currently selected page.
To solve this, simply set ViewPager.setOffscreenPageLimit(2). Then the ViewPager will keep all your Fragments. Obviously this isn't a good idea for a large number of Fragments, but for your case it should be fine.
#Espiandev's solution will work for your current case, but you're right that your state is the issue. You should use the setArgument and/or onSaveInstanceState methods to save your Fragment's state (which shouldn't be too hard, since e.g., a response from the server can usually be represented as a String), and then use getArgument and/or the Bundle passed in onCreate to restore it.
Alternatively, you could have your Activity do the server fetches, and then call setArgument for each of your fragments, and check the arguments inside your Fragment to determine if your data has arrived yet (and if not, potentially display a loading state of some kind).
If you care at all about screen orientation change, this related question will also be useful to you.

Categories

Resources