简体   繁体   中英

Android Shared preferences - Array list of class

I have Player class which has a name and a arraylist of scores. Scores gets added dynamically with a button. I want to use shared preferences to save the Arraylist<Player> players which I created in my main activity. I have tried a couple of solutions with no success.

What I tried so far:

Links: Save ArrayList to SharedPreferences

When I used ObjectSerializer class I cant import package org.apache.pig.impl.util; and this causes to get errors such as :

在此处输入图片说明

because WrappedIOException is in that package.

Tinydb : Tiny db seemed liked a good solution but I get error when I retrive my data. These are the methods I changed from the java file:

    public void putListObject(String key, ArrayList<Player> playerArray){
        checkForNullKey(key);
        Gson gson = new Gson();
        ArrayList<String> playerStrings = new ArrayList<String>();
        for(Player player : playerArray){
            playerStrings.add(gson.toJson(player));
        }
        putListString(key, playerStrings);
    }

    public ArrayList<Player> getListObject(String key, Class<?> mClass) {
        Gson gson = new Gson();

        ArrayList<String> objStrings = getListString(key);
        ArrayList<Player> objects = new ArrayList<Player>();

        for (String jObjString : objStrings) {
            Object value = gson.fromJson(jObjString, mClass);
            objects.add((Player) value);
        }
        return objects;
    }

public void putListObject(String key, ArrayList<Player> playerArray){
    checkForNullKey(key);
    Gson gson = new Gson();
    ArrayList<String> playerStrings = new ArrayList<String>();
    for(Player player : playerArray){
        playerStrings.add(gson.toJson(player));
    }
    putListString(key, playerStrings);
}

Player Class:

public class Player implements Serializable {
    private String name;
    private ArrayList<Integer> scores = new ArrayList<>();

    public Player(String name){
        this.name = name;
    }


    public ArrayList<Integer> getScores() {
        return scores;
    }

    public void setScore(int score) {
        scores.add(score);
    }

If anyone have a good solution on how to store and retrive my player arraylist please share

Try converting your objects to JSON before saving to Shared Preferences. GSON is a fast easy to use tool for that.

I have similar requirement in one of my project, and I am able to do it with the help of GSON. Check the below sample code.

   /**
     * Remove preference value.
     *
     * @param mContext The context to use.  Usually your {@link android.app.Application}
     *                 or {@link Activity} object.
     * @param key      The name of the preference to put.
     * <br><br>
     * @return Returns true if preference value were successfully removed from
     * persistent storage.
     */
    public static <E>boolean putList(Context mContext, String key, List<E> objectList){
        return SharedPreferenceUtils.putString(mContext, key, new Gson().toJson(objectList));
    }

    /**
     * Remove preference value.
     *
     * @param mContext The context to use.  Usually your {@link android.app.Application}
     *                 or {@link Activity} object.
     * @param key          The name of the preference.
     * <br><br>
     * @return Returns true if preference value were successfully removed from
     * persistent storage.
     */
    public static <E>List<E> getList(Context mContext, String key){
        TypeToken<List<E>> token = new TypeToken<List<E>>() {};
        String json = SharedPreferenceUtils.getString(mContext, key, null);
        List<E> objectList = new Gson().fromJson(json, token.getType());
        return objectList;
    }

Example:

List<Player> list = new ArrayList<Player>();
list.add(player);
putList(this, "j", list);//Store List to SharedPreference

list = getList(this, "j");//Get List from SharedPreference
Log.e("DATA", list.toString());

For full source code of SharedPreferenceUtils check this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM