本文介绍了Android共享首选项TinyDB putListObject函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用TinyDB的 putListObject 函数将对象列表保存到共享首选项中,但是却出现了第二参数类型错误错误.我可以很好地使用 putObject 函数,该错误仅在使用 putListObject 函数时出现.

I'm trying to save an object list to the Shared Preferences using TinyDB's putListObject function, but I'm getting a Wrong 2nd argument type error. I can use the putObject function just fine, the error only appears when I use the putListObject function.

玩家职业:

public class Player {

    private String name = "";
    private int score = 0;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

putListObject函数:

putListObject function:

 public void putListObject(String key, ArrayList<Object> objArray){
        checkForNullKey(key);
        Gson gson = new Gson();
        ArrayList<String> objStrings = new ArrayList<String>();
        for(Object obj : objArray){
            objStrings.add(gson.toJson(obj));
        }
        putListString(key, objStrings);
    }

我如何使用该功能:

ArrayList<Player> playerList = new ArrayList<Player>();

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

我得到的错误:


我们将不胜感激!


Help would be much appreciated!

推荐答案

尽管 Player 的任何实例都是 Object ,是 ArrayList 播放器与对象的 ArrayList 不同.将您的方法签名更改为:

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)

和for循环至:

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

这篇关于Android共享首选项TinyDB putListObject函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 22:55