In Android development there are several ways to persist the data of an application. One of them is Sharedpreferences, which you can use when you have a small collection of value-keys that you’d like to save (as the android documentation itself says).
Follows the main ways to use Sharedpreferences:
Creating the Sharedpreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MinhasPreferencias", MODE_PRIVATE);
Editor editor = pref.edit();
Storing data as a value key
editor.putBoolean("key_name1", true); // salvando um boolean - true/false
editor.putInt("key_name2", "int value"); // salvando um integer
editor.putFloat("key_name3", "float value"); // salvando um float
editor.putLong("key_name4", "long value"); // salvando um long
editor.putString("key_name5", "string value"); // salvando uma string
// salva as mudanças no SharedPreferences
editor.apply();
Returning values from Sharedpreferences
// Se o valor da chave não existir, então retornará o segundo parametro
// Você pode armazenar esse retorno em uma variável
// Ex: String nome = pref.getString("nome", null);
pref.getBoolean("key_name1", true); // retornando boolean
pref.getInt("key_name2", 0); // retornando Integer
pref.getFloat("key_name3", null); // retornando Float
pref.getLong("key_name4", null); // retornando Long
pref.getString("key_name5", null); // retornando String
Deleting unique values Sharedpreferences
editor.remove("key_name3"); // vai deletar a chave key_name3
editor.remove("key_name4"); // vai deletar a chave key_name4
// salva as mudanças no SharedPreferences
editor.apply();
Deleting all information from Sharedpreferences
editor.clear();
editor.apply();
One detail: You can save the changes using the method apply() and commit(), differentiating that the apply() is asynchronous.
Here are some links that might be useful:
Developer.Android - Sharedpreferences
Using the Sharedpreferences
Response based on this other answer
Creating Settings Files
What kind of data do you want to store?
– ramaral
@ramaral would be small data, I edited the question
– Daniela Morais
If you don’t have trouble with English start with this tutorial. If you have any more specific questions ask a new question.
– ramaral
See if this reply helping.
– ramaral