Docsity

Android Preferences & Content Providers: Shared Preferences & Content Providers, Exams of Computer science

Toggle sidebar
bg1
Preferences in Android
Preferences are stored as groups of key/value pairs and are available at the Activity level or shared across all
of Activity classes for a given application (but not outside of the application package).
Preferences in Android are used to keep track of application and user preferences
What Is Preference File?
A preference file is actually a xml file saved in internal memory of device. Every application have some data
stored in memory in a directory data/data/application package name i.e data/data/com.abhiandroid.abhiapp
so whenever getSharedPreferences(String name,int mode) function get called it validates the file that if it
exists or it doesn’t then a new xml is created with passed name.
Two Ways To Save Data Through Shared Preference: Activity based preferences and creating custom
preferences.
Mode And Its Type In Shared Preference:
1. Context.MODE_PRIVATE – default value (Not accessible outside of your application)
2. Context.MODE_WORLD_READABLE – readable to other apps
3. Context.MODE_WORLD_WRITEABLE – read/write to other apps
Shared preferences are simply sets of data values that are stored persistently. By persistence, we are talking
about data that persists across application lifecycle events. In other words, the application (or device, for that
matter) can be started and stopped without losing the data. The next time the user launches the application,
that data will still be available.
An individual preference is simply a key-value pair with a specific data type for the value. The preference key
is simply a string that uniquely identifies the preference and the value is just that: the value of that preference.
For example, your application might want to store the user’s name. The application could have a single
preference to store this information:
ļ‚· The data type of the preference could be a String
ļ‚· The key could be a string called ā€œUserNameā€
ļ‚· The value would be the actual username string, such as ā€œAndroidPowerUser123ā€ or ā€œBobā€
A preference can be any of a number of different data types. The following data types are supported by the
SharedPreferences class:
ļ‚· Boolean values
ļ‚· Float values
ļ‚· Integer values
ļ‚· Long values
ļ‚· String values
How Shared Preferences Work
The Android SDK includes helpful classes for getting application preferences up and running easily. Preference
functionality can be found in the SharedPreferences interface of the android.content package.
An application can have multiple sets of application preferences, where each set has a name. For example, a
game application might have a set of preferences for user information (user name, email, high score, etc.) and
a set of preferences for game state (current level, current score, etc.). Preferences can be stored at the activity
or application level.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Android Preferences & Content Providers: Shared Preferences & Content Providers and more Exams Computer science in PDF only on Docsity!

Preferences in Android

Preferences are stored as groups of key/value pairs and are available at the Activity level or shared across all of Activity classes for a given application (but not outside of the application package). Preferences in Android are used to keep track of application and user preferences

What Is Preference File?

A preference file is actually a xml file saved in internal memory of device. Every application have some data stored in memory in a directory data/data/application package name i.e data/data/com.abhiandroid.abhiapp so whenever getSharedPreferences(String name,int mode) function get called it validates the file that if it exists or it doesn’t then a new xml is created with passed name. Two Ways To Save Data Through Shared Preference: Activity based preferences and creating custom preferences. Mode And Its Type In Shared Preference:

  1. Context.MODE_PRIVATE – default value (Not accessible outside of your application)
  2. Context.MODE_WORLD_READABLE – readable to other apps
  3. Context.MODE_WORLD_WRITEABLE – read/write to other apps Shared preferences are simply sets of data values that are stored persistently. By persistence, we are talking about data that persists across application lifecycle events. In other words, the application (or device, for that matter) can be started and stopped without losing the data. The next time the user launches the application, that data will still be available. An individual preference is simply a key-value pair with a specific data type for the value. The preference key is simply a string that uniquely identifies the preference and the value is just that: the value of that preference. For example, your application might want to store the user’s name. The application could have a single preference to store this information: ļ‚· The data type of the preference could be a String ļ‚· The key could be a string called ā€œUserNameā€ ļ‚· The value would be the actual username string, such as ā€œAndroidPowerUser123ā€ or ā€œBobā€ A preference can be any of a number of different data types. The following data types are supported by the SharedPreferences class: ļ‚· Boolean values ļ‚· Float values ļ‚· Integer values ļ‚· Long values ļ‚· String values

