How do I save app data to my smartphone?

0

In order to not depend on internet connection, can you save the app data in your phone?
For example, when you first open select the language and in the next uses of the app it is not necessary to ask the language, but to search directly from the data that was saved.

    
asked by anonymous 24.04.2015 / 14:37

2 answers

2

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 key-values that you would like to save (as the android documentation itself says).

Here are the main ways to use SharedPreferences:

Creating SharedPreferences

SharedPreferences pref = getApplicationContext().getSharedPreferences("MinhasPreferencias", MODE_PRIVATE); 
Editor editor = pref.edit();

Storing Data as Key-Value

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 SharedPreferences values

// 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 SharedPreferences Information

 editor.clear();
 editor.apply(); 

A detail: You can save changes using the apply () and commit () method, distinguishing that apply () is asynchronous.

Here are some links that might be helpful:

Developer.Android - SharedPreferences

Using SharedPreferences

Answer based on this other answer

Creating configuration files

    
24.04.2015 / 16:37
0

You can store in an xml file, as is a android default , such as activitys, manifest etc.

    
24.04.2015 / 14:47