Upgrade to Pro — share decks privately, control downloads, hide ads and more …

4. Loeng 2015 Mobiilirakenduste arendamine Andr...

4. Loeng 2015 Mobiilirakenduste arendamine Android platvormile

Avatar for Indrek Kõue

Indrek Kõue

May 03, 2015
Tweet

More Decks by Indrek Kõue

Other Decks in Programming

Transcript

  1. TOPICS Local data storage • Shared Preferences • Internal storage

    • External storage • SQLite database + ORM Positioning
  2. REHERSAL 1. User Interface Thread 2. Restore Activity State 3.

    Device Independent Pixel 4. Services 5. Content Providers 6. Broadcast Receivers
  3. DATA STORAGE Shared Preferences for primitive data Example: counters, user

    selected values etc. Internal storage for large private data sets Example: private pictures, videos etc. External storage for large public data sets Example: pictures, videos etc. SQLite databases for structured storage Example: customer database, statistics, products etc.
  4. SHARED PREFERENCES Used for storing key-value pairs of primitive data

    types Example: int, long, double etc. + String • Private to your applications • Persists across user sessions • Cleared when user uninstalls application • User can manually clear going under settings > apps > clear data
  5. SHARED PREFERENCES getDefaultSharedPreferences(int mode) one preferences file for whole applications

    getSharedPreferences(String name, int mode) multiple preferences files by name getPreferences(int mode) single preference for an Activity mode: 0 - Context.MODE_PRIVATE 4 - Context.MODE_MULTI_PROCESS
  6. SHARED PREFERENCES Write SharedPreferences settings = getDefaultSharedPreferences( Context.MODE_PRIVATE); SharedPreferences.Editor editor

    = settings.edit(); editor.putBoolean("isNightThemeSelected", true); editor.commit(); Read SharedPreferences settings = getDefaultSharedPreferences( Context.MODE_PRIVATE); boolean nightTheme = editor.getBoolean("isNightThemeSelected", false);
  7. INTERNAL STORAGE Can be used for any type of data:

    text, images, videos, raw binary etc. • Private to your applications • Persists across user sessions • Cleared when user uninstalls application • User can manually clear going under settings > apps > clear data
  8. INTERNAL STORAGE Write String FILENAME = "hello_file"; String string =

    "hello world!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close();
  9. INTERNAL STORAGE Read String FILENAME = "hello_file"; FileInputStream fis =

    openFileInput(FILENAME); byte[] bytes = fis.read(); fis.close();
  10. EXTERNAL STORAGE Can be used for any type of data:

    text, images, videos, raw binary etc. • Needs permission “WRITE_EXTERNAL_STORAGE” • Can be used for public files • Persists across user sessions • If data is public, then it is not deleted after app uninstall File object Defines reference to resource Example: File file = new File(path, filename);
  11. EXTERNAL STORAGE getExternalStoragePublicDirectory (String type) Type: DIRECTORY_PICTURES DIRECTORY_MOVIES DIRECTORY_DOWNLOADS etc.

    Example: File path = Environment. getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES);
  12. EXTERNAL STORAGE Write InputStream is = getMyStream(); byte[] data =

    new byte[is.available()]; is.read(data); File file = new File(path, "DemoPicture.jpg"); OutputStream os = new FileOutputStream(file); os.write(data); // close is and os Read File file = new File(path, "DemoPicture.jpg");
  13. SQLITE • Full support for SQLite databases. • Won’t be

    accessible outside the application. • Needs to extend SQLiteOpenHelper • To write call getWritableDatabase() • To read call getReadableDatabase(), • Execute SQL using query() • SQLite query will return a Cursor pointing to all the rows
  14. SQLITE public class DbHelper extends SQLiteOpenHelper { private static final

    String DICTIONARY_TABLE_NAME = "dictionary"; private static final String DICTIONARY_TABLE_CREATE = "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" + KEY_WORD + " TEXT, " + KEY_DEFINITION + " TEXT);"; DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DICTIONARY_TABLE_CREATE); } }
  15. SQLITE Insert example: // Gets the data repository in write

    mode SQLiteDatabase db = DbHelper.getWritableDatabase(); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id); values.put(FeedEntry.COLUMN_NAME_TITLE, title); values.put(FeedEntry.COLUMN_NAME_CONTENT, content); // Insert the new row, returning the primary key of the new row long newRowId = db.insert(FeedEntry.TABLE_NAME, FeedEntry.COLUMN_NAME_NULLABLE, values);
  16. SQLITE Select example: SQLiteDatabase db = mDbHelper.getReadableDatabase(); // Define a

    projection that specifies which columns from the database // you will actually use after this query. String[] projection = {FeedEntry._ID, FeedEntry.COLUMN_NAME_TITLE, FeedEntry.COLUMN_NAME_UPDATED, ...}; Cursor c = db.query( FeedEntry.TABLE_NAME, // The table to query projection, // The columns to return null, // The columns for the WHERE clause null, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups null // The sort order );
  17. SQL ORM Object-relational mapping Less code = good code ORMLite:

    http://ormlite.com/sqlite_java_android_orm. shtml
  18. SQL ORM @DatabaseTable(tableName = "accounts") public class Account { @DatabaseField(id

    = true) private String name; @DatabaseField private String param1; @DatabaseField private String param2; ….….. public Account() { // ORMLite needs a no-arg constructor } }
  19. SQL ORM Insert: ConnectionSource connectionSource = new JdbcConnectionSource("jdbc:h2:mem:account";); Dao<Account, String>

    accountDao = DaoManager.createDao(connectionSource, Account.class); Account account = GetCurrentUserAccount(); accountDao.create(account); Select: Account account = accountDao.queryForId(ID);
  20. POSITIONING LocationManager • Query for the last known user location.

    • Register/unregister for periodic location updates • Register/unregister for a given Intent to be fired if the device comes within a given proximity Example: LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
  21. POSITIONING WIFI and mobile network provider Permission: android.permission.ACCESS_COARSE_LOCATION Example: locationManager.requestLocationUpdates

    (LocationManager.NETWORK_PROVIDER, TIME_INTERVAL, DISTANCE_INTERVA, locationListener); + fast - unaccurate (up to 100m)
  22. POSITIONING // Define a listener that responds to location updates

    LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; LocationManager locationManager = (LocationManager) this. getSystemService(Context.LOCATION_SERVICE); // Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(LocationManager. NETWORK_PROVIDER, MINIMUM_TIME_MS, MINIMUM_DISTANCE_M, locationListener);
  23. TOPICS Local data storage • Shared Preferences • Internal storage

    • External storage • SQLite database + ORM Positioning
  24. ?