SharedPreferences

Jedným z možných spôsobov ukladania dát do mobilného zariadenia je použitie SharedPreferences. Dáta sa ukladajú prostredníctvom typu klúč-hodnota. Uložené hodnoty sa uchovajú aj po ukončení aplikácie. Do SharedPreferences môžeme ukladať rôzne dáta, pričom klúč musí byť typu String a hodnota môže byť primitívneho dátového typu (String, Boolean, int, long, float).

Na získanie objektu SharedPreferences sa používa metóda getSharedPreferences() s parametrom, ktorý definuje prístupový mód, napr. MODE_PRIVATE pre získanie privátnych údajov aplikácie:

Activity.getSharedPreferences(String name, int mode)

MODE_PRIVATE: File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).

MODE_WORLD_READABLE: File creation mode: allow all other applications to have read access to the created file.

MODE_WORLD_WRITEABLE : File creation mode: allow all other applications to have write access to the created file.

Zapisovanie do SharedPreferences vykonáva metóda SharedPreferences.edit(), ktorá získa objekt, cez ktorý môžeme pridať alebo upraviť hodnoty pomocou metód:

  • putInt(String key, int value)
  • putString(String key, String value)
  • remove(String key)

Po pridaní/upravení záznamu musíme zavolať metódu commit(), ktorá dáta uloží do zariadenia.

Na čítanie údajov sú k dispozícií metódy, prvý parameter je klúč a druhý je hodnota, pokiaľ preferences neexistuje:

  • getAll()
  • getString(String key, String defaultValue)
  • getInt(String key, int defaultValue)
  • getLong(String key, int defaultValue)
  • getFloat(String key, int defaultValue)
  • getBoolean(String key, int defaultValue)

Príklad

Aplikácia obsahuje text, ktorý vypisuje na obrazovke text uložený v SharedPreferences. Pod textom sa nachádza EditText, do ktorého sa zadá nový text, ktorý sa uloží do SharedPreferences po stlačení tlačidla „Ulož“. Aktivita sa následne znovu načíta.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
      android:layout_width="match_parent"    
      android:layout_height="match_parent"    
      android:orientation="vertical">
    <TextView
        android:id="@+id/text_aktualne_ulozena_hodnota"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Ulož hodnotu"
        android:layout_gravity="center_horizontal"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Ulož hodnotu" />
        <EditText
            android:id="@+id/edt_uloz_hodnotu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Ulož"
        android:onClick="uloz"/>
</LinearLayout>

 MainActivity.java

public class MainActivity extends AppCompatActivity {
   EditText edtUlozitHodnotu;
    TextView text;
    SharedPreferences sharedPreferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        sharedPreferences = this.getSharedPreferences("p_v", Context.MODE_PRIVATE);

        edtUlozitHodnotu = findViewById(R.id.edt_uloz_hodnotu);

        text = findViewById(R.id.text_aktualne_ulozena_hodnota);

        text.setText(sharedPreferences.getString("ulozenaHodnota","defaultna hodnota"));
    }

    //tlačidlo uložiť hodnotu
    public void uloz(View view) {

        sharedPreferences.edit().putString("ulozenaHodnota",edtUlozitHodnotu.getText().toString()).commit();
        recreate();
    }
}