簡體   English   中英

使用sharedPreferences保存和加載微調器值

[英]Saving and loading spinner value using sharedPreferences

我嘗試使用sharedPreferencesspinner保存和加載所選項目。 即使代碼沒有顯示錯誤,也無法正常工作。 有人幫忙。

country=(Spinner)findViewById(R.id.spinner);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.countries_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

public void saveFile(){
        SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPref.edit();
        int userChoice = country.getSelectedItemPosition();
        editor.putInt("userChoiceSpinner",userChoice);
}

public void readFile(){
        SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
        int spinnerValue = sharedPref.getInt("userChoiceSpinner",0);
        country.setSelection(spinnerValue);
}

您忘記了使用editor.apply(); SharedPreferences保存價值

editor.apply();

  • 提交您的首選項更改,從此編輯器回到正在編輯的SharedPreferences對象。 這將自動執行請求的修改,從而替換SharedPreferences當前存在的任何內容。

嘗試這個

    public void saveFile(){
        SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPref.edit();
        int userChoice = country.getSelectedItemPosition();
        editor.putInt("userChoiceSpinner",userChoice);
        editor.apply();
    }

您將國家/地區和微調器設置為相同的ID,可能顯示一個微調器未設置數據

country=(Spinner)findViewById(R.id.spinner);
spinner = (Spinner) findViewById(R.id.spinner);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM