Spinner Selection - Save to SharedPreferences, then Restore

I use "SharedPreferences" in my application to maintain the ability to save / retrieve string values ​​from multiple edittext blocks, and this works just fine. I also have a Spinner in my activity with an array of strings for its useful values. But I don’t understand how to write the spinners choice in SharedPreferences, and then read SharedPreferences later in retireve and set its value.

Here is the configuration I have for edittext:

-Button to activate save values ​​in SharedPreferences -

public void buttonSaveSendClick(View view) {

    SharedPreferences.Editor editor = getPreferences(0).edit();

    EditText editTextCallId = (EditText) findViewById(R.id.editTextCallId);
    editor.putString("editTextCallIdtext", editTextCallId.getText().toString());
    editor.putInt("selection-startCallId", editTextCallId.getSelectionStart());
    editor.putInt("selection-endCallId", editTextCallId.getSelectionEnd());
    editor.commit();
}

-Button to activate the last saved values ​​from SharedPreferences -

public void buttonRestoreLastClick(View view) {

    SharedPreferences prefs = getPreferences(0); 

    EditText editTextCallId = (EditText) findViewById(R.id.editTextCallId);
    String editTextCallIdtextrestored = prefs.getString("editTextCallIdtext", null);
    editTextCallId.setText(editTextCallIdtextrestored, EditText.BufferType.EDITABLE);
    int selectionStartCallId = prefs.getInt("selection-startCallId", -1);
    int selectionEndCallId = prefs.getInt("selection-endCallId", -1);
    editTextCallId.setSelection(selectionStartCallId, selectionEndCallId);
}

, ()? , ""?

+3
1

editor.apply(); editor.put(); . , , . , , int .

:

int selectedPosition = yourSpinner.getSelectedItemPosition();
editor.putInt("spinnerSelection", selectedPosition);
editor.apply();

:

yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));

, . :

String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
editor.putString("spinnerSelection", selectedString);
editor.apply();

, [i] , prefs. yourSpinner.setSelected(position). ArrayList, ,

ArrayList.indexOf(prefs.getString("spinnerSelection", ""));

indexOf(); ArrayList indexOf(); . indexOf(); , , .

+6

Source: https://habr.com/ru/post/1793631/


All Articles