Top Banner
Saving Data How to save your application data in your device +RobertoOrgiu @_tiwiz +MatteoBonifazi @mbonifazi
31

Android - Saving data

Apr 12, 2017

Download

Internet

Matteo Bonifazi
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Android - Saving data

Saving DataHow to save your application data in your device

+RobertoOrgiu@_tiwiz

+MatteoBonifazi@mbonifazi

Page 2: Android - Saving data

Storage optionsAndroid provides several options for you to save

persistent application data.

Page 3: Android - Saving data

Saving Key-Value Sets

Page 4: Android - Saving data

With relatively small collection of key-values that you'd like to save, you should use the

SharedPreferences APIs

Page 5: Android - Saving data

Handle to a SharedPreferences

Context context = getActivity();SharedPreferences sharedPref = context.getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE);

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

getSharedPreferences() multiple shared preference files identified by name, which you specify with the first parameter. You can call

this from any Context in your app.

getPreferences() use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.

Page 6: Android - Saving data

Write to Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPref.edit();editor.putInt(getString(R.string.saved_high_score), newHighScore);editor.commit();

Page 7: Android - Saving data

Read from Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);int defaultValue = getResources().getInteger(R.string.saved_high_score_default);long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

Page 8: Android - Saving data

Saving files

Page 9: Android - Saving data

Internal or External StorageAll Android devices have two file storage areas: "internal" and "external" storage.

Some devices divide the permanent storage space into "internal" and "external" partitions, so even without a removable storage medium

Page 10: Android - Saving data

Internal StorageInternal storage is best when you want to be sure that neither the user nor other apps can access your files.

● It's always available.● Files saved here are accessible by only your app.● When the user uninstalls your app, the system removes all

your app's files from internal storage.

Page 11: Android - Saving data

Create a file in Local Storage

File file = new File(context.getFilesDir(), "myfile");

String string = "Hello world!";FileOutputStream outputStream;try { outputStream = openFileOutput("myfile", Context.MODE_PRIVATE); outputStream.write(string.getBytes()); outputStream.close();} catch (Exception e) { e.printStackTrace();}

Page 12: Android - Saving data

External StorageThe best place for files that don't require access restrictions

● It's not always available.● It's world-readable.● When the user uninstalls your app, the system removes

your app's files from here only if you save them in the directory from getExternalFilesDir().

Page 13: Android - Saving data

Permission and Check Availability

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

public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false;}

Page 14: Android - Saving data

Saving Data in SQL Databases

Page 15: Android - Saving data

SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC, e.t.c

Page 16: Android - Saving data

The Contract class

public final class FeedReaderContract { // To prevent someone from accidentally instantiating the contract class, // make the constructor private. private FeedReaderContract() {}

/* Inner class that defines the table contents */ public static class FeedEntry implements BaseColumns { public static final String TABLE_NAME = "entry"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_SUBTITLE = "subtitle"; }}

A contract class is a container for constants that define names for URIs, tables, and columns. The

contract class allows you to use the same constants across all the other classes in the same package.

Page 17: Android - Saving data

The Contract class

private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" + FeedEntry._ID + " INTEGER PRIMARY KEY," + FeedEntry.COLUMN_NAME_TITLE + " TEXT," + FeedEntry.COLUMN_NAME_SUBTITLE + " TEXT)";

private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;

Page 18: Android - Saving data

SQLiteOpenHelper

public class FeedReaderDbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "FeedReader.db"; public FeedReaderDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES);}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } ….}

A useful set of APIs is available in the SQLiteOpenHelper class. When you use this class to obtain references to your database

Page 19: Android - Saving data

Put Information into a Database

// Gets the data repository in write modeSQLiteDatabase db = mDbHelper.getWritableDatabase();

// Create a new map of values, where column names are the keysContentValues values = new ContentValues();values.put(FeedEntry.COLUMN_NAME_TITLE, title);values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);

// Insert the new row, returning the primary key value of the new rowlong newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);

Page 20: Android - Saving data

Read Information from a Database ( 1 / 2 )

SQLiteDatabase db = mDbHelper.getReadableDatabase();// Define a projection that specifies which columns from the databaseString[] projection = { FeedEntry._ID, FeedEntry.COLUMN_NAME_TITLE, FeedEntry.COLUMN_NAME_SUBTITLE };

String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";String[] selectionArgs = { "My Title" }; // Filter results WHERE "title" = 'My Title'String sortOrder = FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";Cursor cursor = db.query/ FeedEntry.TABLE_NAME, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionArgs, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups sortOrder ); // The sort order

Page 21: Android - Saving data

Read Information from a Database ( 2 / 2 )

List itemIds = new ArrayList<>();while(cursor.moveToNext()) { long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(FeedEntry._ID)); itemIds.add(itemId);}cursor.close();

Page 23: Android - Saving data

There is no ONE SOLUTION!

But there are many other ways

Page 24: Android - Saving data

ObjectBox

Website and referencehttp://greenrobot.org/announcement/introducing-objectbox-beta/http://greenrobot.org/objectbox/documentation/how-to-get-started/

Page 25: Android - Saving data

Defining objects

@Entitypublic class Note { @Id private long id; private String text; private Date date; ...

Page 26: Android - Saving data

Obtaining a box

notesBox = ((MyApplication) getApplication()).getBoxStore().boxFor(Note.class);

Page 27: Android - Saving data

Inserting notes

Note note = new Note(0, noteText, comment, new Date());notesBox.put(note);Log.d(App.TAG, "Inserted new note, ID: " + note.getId());

Page 28: Android - Saving data

Removing notes

notesBox.remove(note);

Page 29: Android - Saving data

Configuring the box

//MyApplication.javaboxStore = MyObjectBox.builder().androidContext(App.this).build();

Page 30: Android - Saving data

More features

● Relations● Compatibility with GreenDAO● Queries● Custom Types

Page 31: Android - Saving data

+MatteoBonifazi@mbonifazi

Thank You!

+RobertoOrgiu@_tiwiz