0% found this document useful (0 votes)
66 views8 pages

CH 4

The document discusses database connectivity in Android applications using SQLite and content providers. It covers writing to and reading from internal and external storage files in Android, managing data using SQLite databases by creating SQLiteOpenHelper subclasses and executing queries, and sharing data between applications using content providers which allow other apps to access data through a standardized API and URI assignments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views8 pages

CH 4

The document discusses database connectivity in Android applications using SQLite and content providers. It covers writing to and reading from internal and external storage files in Android, managing data using SQLite databases by creating SQLiteOpenHelper subclasses and executing queries, and sharing data between applications using content providers which allow other apps to access data through a standardized API and URI assignments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Subject : Mobile Application Development in Android using Kotlin

Chapter - 2 : Database Connectivity Using SQLite and Content Provider

1) Using Android Data and Storage APIs

Android provides many kinds of storage for applications to store their data. These storage places
are shared preferences, internal and external storage, SQLite storage, and storage via network
connection.

In this chapter we are going to look at the internal storage. Internal storage is the storage of the
private data on the device memory.

By default these files are private and are accessed by only your application and get deleted ,
when user delete your application.

Writing file

In order to use internal storage to write some data in the file, call the openFileOutput() method
with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is
given below −

FileOutputStream fOut = openFileOutput("file name


here",MODE_WORLD_READABLE);

The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the


object of FileInputStream. After that you can call write method to write data on the file. Its
syntax is given below −

String str = "data";

fOut.write(str.getBytes());

fOut.close();

Reading file

In order to read from the file you just created , call the openFileInput() method with the name of
the file. It returns an instance of FileInputStream. Its syntax is given below −

FileInputStream fin = openFileInput(file);

After that, you can call read method to read one character at a time from the file and then you
can print it. Its syntax is given below −

Prepared by : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

int c;

String temp="";

while( (c = fin.read()) != -1){

temp = temp + Character.toString((char)c);

//string temp contains all the data of the file.

fin.close();

Using Shared Preferences

The SharedPreferencesclass provides a general framework that allows you to save and retrieve
persistent key-value pairs of primitive data types. You can use SharedPreferencesto save any
primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions
(even if your application is killed).

User Preferences

Shared preferences are not strictly for saving “user preferences,” such as what ringtone a user has
chosen. If you’re interested in creating user preferences for your application, see
PreferenceActivity, which provides an Activity framework for you to create user preferences,
which will be automatically persisted (using shared preferences).

To get a SharedPreferencesobject for your application, use one of two methods:

getSharedPreferences() – Use this if you need multiple preferences files identified by name,
which you specify with the first parameter.

getPreferences() – Use this if you need only one preferences file for your Activity. Because this
will be the only preferences file for your Activity, you don’t supply a name.

To write values:

Call edit()to get a SharedPreferences.Editor.

Add values with methods such as putBoolean()and putString().

Commit the new values with commit()

To read values, use SharedPreferencesmethods such as getBoolean()and getString().

Prepared by : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Here is an example that saves a preference for silent keypress mode in a calculator:

public class Calc extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override

protected void onCreate(Bundle state){

super.onCreate(state);

...

// Restore preferences

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

@Override

protected void onStop(){

super.onStop();

// We need an Editor object to make preference changes.

// All objects are from android.context.Context

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

Prepared by : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

// Commit the edits!

editor.commit();

Saving cache files

If you’d like to cache some data, rather than store it persistently, you should use getCacheDir()to
open a Filethat represents the internal directory where your application should save temporary
cache files.

When the device is low on internal storage space, Android may delete these cache files to
recover space. However, you should not rely on the system to clean up these files for you. You
should always maintain the cache files yourself and stay within a reasonable limit of space
consumed, such as 1MB. When the user uninstalls your application, these files are removed.

Other useful methods

getFilesDir()

Gets the absolute path to the filesystem directory where your internal files are saved.

getDir()

Creates (or opens an existing) directory within your internal storage space.

deleteFile()

Deletes a file saved on the internal storage.

fileList()

Returns an array of files currently saved by your application.

Accessing files on external storage

If you’re using API Level 8 or greater, use getExternalFilesDir()to open a Filethat represents the
external storage directory where you should save your files. This method takes a typeparameter
that specifies the type of subdirectory you want, such asDIRECTORY_MUSICand
DIRECTORY_RINGTONES(pass nullto receive the root of your application’s file directory).
This method will create the appropriate directory if necessary. By specifying the type of
directory, you ensure that the Android’s media scanner will properly categorize your files in the
system (for example, ringtones are identified as ringtones and not music). If the user uninstalls
your application, this directory and all its contents will be deleted.

Prepared by : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

If you’re using API Level 7 or lower, use getExternalStorageDirectory(), to open a


Filerepresenting the root of the external storage. You should then write your data in the
following directory:

/Android/data/<package_name>/files/

The <package_name>is your Java-style package name, such as “com.example.android.app“. If


the user’s device is running API Level 8 or greater and they uninstall your application, this
directory and all its contents will be deleted.

2) Managing data using SQLite

Using Databases

Android provides full support for SQLite databases. Any databases you create will be accessible
by name to any class in the application, but not outside the application.

The recommended method to create a new SQLite database is to create a subclass of


SQLiteOpenHelperand override theonCreate()method, in which you can execute a SQLite
command to create tables in the database. For example:

public class DictionaryOpenHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;

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);

Prepared by : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(DICTIONARY_TABLE_CREATE);

You can then get an instance of your SQLiteOpenHelperimplementation using the constructor
you’ve defined. To write to and read from the database, call getWritableDatabase()and
getReadableDatabase(), respectively. These both return a SQLiteDatabaseobject that represents
the database and provides methods for SQLite operations.

Android does not impose any limitations beyond the standard SQLite concepts. We do
recommend including an autoincrement value key field that can be used as a unique ID to
quickly find a record. This is not required for private data, but if you implement acontent
provider, you must include a unique ID using the BaseColumns._IDconstant.

You can execute SQLite queries using the SQLiteDatabasequery()methods, which accept various
query parameters, such as the table to query, the projection, selection, columns, grouping, and
others. For complex queries, such as those that require column aliases, you should use
SQLiteQueryBuilder, which provides several convienent methods for building queries.

Every SQLite query will return a Cursorthat points to all the rows found by the query. The
Cursoris always the mechanism with which you can navigate results from a database query and
read rows and columns.

For sample apps already send by me that demonstrate how to use SQLite databases in Android.

3) Sharing Data Between Applications with Content Providers

By using the content provider, data can be shared across applications. The content provider is a
set of data wrapped up in a custom API to read and write. Applications/Processes have to register
themselves as a provider of data. Other applications can request Android to read/write that data
through a fixed API.

Content provider API has methods to perform operations(CRUD) on data.

Contacts are the best example – that exposes user information to other applications, Media store-
Allows other applications to access, store media files.

Prepared by : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

There is some standard methods – insert(), query(), update(), delete(), to access application data.
So it is easy to implement a content provider.

We need to assign a URI to each Content Provider, starting with “content://” and that will be
recognized by applications.

Steps To Writing A Content Provider:

1. Create a class for ContentProvider.

2. Define content URI

3. Implement all the unimplemented methods. insert(), update(), query(), delete(),


getType().

4. Declare the content provider in AndroidManifest.xml

URI: Content Provider URI – Content://Authority/Path/Id

1. content:// – The content provider URIs should start with this value.

2. ‘authority’ – This is Java namespace of the content provider implementation passes the
Java package name.

3. ‘path’ – This is a virtual directory within the provider that identifies, what kind of data
being requested.

4. ‘id’ – This is an optional part that specifies the primary key of a record being requested.
This part can be ignored to access all data.

Applying CRUD Operations:

Add data:

We need to override insert() method. If data inserted successful, it will return the URI value with
the associated with ID.

For example: If we passed – content://packageName/sample

Method will return content://packageName/sample/1

Updating data:

update() method of the ContentProvider is used to update records.

This method will return the number of rows updated.

Prepared by : Shivani Trivedi


Subject : Mobile Application Development in Android using Kotlin

Deleting data:

delete() method of the ContentProvider will return the number of records deleted.

Registering The Provider In AndroidManifest.Xml:

We need to register the content providers in the AndroidManifest.xml.

<provider

android:name=".MyProvider"

android:authorities="packageName.MyProvider">

</provider>

Prepared by : Shivani Trivedi

You might also like