K
K
Krasavchik262020-05-07 14:11:29
Java
Krasavchik26, 2020-05-07 14:11:29

How to use SharedPreferences for Position, Switch, Spinner?

How to get a position in the code, for example, from Spinner or Switch, in order to save this position in SharedPreferences?
Below are a few codes that I dug up, but it's not clear how to use and which one at all.

First code

Spinner spinner = findViewById(R.id.spinner);
String selected = spinner.getSelectedItemPosition().toString();


Second code:
def_pref = PreferenceManager.getDefaultSharedPreferences(this);
        String text_aaa = def_pref.getString("key", "Тест");
        if (text_aaa != null) {
            switch (text_aaa) {
                case "Тест":
                    

                    break;

                case "Тест 2":
                    
                    break;

                case "Тест 3":
                    
                    break;

                case "Тест 4":
                
                    break;
            }

Third code:
private void saveText() {
        def_pref = getSharedPreferences("MyPref", MODE_PRIVATE);
        SharedPreferences.Editor ed = def_pref.edit();
        ed.putString(SAVED_TEXT, nik.getText().toString());
        ed.commit();

    }


    private void loadText() {
        def_pref = getSharedPreferences("MyPref", MODE_PRIVATE);
        String savedText = def_pref.getString(SAVED_TEXT, "");
        nik.setText(savedText);

    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor, 2020-05-07
@RATlius

1 code - getting the string of the selected `spinner`
2 code - reading from `SharedPreferences`
3 code - reading and writing `SharedPreferences`
You need to:
1: get the value from `Spinner`
2: put the value into `SharedPreferences`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question