Search code examples
javaandroidandroid-recyclerviewsharedpreferences

Save Arraylist into sharedpreferences in one activity and load it in recyclerview in another activity


I'm a newbie to Android Dev and trying to build an app where user buys a product and details such as Name, Price, Purchase date etc are to be reflected on the Orders Page once the user clicks on "Yes" button and order is placed.

I'm trying to store each order's variable into ArrayList in first activity and bind/show the ArrayList into recyclerview in second activity. But when I'm trying the below code its only showing one item in recyclerview which is the last purchase.

Function to save ArrayList in SharedPrefernces:-

private void saveData() {
    SharedPreferences sharedPreferences = getSharedPreferences("orders",MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    orderlist.add(new ModelClass(name,date,price));
    String json = gson.toJson(orderlist);
    editor.putString("tasklist",json);
    editor.apply();
}

Function in Orders Page(RecyclerView) Activity to load Data :-

private void loadData(){
    SharedPreferences sharedPreferences = getSharedPreferences("orders",MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString("tasklist",null);
    Type type = new TypeToken<ArrayList<ModelClass>>(){}.getType();
    orderlist = gson.fromJson(json,type);

}

Thankyou in Advance


Solution

  • While saving tasks you need to keep the existing list try this -

    private void saveData() {
        SharedPreferences sharedPreferences = getSharedPreferences("orders",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        // fetch existing list
        String json = sharedPreferences.getString("tasklist",null);
        Type type = new TypeToken<ArrayList<ModelClass>>(){}.getType();
        orderlist = gson.fromJson(json,type);
        // add newest item in old list
        orderlist.add(new ModelClass(name,date,price));
        String json = gson.toJson(orderlist);
        editor.putString("tasklist",json);
        editor.apply();
    }