MAD Ch4 PDF
Document Details
![IdyllicEpiphany1838](https://quizgecko.com/images/avatars/avatar-3.webp)
Uploaded by IdyllicEpiphany1838
Arba Minch University
Tags
Summary
This document details Android data storage options, including shared preferences, internal storage, external storage, SQLite databases, and network connections. It also covers use cases, considerations, and examples for each method. The focus is primarily on practical applications and implementations for Android app development.
Full Transcript
Storing and Retrieving data Chapter 4 Contents ➔ Store and retrieve data in android ➔ Working with content provider ➔ Synchronization and replication Android data storage options Depending on data privacy and storage space requirements; one can choose data storage options ○...
Storing and Retrieving data Chapter 4 Contents ➔ Store and retrieve data in android ➔ Working with content provider ➔ Synchronization and replication Android data storage options Depending on data privacy and storage space requirements; one can choose data storage options ○ Shared preferences – private key-value pair of xml data in device ○ Internal storage – private data on device memory ○ External storage – public data on shared external storage ○ SQLite database – structured data in private database ○ Network connection – store data on a remote server Use Cases and Considerations SQLite: For relational, structured, and large datasets with complex querying needs. SharedPreferences: For small amounts of key-value pairs, such as app preferences and settings. File Storage: For large binary or unstructured files (e.g., media files). Content Providers: For sharing data between apps securely and in a standardized way. Room: A more Android-friendly wrapper for SQLite, with support for annotations and simpler database access. Realm: A fast, object-oriented database, suitable for complex data models and real-time synchronization. Firebase Realtime Database: For real-time, cloud-based data synchronization across users and devices. Using shared preferences Suitable for storing simple key-value pairs or small amounts of data as a plain text (xml) The SharedPreferences java class provides a general framework to store and retrieve persistent key-value pairs of data types. You can save any primitive data : Booleans , floats, ints, longs and strings. The data will persist across user sessions ( even if the app is killed) Working with shared preferences 1) Get SharedPreferences object for your application ○ getSharedPreferences( ) - for multiple preference files with name ○ getPreferences( ) – for one preference file 2) To write values use: ○ Call edit() function to get a SharedPreferences.Editor ○ Use putBoolean(key,value), putString(key,value) etc to write data ○ Commit the new values with commit() or apply() Working with shared preferences 3) To read values use: ○ Use getBoolean(key, defValue), getString(key,defValue) to retrieve data 4) To delete values ○ Call the edit() function ○ Use clear() function ○ Commit the erase of data using apply() or commit() function Example Create a simple app that allows users to set and retrieve their preferences, such as theme color or language selection, using SharedPreferences. Using the Internal Storage To create and write a private file in storage ○ Call openFileOutput( ) with name of file and mode ○ Write to the file with write() ○ Close the stream with close() To read a file ○ Call openFileInput( ) with name of file ○ Read bytes from file using read() ○ Close the stream with close() Using External Storage External storage can be removable media, an internal non- removable media Caution: External files can disappear if the user mounts the external storage on a computer or removes the media Before you work with it; check media availability ○ Call getExternalStorageState( ) The media might be mounted on a computer and it might be ○ Missing , Readonly , or in some other state Accessing files on external storage Use getExternalFilesDir() to open a file that represents an external storage directory where you saved your file. This method takes a type parameter to specify the type of subdirectory you want. For Example: ○ DIRECTORY_MUSIC for music files File musicDir = getExternalFilesDir(Environment.DIRECTORY_MUSIC); ○ DIRECTORY_RINGTONES for ringtone files ○ null – to access the root directory Provide permission for read/write in Android manifest file Example //getting storage state String state= Environment.getExternalStorageState(); //checking if the state is mounted if(state.equals(Environment.MEDIA_MOUNTED)){ //do read/write task } else{ //do something else } Using SQLite Database Android provides full support for SQLite database. It can handle the storage and querying of large datasets efficiently. To create a new SQL database ○ Create a subclass of SQLiteOpenHelper class ○ Override the onCreate( ) method to execute SQL commands and create data tables Working with SQLite database Step 1: Create a subclass of SQLiteOpenHelper class Example : class YourClass extends SQLiteOpenHelper { } Step 2: Now, implementing the two methods of SQLiteOpenHelper is mandatory, hence press ctrl+o or ask for hint (Alt+Enter) The two methods are : onCreate(SQLiteDatabase db) and onUpgrade(SQLiteDatabase db,int i,int i1) Step 3: Call the SQLiteOpenHelper constructor by defining constructor of the class Example: YourClass(Context c) { super(c,dbname,Cursor,version); } …cont’d To write and read from the database use getWritableDatabase() and getReadableDatabase( ) Use SQLiteDatabase.query() methods to execute queries Every SQL query will return Cursor that points to the record …cont’d With cursor you can : Find out how many rows are in the result set via getCount() Iterate over the rows via moveToFirst(), moveToNext(), and isAfterLast() Find out the names of the columns via getColumnNames(), convert those into column numbers via getColumnIndex(), and get values for the current row for a given column via methods like getString(), getInt(), etc. Example Build a note-taking app that allows users to create, edit, and delete notes using an SQLite database. Content provider Content providers are one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only required if you need to share data between multiple applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. …cont’d It allows you to perform queries to read the data, insert new records, and update or delete existing records. …cont’d Any Uri in Android that begins with the content:// scheme represents a resource served up by a content provider. Content providers offer data encapsulation using Uri instances as handles The data could be stored in a SQLite database, or in flat files, or retrieved off a device, or be stored on some far-off server accessed over the Internet. Given a Uri, you may be able to perform basic CRUD (create, read, update, delete) operations using a content provider. Example Develop a music player app that uses a content provider to access and play audio files from the device's media library. Synchronization and replication of mobile data Reading assignment …. Example Build a simple task management app that synchronizes tasks with a remote server using a synchronization framework or library, such as Firebase Realtime Database. The End