How Shared Preferences Work

The Android SDK includes helpful classes for getting application preferences up and running easily. Preference functionality can be found in the SharedPreferences interface of the android.content package. An application can have multiple sets of application preferences , where each set has a name. For example, a game application might have a set of preferences for user information (user name, email, high score, etc.) and a set of preferences for game state (current level, current score, etc.). Preferences can be stored at the activity or application level.

Application-level preferences are available across all activities. These preferences are retrieved using the application Context class method called getSharedPreferences() by name. For example: import android.content.SharedPreferences; … SharedPreferences settings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE); There is no limit to the number of sets of shared preferences your application can have. How your application organizes its preferences is up to you. However, you may want to declare your preference set names so that you can easily load and access the preferences from any Activity within your application. For example: public static final String PREFERENCE_FILENAME = "AppGamePrefs"; An activity can also have private preferences. These preferences are only available within the specific Activity class and are not shared with other activities. An activity can only have one set of private preferences. The following code retrieves the activity’s private preferences: import android.content.SharedPreferences; … SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);

Setting Preferences

Saving preferences to your application is fairly straightforward. First, you must decide if you want application or activity preferences. Use the appropriate method to retrieve the appropriate SharedPreferences object: use the getPreferences() method of the Activity class for activity-level preferences or the getSharedPreferences() method of the Context class for application-level preferences. Once you have a valid SharedPreferences object, you must use a SharedPreferences.Editor to add, modify, or delete preference content. To retrieve an Editor for a specific SharedPreferences object, use its edit() method. Make any changes to the preferences using the methods available in the Editor class. For example, the SharedPreferences.Editor class has helper methods for saving preferences of different data types: ļ‚· Store boolean values with the putBoolean() method ļ‚· Store float values with the putFloat() method ļ‚· Store int values with the putInt() method ļ‚· Store long values with the putLong() method ļ‚· Store String values with the putString() method Within the Editor, you can also remove a specific preference by name using the remove() method, or remove all preferences within the set using the clear() method. Once you’ve finished editing the SharedPreferences object, you can save your changes using the Editor’s commit() method. For example, the following code retrieves a set of application preferences called ā€œMyGamePreferencesā€ and adds a string preference called ā€œUserNameā€ with a value of ā€œGuest123ā€ and a Boolean preference called ā€œPaidUserā€ with a value of false. import android.content.SharedPreferences; … SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);

numbers, strings and Boolean values. Different sets of preferences can be stored in named preference sets. Use shared preferences to store simple application data in a persistent manner. Android Menus Provide some common functionality around the application. There are 3 types of menus in Android:

  1. Option Menu : Search, Compose Email and Settings.
  2. Context Menu : floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.
  3. Pop-up Menu : A popup menu displays a list of items in a vertical list

Create a Menu

a standard XML format to define menu items. Instead of building a menu in our activity's code, we should define a menu and all its items in an XML menu resource and load menu resource as a Menu object in our activity or fragment. we need to create a new folder menu inside of our project resource directory ( res/menu/ ) and add a new XML file to build the menu with the following elements. Element Description

It’s a root element to define a Menu in XML file and it will hold one or more and elements. It is used to create a menu item and it represents a single item on the menu. This element may contain a nested element in order to create a submenu. It’s an optional and invisible for elements. It is used to categorize the menu items so they share properties such as active state and visibility. Following is the example of defining a menu in an XML file ( menu_example.xml ).

The **** element in **menu** supports different type of attributes to define item’s behaviour and appearance. Following are the some of commonly used **** attributes in android applications.

