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()
.