I have a fragment
X which indeed has a RecyclerView
, X has a search view, I use the search view to search something and filter the RecyclerView
into few rows. After the filtering, if user clicks on some row, it goes to another fragment
say Y. From there if the user clicks back it comes back to X. My task is that X should persist the search results after this coming back. What is the best approach to achieve this?

- 1,605
- 1
- 14
- 24

- 3,383
- 6
- 44
- 72
-
post your code here. – Quick learner Sep 08 '17 at 12:07
2 Answers
Propertly override onSaveInstanceState
in Fragment
so that it will store search input - filter. Also override onCreate
in such way it will apply saved filter on your RecyclerView
.
Before navigating to another fragment, obtain Fragment.SavedState
via FragmentManager
and save it temporary in Activity
which hosts your fragments. Note, this state can be lost if you do not properly save Activity state due of configuration changes (rotate) = you have to override also onSaveInstanceState
in Activity
. Or simply save Fragment.SavedState
in global scope (some static field, or in Application
).
When navigating back to previous fragment, re-create fragment from Fragment.SavedState
i. e. invoke Fragment#setInitialSavedState(Fragment.SavedState)
.
For more details see my research on similar topic.

- 2,479
- 21
- 39
You can use a the singleton pattern to store the data!
E.g.
// DataManager.java
public class DataManager {
private static DataManager thisInstance;
// Declare instance variables
List<String> searchResultItems;
public static DataManager getSharedInstance() {
if (thisInstance == null) {
thisInstance = new DataManager();
}
return thisInstance;
}
private DataManager() {
searchResultItems = new ArrayList<>();
}
public List<String> getSearchResultItems() {
return searchResultItems;
}
public void setSearchResultItems(List<String> searchResultItems) {
this.searchResultItems = searchResultItems;
}
}
Now you can store and retrive data from everywhere:
// Setter
DataManager.getSharedInstance().setSearchResultItems(items);
// Getter
List<String> items= DataManager.getSharedInstance().getSearchResultItems();

- 120
- 11