Attribute Description android: id It is used to uniquely identify an element in the application. android:icon It is used to set the item's icon from drawable folder. android: title It is used to set the item's title android:showAsAction It is used to specify how the item should appear as an action item in the app bar. In case if we want to add submenu in menu item, then we need to add a

element as the child of an . Following is the example of defining a submenu in menu item.

Load Android Menu from an Activity

Once we are done with creation of menu, we need to load the menu resource from our activity using MenuInflater.inflate() like as shown below. @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_example, menu); }

Handle Android Menu Click Events

In android, we can handle a menu item click events using ItemSelected() event based on the menu type. Following is the example of handling a context menu item click event using onContextItemSelected(). @Override public boolean onContextItemSelected(MenuItem item) {

Data It specifies a type of data to an intent filter. When we create an intent, it’s important to specify the type of data (MIME type). Category Generally, the android category is optional for intents and it specifies the additional information about the type of component that should handle an intent.

Android Intent Types

There are two types of intents available in android, those are Implicit Intents and Explicit Intents.

Implicit Intents: In android, Implicit Intents won’t specify any name of the component to start instead, it

declare an action to perform and it allows a component from other apps to handle it. For example, by using implicit intents we can request another app to show the location details of the user or etc. Following is the simple code snippet of implicit intent in the android application. Intent intent=new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.abcd.com")); startActivity(intent); Example : When we enter the website URL and click on the button it will open a website in a new browser window in the same application. More details: https://www.tutlane.com/tutorial/android/android-implicit- intents-with-examples

Explicit Intents

In android, Explicit intents explicitly specify the name of the component to be invoked by activity and we use explicit intents to start a component in our own app. For example, we can start a new activity in response to a user action using explicit intents. By using explicit intents we can send or share data/content from one activity to another activity based on our requirements. To create an Explicit Intent , we need to define the component name for an Intent object. Intent di = new Intent(this, ActivityView.class); di.setData(Uri.parse("http://www.tutlane.com")); startService(di);

Example: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText firstNum = (EditText)findViewById(R.id.firstNum); final EditText secNum = (EditText)findViewById(R.id.secondNum); Button btnAdd = (Button)findViewById(R.id.addBtn); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int num1 = Integer.parseInt(firstNum.getText().toString()); int num2 = Integer.parseInt(secNum.getText().toString()); Intent intent = new Intent(MainActivity.this,ResultActivity.class); intent.putExtra("SUM",num1+" + "+num2+" = "+(num1+num2)); startActivity(intent); } }); } } public class ResultActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result); TextView result = (TextView)findViewById(R.id.resultView); Intent intent = getIntent(); String addition = (String)intent.getSerializableExtra("SUM"); result.setText(addition);

Content Providers

A content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the provider using a ā€˜ provider client object’. Together, providers and provider clients offer a consistent, standard interface to data that also handles inter-process communication and secure data access.

Generally, in android to send a request from UI to ContentResolver we have another object called CursorLoader which is used to run the query asynchronously in background. In android application, the UI components such as Activity or Fragment will call a CursorLoader to query and get a required data from ContentProvider using ContentResolver. The ContentProvider object will receive data requests from the client, performs the requested actions (create, update, delete, retrieve) and return the result. Following is the pictorial representation of requesting an operation from UI using Activity or Fragment to get the data from ContentProvider object. Content URIs In android, Content URI is a URI that is used to query a content provider to get the required data. The Content URIs will contain the name of an entire-provider (authority) and the name that points to a table (path). Generally the format of URI in android applications will be like as shown below content://authority/path Following are the details about various parts of an URI in android application. content:// - The string content:// is always present in the URI and it is used to represent the given URI is a content URI. authority - It represents the name of content provider, for example phone, contacts, etc. and we need to use a fully qualified name for third party content providers like com.tutlane.contactprovider path - It represents the table’s path. The ContentResolver object use the URI’s authority to find the appropriate provider and send the query objects to the correct provider. After that ContentProvider uses the path of content URI to choose the right table to access. Following is the example of a simple example of URI in android applications. content://contacts_info/users

