In my MainActivity
I have a RecyclerView
and a Button
.
When the button is clicked, a new activity is launched in which there's a form to fill. After the user finish to fill the all fields, it has to be pressed a button to save the new element. If everything is correct, the user is redirect to another Activity while in background the new element is added to the list of object and saved with Shared Preferences
.
When I get back to the MainActivity
how can I get the new elements?
I tried to retrive the new list by overriding the onResume
method, but it did not work out.
Thanks in advance
EDIT :
MainActivity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//GET: data source for the array list
SetDataSource();
if (travelCards == null) {
travelCards = new ArrayList<>();
}
//...
}
@Override
protected void onPause() {
super.onPause();
SaveDataSource();
}
private void SaveDataSource() {
SharedPreferences sharedPreferences = getSharedPreferences(DataKey.DATA_SOURCE, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(travelCards);
editor.putString(DataKey.SHARED_PREF_CARD_LIST, json);
editor.apply();
}
private void SetDataSource() {
SharedPreferences sharedPreferences = getSharedPreferences(DataKey.DATA_SOURCE, MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(DataKey.SHARED_PREF_CARD_LIST, null);
Type type = new TypeToken<ArrayList<TravelCard>>() {
}.getType();
travelCards = gson.fromJson(json, type);
}