Persistent Storage using Perst Lite in Android. Introduction  Android by default uses SQLLite to handle data storage  SQLLite is a relational database.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Java Card Technology Ch04: Java Card Object
CC SQL Utilities.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
VBA Modules, Functions, Variables, and Constants
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
A Guide to MySQL 3. 2 Objectives Start MySQL and learn how to use the MySQL Reference Manual Create a database Change (activate) a database Create tables.
EPOCH 1000 File Management Data Logging and Reporting
From C++ to C#. Web programming The course is on web programming using ASP.Net and C# The course is on web programming using ASP.Net and C# ASP.Net is.
Data Persistence in Android
Introduction to Android Programming Content Basic environmental structure Building a simple app Debugging.
PROG Mobile Java Application Development PROG Mobile Java Application Development Event Handling Creating Menus.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CSE 486/586, Spring 2013 CSE 486/586 Distributed Systems Content Providers & Services.
CPSC 203 Introduction to Computers T59 & T64 By Jie (Jeff) Gao.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 3 Vector Class. Agenda Design and Implementation of Vector class – add, get, set remove, copy, equals, ensureCapacity Hangman using Vector class.
© 2004 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice SISP Training Documentation Template.
CS378 - Mobile Computing Persistence. Saving State We have already seen saving app state into a Bundle on orientation changes or when an app is killed.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
CSE 486/586, Spring 2012 CSE 486/586 Distributed Systems Recitation.
PROG Mobile Java Application Development PROG Mobile Java Application Development Memory and Memory Issues Data Storage.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Data persistence How to save data using SharedPreferences, Files, and SQLite database 1Data persistence.
9 Persistence - SQLite CSNB544 Mobile Application Development Thanks to Utexas Austin.
Diagnostic Pathfinder for Instructors. Diagnostic Pathfinder Local File vs. Database Normal operations Expert operations Admin operations.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Perst Query-by-Example. Customized Searches  When using relational SQL-style databases, you define a search using a query string  Specify columns 
A Guide to MySQL 3. 2 Introduction  Structured Query Language (SQL): Popular and widely used language for retrieving and manipulating database data Developed.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
CS378 - Mobile Computing Persistence. Saving State We have already seen saving app state into a Bundle on orientation changes or when an app is killed.
Microsoft Visual Basic 2008 CHAPTER ELEVEN Multiple Classes and Inheritance.
Class Builder Tutorial Presented By- Amit Singh & Sylendra Prasad.
Processes and Virtual Memory
Visual Basic for Application - Microsoft Access 2003 Finishing the application.
Android - SQLite Database 12/10/2015. Introduction SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
CPSC 203 Introduction to Computers T97 By Jie (Jeff) Gao.
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Android Boot Camp.
Day in the Life (DITL) Production Operations with Energy Builder Copyright © 2015 EDataViz LLC.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
CHAPTER 9 File Storage Shared Preferences SQLite.
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
School of Engineering and Information and Communication Technology KIT305/KIT607 Mobile Application Development Android OS –Permissions (cont.), Fragments,
Mobile Application Development Data Storage. Android provides several options for you to save persistent application data. The solution you choose depends.
Java for android Development Nasrullah Khan. Using instanceof in Android Development the classes such as Button, TextView, and CheckBox, which represent.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
3 A Guide to MySQL.
Android Application Development 1 6 May 2018
SQLite in Android Landon Cox March 2, 2017.
Android Application SQLite 1.
Mobile Application Development Chapter 5 [Persistent Data in Android]
Mobile Application Development Chapter 4 [Android Navigation and Interface Design] IT448-Fall 2017 IT448- Fall2017.
HNDIT2417 Mobile Application Development
This presentation document has been prepared by Vault Intelligence Limited (“Vault") and is intended for off line demonstration, presentation and educational.
HP Quality Center 10.0 The Test Plan Module
SQL – Application Persistence Design Patterns
eSeries Entities By Julie Ladner
This presentation document has been prepared by Vault Intelligence Limited (“Vault") and is intended for off line demonstration, presentation and educational.
Presentation transcript:

Persistent Storage using Perst Lite in Android

Introduction  Android by default uses SQLLite to handle data storage  SQLLite is a relational database style storage  Requires using SQL based concepts to query for data  Require mapping from raw data to object fields  Not very object-oriented

Perst Lite  Perst Lite is an Object-Oriented Database Management System (OODBMS) with a small memory footprint meant for mobile devices  A from scratch implementation of persistence  Working directly with objects not columns and tables  Implements Persistence by reachability  High-speed indexed lookups and Query-by-Example  Open-source and usable for free on any non- commercial project

Dependencies  In order for the Perst classes to be available to you, you must include the PerstAndroid.jar in your Build Path and Export it  This was pre-built for use in this course  Generally, you need to build it yourself  This will apply to any third party library you need included in your application

Dependencies  To set the build path  Copy the PerstAndroid.jar to the root of your project  Right click the project folder  Select Build Path -> Configure Build Path  Select Libraries Tab  Add JAR -> select your PerstAndroid.jar  Select Order/Export Tab  Check the PerstAndroid.jar  PerstAndroid.jar should now appear in the Referenced Libraries node of the project

Permissions

Permissions  Android requires sensitive operations to be marked with permissions  File access  Network access  SMS access  Etc  Permissions are attached to the Android Manifest  If permissions are not proper placed, APIs needing them will fail

Example  Specific APIs will list which permissions are required by them in order to run  These can be added in the XML or via the GUI <manifest xmlns:android=" package=“admu.edu.cs119" android:versionCode="1" android:versionName="1.0"> …

Perst permissions  The following permissions are required in order for Perst to run  android.permission.WRITE_EXTERNAL_STORAGE

Application Management

 Perst will create a file in the SD card to represent its database  This file will remain in place even after the application has been shut off and use this when it starts again  i.e. the data will persist between app starts  In order to “reset” the application state to its initial stat, you will need to clear application data

Example  When viewing the application you have the option to empty out any previously stored data  Hit Clear data

PerstLite

PerstLite  PerstLite has several concepts that need to be understood to be able to use it  Storage  Root Object  Persistent classes  Reachability  Index

Storage

Storage  The Storage interface provides the methods for accessing the object database  This abstracts how the DB is implemented  SD card, etc.  A Storage instance is created using a factory method // get instance of the storage Storage db = StorageFactory.getInstance().createStorage(); // open the database once you have storage instance db.open(databasePath, 40*1024); // min 40k

Defining the database path  The default Android file system is read- only  You will need to find the actual path to the db file by first opening it and then getting the absolute path to it String databasePath = "test.dbs"; try { // MODE_APPEND is needed or else the file will auto-delete openFileOutput(databasePath, Context.MODE_APPEND).close(); } catch(Exception e) { throw new RuntimeException(e); } databasePath = getFileStreamPath(databasePath).getAbsolutePath(); System.out.println("Initializing: "+databasePath); // open the database db.open(databasePath, 40*1024);

Opening the database  The database file is opened using the open(String name, int pagesize)  The name corresponds to the filename of the db file (you can actually see this file in the /appdb folder)  The pagesize is how much memory to allocate to Perst  The minimum size is 40*1024 bytes  This is used as its internal cache

Closing the Database  Perst keeps data in memory as much as possible to prevent unnecessary saves to the file system which is significantly slower  However, premature termination of the app can prevent changes from being saved  In order to close the DB correctly, you must invoke close() on the Storage  If the incorrectly closed, Perst will try to recover what it can on the next startup.

Example public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Storage db = StorageFactory.getInstance().createStorage(); String databasePath = getAbsolutePath("test.dbs"); db.open(databasePath, 40*1024); // open the database MyRootClass root = (MyRootClass)db.getRoot(); // check if a root object is present in this file if (root == null) { root = new MyRootClass(); // create root object root.setText("I am new text"); db.setRoot(root); TextView tf = (TextView) findViewById(R.id.text); tf.setText("Saving root"); } else { TextView tf = (TextView) findViewById(R.id.text); tf.setText(root.getText()); } db.close(); }

Example getAbsolutePath() private String getAbsolutePath(String databasePath) { try { // MODE_APPEND is needed or else the file will auto-delete openFileOutput(databasePath, Context.MODE_APPEND).close(); } catch(Exception e) { throw new RuntimeException(e); } databasePath = getFileStreamPath(databasePath).getAbsolutePath(); return databasePath; } NOTE: openFileOutput() and getFileStreamPath() are methods of Activity

Saving objects

Root object  In order to be able to save anything to the Storage you must first have a root object attached to it  Which must be an IPersistent subtype  Through this reference, all other IPersistent data (if any) can be retrieved. For example:  Some applications need only a single set of data to be saved  Others need several lists of data and a way to pull these lists out by name

Registering the Root object  When initializing a Storage file you must first invoke getRoot() to check if a root has already been attached  If the method returns null, no root is attached  You must then instantiate an IPersistent type and assign this using the setRoot(IPersistent)

Example MyRootClass root = (MyRootClass)db.getRoot(); // get storage root if (root == null) { // Root is not yet defined: storage is not initialized root = new MyRootClass(); // create root object db.setRoot(root); // register root object }

Styles of Root objects  Simple  Not so simple Storage Single Persistent Object Persistent Object Storage Contains fields or collections of Persistent objects Could be a simple Persistent subclass with nothing but primitives and Strings Persistent Object Collection fields

Styles of Root objects  Complex StorageIndex Persistent Object Index (see later) acts as a dynamic look- up table for other objects

IPersistent/Persistent  The IPersistent interface contains many methods. Most of these are not directly used by the developer but are used by Perst itself  The usual way to make a class work with Perst is to make the class you are saving extend the Persistent class  org.garret.perst.IPersistent and org.garret.perst.Persistent  This supplies all the IPersistent methods needed by the Perst  In cases where extending Persistent is not possible  You will need to open the source code of Persistent and copy them to your class manually and make your class implement the IPersistent interface

Example public class MyRootClass extends Persistent { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; }

Persistence-style  There are two ways to persist data in Perst  Explictly  By Reachability

Explicit Persistent and Storage  When using explicit persistence, a persistent object must be associated to a Storage object so that it can be saved e.g. Via constructor Appointment(Strorage db) { super(db) }  super constructor should pass this db to the parent  A Persistent object can then be saved by calling the object’s store() method

Example import org.garret.perst.*; public class Appointment extends Persistent { private Date time; private int length; private String location; private String subject; Appointment() { } Appointment(Strorage db) { super(db) } …  For explicit style, you need to have 2 constructors  One blank  One which takes a Storage object

Problem with explicit persistence  The problem with explicit persistence is the fact is becomes cumbersome to save a tree of objects  You need to manually store each object in the graph front the top down Storage Persistent Object Contains fields or collections of Persistent objects Persistent Object Collection fields

Persistence by Reachability  Instead of manually calling store() on an object, you can call the Storage commit()  In order for your new object to be saved, however, a path to the root object must be present (i.e. It is reachable)  NewPersistent1 will be saved on commit() but not NewPersistent2  commit() is automatically called on a Storage close() Root Persistent Object Storage Vector New persistent1 New persistent2 addElement() contains

Fields and Collections  Your root object can contain IPersistent type fields or collections like Lists and HashMaps  Collections can be automatically saved as long as their contents are all IPersistent types  Fields that are not meant to be persisted should be marked with the Java keyword transient

Editing existing Persistent objects  Once a root object is saved and retrieved in subsequent runs of your program, you can edit the root’s values  Including any internal objects  You can manually save individual objects using their store() method if a Storage is already associated to it

Editing existing Persistent objects  However, when using Storage.commit() Perst will only update objects that have their modify() method called  This will flag the object for saving (dirty)  Perst will not resave everything, it only saves objects that have been marked as dirty  For performance purposes (re-saving all objects is slow)

Design considerations  When using Persistence by reachability you are relieved of the burden of manually saving an object graph  However, you are now responsible for marking changes using modify() in the changed objects in the graph

Design considerations  Where you place the modify() is something you need to consider  you can modify() at the UI level when you press a button  You can modify() at the object level  The object itself calls its own modify() when certain fields are changed, requires placing modify() in all methods of the object causing change