无法从SharedReferences添加/检索集

qhhrdooz  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(129)

我想在SharedReferences中存储一个集合,并在再次启动活动时检索它。我已经写了这段代码,但无法在下一次发射时得到设置。请告诉我哪里出错了。

private ListView list;
    private ArrayList<String> arrayList = new ArrayList<>();
    private ArrayAdapter arrayAdapter;
    private String difficulty, exactResult, strScore;
    private int score;
    Set<String> set = new HashSet<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_results);

        SharedPreferences pref = getApplicationContext().getSharedPreferences("results", 0); // 0 - for private mode
        SharedPreferences.Editor editor = pref.edit();

        try {
            pref.getStringSet(getString(R.string.results), set);
            arrayList.addAll(set);
        } catch (Exception e) {
            e.printStackTrace();
        }

        list = findViewById(R.id.list);
        Intent intent1 = getIntent();
        difficulty = intent1.getStringExtra("difficulty");
        score = intent1.getIntExtra("score", 0);
        strScore = String.valueOf(score);
        exactResult = difficulty.concat(": ").concat(strScore);

        arrayList.add(exactResult);
        set.addAll(arrayList);

        editor.putStringSet("results", set);
        editor.apply();

        arrayAdapter = new ArrayAdapter(Results.this, android.R.layout.simple_list_item_1, arrayList);
        list.setAdapter(arrayAdapter);
        }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题