0% found this document useful (0 votes)
17 views

Unit 4

The document discusses different storage options in Android including content providers, internal storage, external storage, and shared preferences. Content providers allow sharing data between apps through a standardized interface. Internal storage is private to the app while external storage is shared and files can be accessed by other apps. Shared preferences provide a simple way to store primitive data.

Uploaded by

prac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Unit 4

The document discusses different storage options in Android including content providers, internal storage, external storage, and shared preferences. Content providers allow sharing data between apps through a standardized interface. Internal storage is private to the app while external storage is shared and files can be accessed by other apps. Shared preferences provide a simple way to store primitive data.

Uploaded by

prac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Unit 4: Content Provider, FilesShared

Preference, Storage

Content Providers in Android


Content providers are a fundamental building block for data sharing
between apps in the Android ecosystem. They act as a secure and
standardized intermediary, allowing applications to expose and
manage their data for access by other apps. This enables
functionalities like:

 Sharing Data Between Apps: Imagine a note-taking app that


allows you to share specific notes with a calendar app. The note-
taking app can implement a content provider for its notes data, and
the calendar app can leverage the content resolver to access and
display relevant notes within calendar events.
 Centralized Data Repository: Content providers create a central
location for data, promoting better organization and easier access
for authorized apps. This eliminates the need for apps to reinvent
the wheel by storing similar data structures, reducing redundancy
and improving overall system efficiency.
 Structured Data Access: Content providers enforce a structured
approach to data access. They define URIs (Uniform Resource
Identifiers) that act as unique addresses for accessing specific data
pieces within the provider. This structured approach ensures clarity
and simplifies data retrieval for other applications.

Purpose:
Allows applications to share data with other applications. They provide a
standard interface for other applications to access and modify the
data.

Steps to Create Content Provider:

Define a Content Provider Class:

Extend the ContentProvider class and implement its abstract methods.


Declare Content Provider in Manifest:

Add the provider to the AndroidManifest.xml file.

<provider

android:name=".MyContentProvider"

android:authorities="com.example.provider"

android:exported="true"/>

Implement Content Provider Methods:

Implement the required methods: onCreate(), query(), insert(), update(),


delete(), and getType().

Define URI Structure:

Define the URIs that the content provider will handle using a UriMatcher.

Create a Contract Class:

Define the structure of the data, constants for URIs, and column names.

URI (Uniform Resource Identifier):

Purpose: Identifies the data in the provider. It's used by client


applications to access the data.

Structure: Typically includes the scheme, authority, path, and optional id

content://com.example.provider/table_name/123

Scheme: Always content:// for content providers.

Authority: The domain name or identifier of the content provider.

Path: The specific data resource being addressed.

ID: An optional identifier for a specific row.


Working Mechanism: Behind the Scenes

Here's a deeper dive into how content providers’ function:

Content Provider Implementation: An app that wants to share data


creates a class inheriting from the ContentProvider class. This class
houses the logic for CRUD (Create, Read, Update, Delete)
operations on the provider's data. It also defines data structures
and access control mechanisms.

Content Resolver as the Mediator: Other apps interact with the


content provider through the ContentResolver system service. This
service acts as a bridge, allowing apps to make requests to the
provider. They can request data retrieval, insertion of new records,
or updates to existing data using defined methods.

URIs for Data Location: Content providers are accessed using URIs that
follow a specific format. These URIs typically include three parts:

Scheme: Usually content:// to denote a content provider access.

Authority: A unique identifier for the specific content provider you want
to interact with.

Path: Specifies the data path within the provider (e.g., denoting a table
name or a specific record).

Permission Checks for Data Security: To safeguard sensitive information,


content providers can implement permission controls. These
permissions define which apps are authorized to access or modify
the data. This ensures that only approved apps can interact with the
provider, protecting user privacy and data integrity.

CRUD Operations (Create, Read, Update, Delete):

