0

I have an Activity where I load fragments in a FrameLayout in the activity layout xml. I have 2 fragments: ListFragment and PreferenceFragment.

ListFragment uses an ArrayAdapter and displays an array which is a class variable and populated in the constructor of the ArrayAdapter. This contains dates which are stored in the database.

Now when the user clicks on preferences button in the ActionBar, the ListFragment is replaced by the PreferenceFragment. Here I allow the user to change the date format.

So far so good.

Now when the user presses back to go back from the PreferenceFragment, I override the Activity.onBackPressed() to replace the PreferenceFragment with the ListFragment.

Here I still see the dates with the old format, and the user's chosen setting is not reflected. Upon debugging, I saw that the ListFragment.onCreateView() is called twice. The first time it loads the newly loaded array with the new date format that the user just chose. The second time it loads the old date array (which somehow it saved!).

I am only using FragmentTransaction.replace() in the Activity.onCreate() and in the Activity.onBackPressed().

I have spend the whole day to figure this out. As per this, this shouldn't be happening since I am using replace. I am unable to find anything online. Any suggestions are appreciated.

UPDATE: As per this, the ArrayAdapter.onNotifyDatasetChanged() only takes effect when the list is updated using the Arrayadpaters own add, clear ,etc methods. So now in the ListFragment.onResume() I call adapter.clear() and adapter.addAll(sqliteclass.getArray()). This works, but I am now making 2 trips to the database, in onCreate() and onResume().

Community
  • 1
  • 1
rgamber
  • 5,749
  • 10
  • 55
  • 99

1 Answers1

0
  1. There is no need to override onBackPress() to reverse a FragmentTransaction.
    Just call addToBackStack() on the FragmentTransaction replacing the list with the preferences.
  2. Try calling notifyDataSetChanged() on the ListAdapter in onResume() of your ListFragment. This should force a recreate of the items' views.
flx
  • 14,146
  • 11
  • 55
  • 70
  • This does not help. Somehow, the old format still gets displayed! http://stackoverflow.com/questions/3219779/android-what-does-adapter-notifydatasetinvalidated-do says that the `notifyDataSetInvalidated()` does not do anything.. – rgamber Feb 23 '14 at 09:02
  • sorry, `notifyDataSetChanged()` was what I wanted to suggest. – flx Feb 23 '14 at 09:04
  • Still the same :(... Not sure whats wrong. Let me know if you anymore suggestions! Thanks for your time. – rgamber Feb 23 '14 at 09:15