如何在本地保存和加载自定义对象的键?

How to save and load keys of a custom object locally?

我有一个自定义对象 questionObject,我从 firebase 加载了大约 100 个此类对象的列表,并将其存储在 ArrayList<questionObject> result 中。然后,我按降序对列表 result 进行排序,并将其传递给函数 selectQuestionSet,在该函数中我必须提取之前未向用户显示的前 5 个问题。我需要存储我已经显示的对象的键,并在下次我必须 select 另外 5 个问题以确保没有重复时加载它们。

我该如何实现?我尝试使用 SharedPreferences,但它只存储原始数据类型,所以对我来说用处不大。

这是我的自定义对象:

public class questionObject implements Comparable<questionObject>{
    public String question;
    public String option1;
    public String option2;
    public String option3;
    public String option4;
    public String explanation;
    public String correct_attempts;
    public String total_attempts;
    public int key;


    public questionObject(String question, String option1, String option2, String option3, String option4, String explanation, String correct_attempts, String total_attempts, int key) {
        this.question = question;
        this.option1 = option1;
        this.option2 = option2;
        this.option3 = option3;
        this.option4 = option4;
        this.explanation = explanation;
        this.correct_attempts = correct_attempts;
        this.total_attempts = total_attempts;
        this.key = key ;

    }

    public String getQuestion() {
        return question;
    }

    public String getOption1() {
        return option1;
    }

    public String getOption2() {
        return option2;
    }

    public String getOption3() {
        return option3;
    }

    public String getOption4() {
        return option4;
    }

    public String getExplanation() {
        return explanation;
    }

    public String getCorrect_attempts() {
        return correct_attempts;
    }

    public String getTotal_attempts() {
        return total_attempts;
    }

    public int getKey() {
        return key;
    }

    @Override
    public int compareTo(questionObject comparestu) {
        float compareRatio= Integer.valueOf(((questionObject)comparestu).getCorrect_attempts ())/Integer.valueOf(((questionObject)comparestu).getTotal_attempts ());

        return Float.compare(compareRatio,  Integer.valueOf(this.total_attempts)/Integer.valueOf( this.total_attempts ) );

    }
}

这些是我正在使用的功能:

public void selectQuestionSet(ArrayList<questionObject> result){
        int count = 0;
        Collections.sort(result);
        for (questionObject object: result) {
            if(count < 4 && checkUsage ( object.key )){
                //display the question
                //append key to stored list
            }

        }
    }

    public boolean checkUsage(int key){
        //Check whether key already used or not here
        return false;
    }

我应该在上面的函数中写什么才能从 result 对象中得到 5 个问题,其 key 不在存储的键中?

一种方法是将密钥存储在 SharedPrefernces

由于密钥是 int 类型,您可以将它们存储在 SharedPrefrences

或者另一种方法是序列化对象,然后存储整个对象。为此,您可以参考