Here the string content:// is used to represent URI is a content URI, contacts_info string is the name of the provider’s authority and users string is the table’s path. Creating a Content Provider To create a content provider in android applications we should follow below steps. ļ‚· We need to create a content provider class that extends the ContentProvider base class. ļ‚· We need to define our content provider URI to access the content. ļ‚· The ContentProvider class defines a six abstract methods (insert(), update(), delete(), query(), getType()) which we need to implement all these methods as a part of our subclass. ļ‚· We need to register our content provider in AndroidManifest.xml using tag. Following are the list of methods which need to implement as a part of ContentProvider class. ļ‚· query() - It receives a request from the client. By using arguments it will get a data from the requested table and return the data as a Cursor object. ļ‚· insert() - This method will insert a new row into our content provider and it will return the content URI for newly inserted row. ļ‚· update() - This method will update existing rows in our content provider and it returns the number of rows updated. ļ‚· delete() - This method will delete the rows in our content provider and it returns the number of rows deleted. ļ‚· getType() - This method will return the MIME type of data to given content URI. ļ‚· onCreate() - This method will initialize our provider. The android system will call this method immediately after it creates our provider.

SQLite Database in Android

SQLite is another data storage available in Android where we can store data in the user’s device and can use it any time when required. SQLite is a opensource SQL database that stores data to a text file on a device. SQLite supports all the relational database features

