0

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);
}

1 Answers1

0

After some try, I found out how to update the RecyclerView. In my MainActivity I override the onResume() method and I make execute this method:

@Override
protected void onResume() {
    super.onResume();
    UpdateDataSource();
}

And this is the UpdateDataSource() method :

private void UpdateDataSource() {
    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();
    //Save the new list retrieved from the SharedPref into a temporary ArrayList
    ArrayList<TravelCard> temp = gson.fromJson(json, type);
    //I copy the new list into my main list
    travelCards = temp;
    //I set the new list in the RecyclerView Adapter
    mAdapter.setTravelCards(temp);
    //Notify the adapter that  the data set has been changed
    mAdapter.notifyDataSetChanged();
}