Create (Insert):
o Adds new data to the content provider.
o Method: insert(Uri uri, ContentValues values)
o ContentValues values = new ContentValues();

Example:

values.put("column_name", "value"); Uri newUri =


getContentResolver().insert(CONTENT_URI, values);

Read (Query):

o Retrieves data from the content provider.


o Method: query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)

Example

Cursor cursor = getContentResolver().query(CONTENT_URI,


projection, selection, selectionArgs, sortOrder);

Update:

o Modifies existing data in the content provider.


o Method: update(Uri uri, ContentValues values, String selection,
String[] selectionArgs)

Example

ContentValues values = new ContentValues();

values.put("column_name", "new_value");

int rowsUpdated = getContentResolver().update(CONTENT_URI,


values, selection, selectionArgs);

Delete:
o Removes data from the content provider.
o Method: delete(Uri uri, String selection, String[] selectionArgs)

Example

int rowsDeleted = getContentResolver().delete(CONTENT_URI,


selection, selectionArgs);

Example Implementation:

1. Contract Class:

public final class MyContract {

public static final String AUTHORITY = "com.example.provider";

public static final Uri BASE_CONTENT_URI =


Uri.parse("content://" + AUTHORITY);

public static final String PATH_DATA = "data";

public static final class DataEntry implements BaseColumns {

public static final Uri CONTENT_URI =


BASE_CONTENT_URI.buildUpon().appendPath(PATH_DATA).build();

public static final String TABLE_NAME = "data";

public static final String COLUMN_NAME = "name";

Internal Storage:

Purpose: Internal storage is private to the application and is always


available. It's primarily used for storing sensitive data or data that
doesn't need to be shared with other applications.
Key Points:

Location: Stored in the device's internal memory.

Accessing Internal Storage:

You can use the Context.openFileOutput() method to create and


write to private files within your app's internal storage directory.

For reading private files, use Context.openFileInput().Security: Files


stored here are private and are not accessible to other applications
or users unless the device is rooted.

Lifetime: Files are removed when the application is uninstalled.

Example

String filename = "myfile.txt";

String fileContents = "Hello world!";

FileOutputStream fos = openFileOutput(filename,


Context.MODE_PRIVATE);

fos.write(fileContents.getBytes());

fos.close();

External Storage:

Purpose: External storage refers to removable storage options like


SD cards. It's suitable for storing user-generated data, large media
files (like videos, music), or data that can be shared with other
apps.

Use Cases:

Downloaded music, videos, and photos

User-generated documents or app data meant to be shared


Cached data that can be offloaded to free up internal space (be
cautious about privacy concerns)

Key Points:

o Location: Typically an SD card or internal storage emulated as


an SD card.
o Access: Shared among all applications with appropriate
permissions.
o Security: Files here can be accessed by any application with
the required permissions.
o Lifetime: Files remain until explicitly deleted or the user
uninstalls the application.

Example Usage:

File file = new


File(Environment.getExternalStorageDirectory(),
"myfile.txt");

String fileContents = "Hello world!";

FileOutputStream fos = new FileOutputStream(file);

fos.write(fileContents.getBytes());

fos.close();

Accessing External Storage:

You need to request storage permissions at runtime using the


Storage API (ContextCompat.checkSelfPermission() and
requestPermissions()) before accessing external storage.

Use the Environment.getExternalStoragePublicDirectory() method to


get a reference to specific directories on the external storage.

Then, you can use File class methods to create, read, write, and
manage files within those directories.

Security: External storage is accessible by other apps and the user,


so be mindful of what data you store there.
Shared Preferences:

Purpose: Shared preferences are a lightweight storage option for


storing small amounts of primitive data (strings, integers, booleans,
etc.) as key-value pairs. They are ideal for application settings and
preferences that need to persist across app restarts.

Key Points:

o Storage: Data is stored as XML files in the app's private


directory.
o Access: Accessed using a shared instance of
SharedPreferences.
o Security: Data stored here is private to the application but not
encrypted.
o Lifetime: Remains until explicitly cleared or the application is
uninstalled.

Example Usage:

SharedPreferences sharedPreferences =
getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("key", "value");

editor.apply();

Use Cases:

User login information (consider security implications for sensitive


data)

UI theme preferences (light/dark mode)

Flags indicating app onboarding completion


Accessing Shared Preferences:

Use the getSharedPreferences() method of the Context class to


retrieve a reference to the shared preference file.

Use the Editor object obtained from the shared preferences to put
(store) and get (retrieve) data using key-value pairs.

Security: Shared preferences are stored in an XML file on the


device, so they are not encrypted by default. Avoid storing sensitive
data like passwords in shared preferences.

Choosing the Right Storage Option:

The choice between internal storage, external storage, and shared


preferences depends on the type and size of data you want to store:

Use internal storage for: App-specific data, private settings, and


temporary files.

Use external storage for: User-generated data, large media files,


and data meant for sharing.

Use shared preferences for: Small amounts of application settings


and preferences.

Introduction to SQLite Database,


SQLiteOpenHelper class, and Cursor.

Introduction to SQLite Database:


SQLite is a lightweight, embedded relational database engine that is built
into Android. It provides a convenient way to store structured data in a
local database.

Key Points:

Relational Database: Organizes data into tables with rows and columns,
allowing for efficient data retrieval and manipulation.

Serverless: Unlike traditional SQL databases, SQLite doesn't require a


separate server process to be running.

Transactional: Supports ACID (Atomicity, Consistency, Isolation,


Durability) properties, ensuring data integrity.

Embedded: The entire database is stored in a single disk file, making it


suitable for embedded devices and mobile applications.

Usage: Commonly used for local data storage in Android applications,


such as user preferences, cache, or structured data.

SQLiteOpenHelper Class:

Purpose: SQLiteOpenHelper is a helper class that manages database


creation and version management. It provides methods to create,
upgrade, and downgrade the database schema.

Key Points:

Database Creation: Provides a set of methods for creating and initializing


the database and its tables.

Version Management: Manages database versioning, allowing for


seamless upgrades and migrations.

OnCreate(): Called when the database is created for the first time.

OnUpgrade(): Called when the database needs to be upgraded to a new


schema version.

OnDowngrade(): Called when the database needs to be downgraded to a


previous schema version (rarely used).

Example Usage:

public class MyDbHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "mydatabase.db";

private static final int DATABASE_VERSION = 1;

public MyDbHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

// Create database tables

db.execSQL("CREATE TABLE IF NOT EXISTS my_table (_id INTEGER


PRIMARY KEY, name TEXT)");

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int


newVersion) {

// Upgrade database schema

if (oldVersion < 2) {

db.execSQL("ALTER TABLE my_table ADD COLUMN age


INTEGER");

Cursor: Unveiling Query Results


Read-Only Data Navigator: A Cursor acts as a read-only interface that
represents the outcome of a database query execution. It essentially
provides a way to traverse through the data retrieved by your query.

Row by Row Exploration: The Cursor allows you to iterate through each
row returned by the query. Imagine a table of contacts; a Cursor lets you
visit each contact record (row) one by one.

Extracting Column Values: Within each row, you can access data stored in
specific columns. The Cursor provides methods like getString(), getInt(),
etc., corresponding to different data types (text, integer, etc.) stored in
the columns. By calling these methods, you extract the desired data
values from each row.

Example Usage:

SQLiteDatabase db = dbHelper.getReadableDatabase();

Cursor cursor = db.rawQuery("SELECT * FROM my_table", null);

while (cursor.moveToNext()) {

String name = cursor.getString(cursor.getColumnIndex("name"));

int age = cursor.getInt(cursor.getColumnIndex("age"));

// Process data...

cursor.close(); // Close the cursor when finished

You might also like