The SQLiteOpenHelper is responsible for opening database if exist, creating database if it does not exists and upgrading if required. The SQLiteOpenHelper only require the DATABASE_NAME to create database. After extending SQLiteOpenHelper you will need to implement its methods onCreate, onUpgrade and constructor. onCreate(SQLiteDatabase sqLiteDatabase) method is called only once throughout the application lifecycle. It will be called whenever there is a first call to getReadableDatabase() or getWritableDatabase() function available in super SQLiteOpenHelper class. So SQLiteOpenHelper class call the onCreate() method after creating database and instantiate SQLiteDatabase object. Database name is passed in constructor call. Create: Creating a database is very simple in android by using SQLiteOpenHelper class. Whenever we need to create a database we have to extend SQLiteOpenHelper class as follows: /*A helper class to perform database related queries/ public class SqliteManager extends SQLiteOpenHelper { public static final String DATABASE_NAME = "abhiandroid.db"; public static final int version = 1 ; public SqliteManager(Context context) { super(context, DATABASE_NAME, null, version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String dbQuery = "CREATE TABLE Items (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT, description TEXT)"; sqLiteDatabase.execSQL(dbQuery); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { } } Insert, Read, Delete & Update Operation In Sqlite: To perform insert, read, delete, update operation there are two different ways: ļ‚· Write parameterized queries (Recommended) ļ‚· Write raw queries Parameterized Queries : These are those queries which are performed using inbuilt functions to insert, read, delete or update data. These operations related functions are provided in SQLiteDatabase class.

Raw Queries : These are simple sql queries similar to other databases like MySql, Sql Server etc, In this case user will have to write query as text and passed the query string in rawQuery(String sql,String [] selectionArgs) or execSQL(String sql,Object [] bindArgs) method to perform operations. Insert: To perform insert operation using parameterized query we have to call insert function available in SQLiteDatabase class. insert() function has three parameters like public long insert(String tableName,String nullColumnHack,ContentValues values) where tableName is name of table in which data to be inserted. public long insert(String tableName,String nullColumnHack,ContentValues values) NullColumnHack may be passed null, it require table column value in case we don’t put column name in ContentValues object so a null value must be inserted for that particular column, values are those values that needs to be inserted- ContentValues is a key-pair based object which accepts all primitive type. Update : Update function is quite similar to insert but it requires two additional parameters, it doesn’t required nullColumnHack. It has total four parameters two are similar to insert function that is tableName and contentValues. Another two are whereClause(String) and whereArgs(String[]). Update function is available in SQLiteDatabase class it looks as follows: public int update(String tableName,ContentValues contentValues,String whereClause,String[] whereAr gs) Here whereClause is tell the database where to update data in table, it’s recommended to pass ?s (questions) along with column name in whereClause String. Similarly whereArgs array will contain values for those columns whose against ?s has been put in whereClause. Update function will return number of rows affected if success, 0 otherwise. Delete: Similar to insert and update, delete function is available in SQLiteDatabase class, So delete is very similar to update function apart from ContentValues object as it’s not required in delete. public int delete(String tableName,String whereClause,String [] whereArgs) function has three parameters these are totally similar to update function’s parameters and are used in same way as in update function. db.delete( "Items" , whereClause, whereArgs); Read(select): Reading from a database table is bit different from other functions like insert,update and delete. SQLiteDatabase class provides query() method to read data from table. query() method is overloaded with different set of parameters. It returns Cursor object so Cursor is a result-set with queried data, it provides different functions really helpful while reading data. Following are some overloaded query functions: ļ‚· public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

Sr. No. Key DDL DML 1 Stands for DDL stands for Data Definition Language. DML stands for Data Manipulation Language. 2 Usage DDL statements are used to create database, schema, constraints, users, tables etc. DML statement is used to insert, update or delete the records. 3 Classification DDL has no further classification. DML is further classified into procedural DML and non- procedural DML. 4 Commands CREATE, DROP, RENAME and ALTER. INSERT, UPDATE and DELETE.

Cursors

Cursors are what contain the result set of a query made against a database in Android. The Cursor class has an API that allows an app to read (in a type-safe manner) the columns that were returned from the query as well as iterate over the rows of the result set. Reading Cursor Data Once a cursor has been returned from a database query, an app needs to iterate over the result set and read the column data from the cursor. Internally, the cursor stores the rows of data returned by the query along with a position that points to the current row of data in the result set. When a cursor is returned from a query() method, its position points to the spot before the first row of data. This means that before any rows of data can be read from the cursor, the position must be moved to point to a valid row of data. The Cursor class provides the following methods to manipulate its internal position: ļ‚· boolean Cursor.move(int offset): Moves the position by the given offset ļ‚· boolean Cursor.moveToFirst(): Moves the position to the first row ļ‚· boolean Cursor.moveToLast(): Moves the position to the last row ļ‚· boolean Cursor.moveToNext(): Moves the cursor to the next row relative to the current position ļ‚· boolean Cursor.moveToPosition(int position): Moves the cursor to the specified position ļ‚· Cursor.moveToPrevious(): Moves the cursor to the previous row relative to the current position Each move() method returns a boolean to indicate whether the operation was successful or not. This flag is useful for iterating over the rows in a cursor.

Managing the Cursor The internals of a cursor can contain a lot of resources such as all the data returned from the query along with a connection to the database. Because of this, it is important to handle a cursor appropriately and tell it to clean up when it is no longer in use to prevent memory leaks. To perform the cleanup, the Cursor class contains the Cursor.close() method, which needs to be called when an activity or fragment no longer needs the cursor. In versions of Android before 3.0, cursor maintenance was left to developers. They either had to handle the closing of the cursor themselves or had to make sure they informed an activity that it was using a cursor so the activity would close the cursor at an appropriate time. Android 3.0 introduced the loader framework that takes care of managing cursors for activities/fragments. To support older versions of Android, the loader framework has also been backported and added to the support library. When using the loader framework, apps no longer need to worry about calling Cursor.close() or informing an activity/fragment of a cursor that it needs to manage.

Reading Contacts

You can read phone contacts using Content Provider. With the help of this content provider we can communicate with the contacts app and query the URIs and columns to get contact information and it will return as contact name, all contact numbers, all email addresses, company name, etc.