0

I have wrote a little code to save new just added items to sharedpreferences. But if I retrieve the sharedpreferences in an arraylist it displays {"todo":"new item" } but I only want to display one item and only the text if you understand me. Here is my save Arraylist code:

public void saveArrayList(Context context ,ArrayList<DayItems> mlist){
    SharedPreferences shared;
    SharedPreferences.Editor editor;

    shared = context.getSharedPreferences("MONDAY", Context.MODE_PRIVATE);
    editor = shared.edit();

    Gson gson = new Gson();
    String json = gson.toJson(mlist);
    editor.putString("mondAy", json);
    String getSaved = shared.getString("mondAy", null);
    Toast.makeText(PlannerActivity.this, getSaved, Toast.LENGTH_LONG).show();
    editor.commit();
}

Here is my add item to arraylist:

@Override
                                public void onClick(View v) {
                                    String afspraak = addTEXT.getText().toString().trim();
                                    if(afspraak.length()>0){
                                        addTEXT.setText("");
                                        mon.add(new DayItems(afspraak));
                                        dayAdapter.notifyDataSetChanged();
                                        //save arraylist with new item
                                        saveArrayList(context, mon);
                                    }

                                }
                            });

Actually what I want is a snippet to retrieve SharedPreferences. Thanks in Advance!

2 Answers 2

1

You can try this to retrieve from SharedPreferences

    List<DayItems> listDayItems = gson.fromJson(shared.getString("mondAy", null), new TypeToken<List<DayItems>>() {
        }.getType());
Sign up to request clarification or add additional context in comments.

Comments

0

It's definitely works with your condition:

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();

String json = sharedPrefs.getString(TAG, null);

Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();

ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);

2 Comments

Thank you for your answer! I will definitely try this one out!
Thanks @svenvdz to fast Response as we gave you to reply your post. Thanks Again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.