I want to save the hashmap to Shared preferences.

Asked 1 years ago, Updated 1 years ago, 84 views

I'm organizing a list view on Android, but I received string values through edit text in the activity of writing, and I sent them to the main activity using the intro, and put them in the list view. And then I want to put those values in the hash map and save them through Shared Preferences to save them even when the program turns off. However, I am at a loss as to what to do because Shared preferences can only store basic types.

    String test1 = data.getStringExtra("tex1");
                String test2 = data.getStringExtra("tex2");
                String test3 = data.getExtras().getString("tex3"); // receive intents and save as strings





                arItem.add(newListViewItem(test1, test2, test3)); // add intents
                ArrayList<HashMap<String , String>> aritem_hash= new ArrayList<HashMap<String , String>>();
                for(ListViewItem item : arItem){
                    HashMap map = new HashMap();
                    map.put("Date",item.DateSrc);
                    map.put("Title",item.titleStr);
                    map.put("Local",item.LocalStr);
                    aritem_hash.add(map);

                }  //Save as hashmap

hashmap sharedpreferences

2022-09-21 20:22

1 Answers

Shouldn't we serialize the hashmap and save it, and then restore it by serializing it when reading it?

 // Save
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
  Editor editor = prefs.edit();
  try {
    editor.putString(STORED, ObjectSerializer.serialize(aritem_hash));
  } } catch (IOException e) {
    e.printStackTrace();
  }
  editor.commit();
 // Restore
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

  try {
    aritem_hash = (ArrayList<HashMap<String , String>>) ObjectSerializer.deserialize(prefs.getString(STORED, ObjectSerializer.serialize(new ArrayList<task>())));
  } } catch (IOException e) {
    e.printStackTrace();
  } } catch (ClassNotFoundException e) {
    e.printStackTrace();
  }


2022-09-21 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.