添加新元素后刷新RecyclerView-Android

时间:2018-07-25 17:31:00

标签: java android android-recyclerview

在我的MainActivity中,我有一个RecyclerView和一个Button。 单击该按钮后,将启动一个新活动,其中需要填写表格。用户填写完所有字段后,必须按下按钮以保存新元素。如果一切正确,则将用户重定向到另一个Activity,而在后台将新元素添加到对象列表中,并用Shared Preferences保存。 回到MainActivity后,如何获得新元素? 我试图通过覆盖onResume方法来检索新列表,但是没有成功。 预先感谢

编辑:

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 个答案:

答案 0 :(得分:0)

经过一番尝试,我发现了如何更新RecyclerView。 在我的MainActivity中,我重写了onResume()方法,并执行了该方法:

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

这是UpdateDataSource()方法:

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