How to use SharedPreferences to save more than one values?

前端 未结 6 1575
慢半拍i
慢半拍i 2020-11-29 08:03

I am developing a dictionary app. In my app, I assume that user wants to save favourite words. I have decided to use SharedPreferences to save these values

6条回答
  •  心在旅途
    2020-11-29 08:12

    You could use a TreeMap (or other type of list which implements Serializable). Here's how I handled a list of favourites recently. In the TreeMap, Favourite is a class I use. In your case, you could just use TreeMap instead.

    private static TreeMap favourites;
    
    ...
    ...
    ...
    
    // load favourites
    FileInputStream fis=null;
    ObjectInputStream ois = null;
    try {
        fis = context.openFileInput(context.getString(R.string.favourites_file));
        try {
        ois = new ObjectInputStream(fis);
        favourites = (TreeMap) ois.readObject();
        } catch (StreamCorruptedException e) {
        } catch (IOException e) {
        } catch (ClassNotFoundException e) {
        }
    } catch (FileNotFoundException e) {
    } finally {
        try {
        if (ois!=null){
            ois.close();
        }
        } catch (IOException e) {
        }    
    }
    
    if (favourites==null){
        favourites = new TreeMap();     
    }
    
    ...
    ...
    ...
    
    // save favourites
    FileOutputStream fos=null;
    ObjectOutputStream oos=null;
    try {
        fos = context.openFileOutput(context.getString(R.string.favourites_file), MODE_PRIVATE);
        try {
        oos = new ObjectOutputStream(fos);
        oos.writeObject(favourites);
        } catch (IOException e) {
        }
    } catch (FileNotFoundException e) {
    } finally {
        if (oos!=null){
        try {
            oos.close();
        } catch (Exception e2) {
    
        }
        }    
    }
    

    You can also avoid the "::" thing you're doing to separate values.

    Hope that helps...

提交回复
热议问题