You are on page 1of 25

Almacenamiento

Logro

Al finalizar la sesión, el estudiante


construye experiencias móviles
nativas que almacenan
información en archivos locales del
dispositivo.
Temario

• Fundamentos
• Shared Preferences
• Almacenamiento interno
• Almacenamiento externo
TEMA # 1

Fundamentos
Permisos

Toda app en Android se ejecuta en un sandbox con


acceso limitado.
Storage Options

Shared Preferences
Internal Storage
External Storage
SQLite Storage
Network Connection
TEMA # 2

Shared Preferences
Using Shared Preferences

SharedPreferences class

Almacenar / recuperar pares key-value de tipos


primitivos.
Data persiste entre sesiones de usuario
Shared Preferences
Obtener un objeto SharedPreferences

getSharedPreferences()
getPreferences()

Modes
Context.MODE_PRIVATE
Context.MODE_APPEND
Shared Preferences
Almacenar valores
edit() retorna SharedPreferences.Editor
Agregar valores con putXX (ej. putBoolean(), putString())
Confirmar nuevos valores con commit()
Leer valores con getXX (ej. getBoolean(), getString())
Shared Preferences
Almacenando valores simples
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
Shared Preferences
Almacenando colecciones
public class Product {
public final String productName;
public final String price;
public final String content;
public final String imageUrl;

public Product() {
}

public Product(String productName, String price,


String content, String imageUrl) {
this.productName = productName;
this.price = price;
this.content = content;
this.imageUrl = imageUrl;
}
}

List<Product> favoriteProducts = new ArrayList<Product>();


Shared Preferences
Almacenando colecciones


Gson gson = new Gson();
String jsonFavoriteProducts = gson.toJson(favoriteProducts);

SharedPreferences settings = getSharedPreferences(


PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(“favorites”, jsonFavoriteProducts);
editor.commit();
Shared Preferences
Recuperando colecciones


public class ProductList extends ArrayList<Product> {};

SharedPreferences settings = getSharedPreferences(


PREFS_NAME, Context.MODE_PRIVATE);
String jsonFavoriteProducts = settings.getString(“favorites”);
favoriteProducts = new Gson().fromJson(
jsonfavoriteProducts, ProductList.class);
TEMA # 3

Almacenamiento interno
Internal Storage
FileOutputStream

openFileOutput() (file name, operating mode)


Almacenar con write()
Cerrar con close()

Modes
Context.MODE_PRIVATE
Context.MODE_APPEND
Internal Storage
FileOutputStream

String FILENAME = "hello_file";


String string = "hello world!";

FileOutputStream fos = openFileOutput(


FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Internal Storage
FileInputStream

openFileInput() (file name, operating mode)


Leer con read()
Cerrar con close()
TEMA # 4

Almacenamiento externo
External Storage
Permissions

<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>

Permissions
WRITE_EXTERNAL_STORAGE
READ_EXTERNAL_STORAGE (implicit)
External Storage
Public Directories

public File getAlbumStorageDir(String albumName) {


// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
External Storage
Environment directories

DIRECTORY_ALARMS
DIRECTORY_DCIM
DIRECTORY_DOCUMENTS
DIRECTORY_DOWNLOADS
DIRECTORY_MOVIES
DIRECTORY_MUSIC
DIRECTORY_NOTIFICATIONS
DIRECTORY_PICTURES
DIRECTORY_PODCASTS
DIRECTORY_RINGTONES
Conclusiones

1 Storage

2 Shared Preferences 4 Internal Storage 6 External Storage

3 Almacenar valores 5 Abrir para escritura 7 Manejo de permisos


Recuperar valores Guardar información Rutas externas
Abrir para lectura
Leer información
Bibliografía

• Preferences
http://developer.android.com/training/basics/data-storage/shared-preferences.html
Material producido por la Universidad Peruana de Ciencias Aplicadas
Autor: Ángel Augusto Velásquez Núñez
COPYRIGHT ©UPC 2016 - Todos los derechos reservados.