Android Shared Preference TinyDB putListObject frunction

kcochibili Developer of TinyDB answered this on github. He says, you must cast your custom objects to object before trigger putListObject.

A sample for putting Custom Object ArrayList:

ArrayList<Player> players = new ArrayList<Player>();
ArrayList<Object> playerObjects = new ArrayList<Object>();

for(Player a : players){
    playerObjects.add((Object)a);
}

TinyDB tinydb = new TinyDB(this);
tinydb.putListObject("players", playerObjects);

Also when you want to get values from DB it will give ArrayList< Object >. So you may want to cast them back to your custom object.

A sample for this:

TinyDB tinydb = new TinyDB(this);
ArrayList<Object> playerObjects = tinydb.getListObject("players", Player.class);
ArrayList<Player> players = new ArrayList<Player>();

for(Object objs : playerObjects){
    players.add((Player)objs);
}

You can use all custom objects by casting. The other way i prefer is, adding get and put methods for all custom objects to TinyDB Class. For example :

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

//No need Class<?> mClass parameter. Because we know it is Player!
public ArrayList<Player> getListPlayer(String key){
    Gson gson = new Gson(); 

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

    for(String jObjString : objStrings){
        Player player  = gson.fromJson(jObjString,  Player.class);
        playerList.add(player);
    }
    return playerList;
}

Although any instance of Player is an Object, an ArrayList of Players is not the same as an ArrayList of Objects. Change your method signature to :

putListObject(String key, ArrayList<Player> objArray)

and for loop to:

for(Player player : objArray){
   objStrings.add(gson.toJson(player));
}

Tags:

Java

Android