0

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 :

enter image description here

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

3
  • In your serialize method get rid of the red lined code... and also you don't truly need to return anything so you can get rid of that too. Commented Apr 13, 2016 at 13:28
  • I haven't used tinyDb but if you could show the errors you got with it then someone is more likely able to help you. Storing this information in a db is probably going to be your best solution in the long run. Commented Apr 13, 2016 at 13:29
  • the simplest solution is to use a sqlite database. storing big data on shared preferences is not very good idea..... Commented Apr 13, 2016 at 13:30

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

can you show an example, I have tried GSON but no success
0

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.

Comments

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.