0% found this document useful (0 votes)
8 views94 pages

AP M2

This document provides an overview of Android resources, explaining their importance in application development and how they can be utilized to enhance flexibility and maintainability. It covers various types of resources such as string resources, layout resources, color resources, dimension resources, and image resources, along with examples of their implementation in XML and Java code. Additionally, it discusses resource reference syntax, the structure of resource directories, and the use of logcat for debugging in Android applications.

Uploaded by

santamariya474
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)
8 views94 pages

AP M2

This document provides an overview of Android resources, explaining their importance in application development and how they can be utilized to enhance flexibility and maintainability. It covers various types of resources such as string resources, layout resources, color resources, dimension resources, and image resources, along with examples of their implementation in XML and Java code. Additionally, it discusses resource reference syntax, the structure of resource directories, and the use of logcat for debugging in Android applications.

Uploaded by

santamariya474
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/ 94

Module – 2

SEMESTER VI - CS/BCA
S.A
1. Understanding android resources
➢Resources play a key role in Android architecture. A resource in Android is a
file (like a music file or a file that describes the layout for a window) or a
value (like the title of a dialog box) that is bound to an executable
application.
➢These files and values are bound to the executable application in such a way
that you can change them or provide alternatives without recompiling the
application.
➢Familiar examples of resources include strings, colors, dimensions and
layouts.
➢Instead of hard-coding strings in an application, resources allow you to use their
IDs instead.
➢This indirection lets you change the text of the string resource without changing
the source code.
• Android R .java is a java class that contain definitions for all the
resources a specific application that you are building. Every
resource that is used in you application will have its id in the
android R.java file.

• Suppose if a simple plain text view is dragged into the main screen
of main-activity.xml, now this plain text view will have its resource
id in the android R.java file.
Example

• XML file saved at res/values/strings.xml:


• <?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello!</string>
</resources>
This layout XML applies a string to a View – activitymain.xml:
• <TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

• MainActivity.java
• String mystring = getResources().getString(R.string.hello);
a). String Resources
➢Android allows you to define strings in one or more XML resource
files.
➢These XML files containing string-resource definitions reside in the
/res/values subdirectory.
➢The names of the XML files are arbitrary, although you commonly
see the file name as strings.xml.

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="hello">hello</string>
<string name="app_name">hello appname</string>
</resources>
➢When this file is created or updated, the Eclipse ADT plug-in
automatically creates or updates a Java class in your application’s root
package called R.java with unique IDs for the string resources
specified.

➢First, R.java defines a top-level class in the root package:


public static final class R

➢Within that outer class of R, Android defines an inner class, static


final class string.

➢R.java creates this inner static class to hold string resource IDs.
b). Layout Resources
➢In Android, the view for a screen is often loaded from an XML file
as a resource.
➢This is very similar to an HTML file describing the content and
layout of a web page.
➢These XML files are called layout resources.
➢A layout resource is a key resource used in Android UI
programming.
public class HelloWorldActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
➢The line setContentView(R.layout.main) points out that there is a
static class called R.layout, and within that class, there is a constant
called main (an integer) pointing to a View defined by an XML layout
resource file.

➢The name of the XML file is main.xml, which needs to be placed in


the resources’ layout subdirectory.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
➢You need to define a separate layout file for each screen (or activity).
c). Resource Reference Syntax
➢Regardless of the type of resource, all Android resources are
identified (or referenced) by their IDs in Java source code.
➢The syntax you use to allocate an ID to a resource in the XML file is
called Resource Reference Syntax.
➢This syntax is not limited to allocating just ids: it is a way to identify
any resource such as a string, a layout file, or an image.
➢This resource reference has the following formal structure:
➢@package:type/name

resource reference In Java: R.color.color_name


In XML: @package:color/color_name
➢The type corresponds to one of the resource-type namespaces
available in R.java, some of which follow:
✓ R.drawable, R.id, R.layout, R.string, R.plural, R.array
➢You can use any Java package name in place of the package
placeholder to locate the correct R.java file to resolve the reference.
<TextView
android:id=”@+id/text1” …./>

➢In the syntax "@+id/text", the + sign has a special meaning.

➢It tells Android that the ID text may not already exist and, if that’s
the case, to create a new one and name it text.
d). Defining Your Own Resource IDs for Later Use

➢However, it is possible to create IDs beforehand and use them later


in your own packages.
➢We have to create our own resource, first create a resource.xml file
under res/values/.
➢The solution is to use a resource tag called item to define an ID
without attaching to any particular resource.
<resources>
<item type="id" name="text"/>
</resources>
e). Compiled and Uncompiled Android Resources

➢Android supports resources primarily through two types of files:


XML files and raw files.
➢Non compiled binary or text files are kept under raw resources. Each
file has a unique id.
➢The resource type for raw files is raw. So, you can access these file
identities through R.raw.filename-extension.
➢Resource files are kept in various subdirectories based on their type.
➢Here are some important subdirectories in the /res folder and the
types of resources they host:
✓ anim: Compiled animation files
✓ drawable: Bitmaps
✓ layout: UI and view definitions
✓ values: Arrays, colors, dimensions, strings, and styles
✓ xml: Compiled arbitrary XML files
✓ raw: Noncompiled raw files
➢The resource compiler in the Android Asset Packaging Tool (AAPT)
compiles all the resources except the raw resources and places them into
the final .apk file.
➢This file, which contains the Android application’s code and
resources, correlates to Java’s .jar file (apk stands for Android package).
➢ The .apk file gets installed onto the device.
2. Enumerating Key Android Resources
a). String Arrays
➢An array of strings can be specified as a resource in any file under the
/res/values subdirectory.
➢To do so, an XML node called string-array is used.
➢This node is a child node of resources just like the string resource
node.
➢An example of specifying an array in a resource file.
String.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="test_array">
<item>one</item>
<item>two</item>
<item>three</item>
</string-array>
</resource>
➢Once you have this string-array resource definition, you can retrieve
this array in the Java code as shown
MainActivity.java
package com.example.strapp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str[] = getResources().getStringArray(R.array.test_array);
Styling with HTML

Styling can be added to strings with HTML mark up.

For example:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="welcome">Welcome to <b>Android</b>!</string>
</resources>

Bold: <b>, Italic: <i>, <cite>, <big>, <small>


<font face=”font_family“ color=”hex_color”>.

Strikethrough: <s>, <strike>, Underline: <u>, Superscript: <sup>, Subscript:


<sub>, Bullet points: <ul>, <li>,
Line breaks: <br>, Division: <div>
b). Plurals
➢The resource plurals is a set of strings. It is called Quantity string and
is used to defines plurals in android.
➢These strings are various ways of expressing a numerical quantity,
such as how many eggs are in a nest.
➢Consider an example:
✓ There is 1 egg.
✓ There are 2 eggs.
✓ There are 0 eggs.
✓ There are 100 eggs.
➢The sentences are identical for the numbers 2, 0, and 100. However,
the sentence for 1 egg is different.
➢Android allows you to represent this variation as a plurals resource.
String.xml
<resources...>
<plurals name=“plural_example">
<item quantity="one">There is 1 egg</item>
<item quantity="other">There are %d eggs</item>
</plurals>
</resources>
➢The two variations are represented as two different strings under one
plural.
➢Java code helps to use this plural resource to print a string given a
quantity.
➢The first parameter to the getQuantityString() method is the plurals
resource ID.
➢The second parameter selects the string to be used.
➢When the value of the quantity is 1, the string is used as it is.
➢When the value is not 1, you must supply a third parameter whose
value is to be placed where %d is.
➢You must always have at least three parameters if you use a formatting
string in your plurals resource.

String s1=getResources().getQuantityString
(R.plurals. plural_example,1);
String s2=getResources().getQuantityString
(R.plurals. plural_example,2);
c). Color Resources
➢Reference identifiers can be used to indirectly reference colors.
➢This enables Android to localize colors and apply themes.
➢Once the colors are defined and identified colors in resource files, it
can be accessed in Java code through their IDs.
➢These IDs, by extension, are accessible through the Android
android.R.color namespace.

XML Syntax for Defining Color Resources


<resources>
<color name="red">#f00</color>
<color name="blue">#0000ff</color>
<color name="green">#f0f0</color>
<color name="b_gcolor">#ffffff00</color>
</resources>
➢The entries need to be in a file residing in the /res/values subdirectory.
int clr = getResources().getColor(R.color.green);
Color resource can be accessed using the java code given above.

➢Using color resource in a view definition.


<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/b_gcolor"
android:text="Sample Text to Show Red Color“>

/>
d). Dimension Resources
➢Pixels, inches, and points are all examples of dimensions that can play
a part in XML layouts or Java code.
➢Dimension resources can be used to style and localize Android UIs
without changing the source code.

XML Syntax for Defining Dimension Resources


<resources>
<dimen name="size_in_pixels">1px</dimen>
<dimen name="size_in_dp">5dp</dimen>
<dimen name="medium_size">100sp</dimen>
<dimen name=“inch_size”””’>10in</dimen>
</resources>
➢You can specify the dimensions in any of the following units:
px: Pixels
in: Inches
mm: Millimeters
pt: Points
dp: Density-independent pixels based on a 160dpi (pixel density
per inch) screen (dimensions adjust to screen density)
sp: Scale-independent pixels (dimensions that allow for user
sizing; helpful for use in fonts)
➢In Java, you need to access your Resources object instance to retrieve
a dimension by calling getResources on an activity object.
Using Dimension Resources in Java Code
float dimen = getResources().getDimension(R.dimen.size_in_pixels);

Using Dimension Resources in XML


<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/size_in_pixels “
/>
e). Image Resources
➢Android generates resource IDs for image files placed in the
/res/drawable subdirectory.
➢The supported image types include .gif, .jpg, and .png. Each image
file in this directory generates a unique ID from its base file name.
➢If the image file name is sample_image.jpg, for example, then the
resource ID generated is R.drawable.sample_image.
➢You can reference the images available in /res/drawable in other XML
layout definitions.
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=“su bmit"
android:background="@drawable/sample_image"
/>
➢Android also supports a special type of image called a stretchable
image.
➢This is a kind of .png where parts of the image can be specified as
static and stretchable. ImageView is required for viewing images.
➢It comes in handy when used as a background for a button where the button has to stretch
itself to accommodate the text.

➢Java code
Drawable drawable = getResources().getDrawable(R.Drawable.myimage);

➢Xml code
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/myimage" />
f). Color-Drawable Resources
➢In Android, an image is one type of a drawable resource.
➢Android supports another drawable resource called a color-drawable
resource; it’s essentially a colored rectangle.
➢To define one of these color rectangles, you define an XML element
by the node name of drawable in any XML file in the /res/values
subdirectory.
XML Syntax for Defining Color-Drawable Resources
<resources>
<drawable name="red_rectangle">#f00</drawable>
<drawable name="blue_rectangle">#0000ff</drawable>
<drawable name="green_rectangle">#f0f0</drawable>
</resources>
Reviewing the Resources Directory
Structure
Resource Directories :-
➢/res/values/strings.xml
• /colors.xml
• /dimens.xml
• /attrs.xml
• /styles.xml
➢/drawable/*.png
• /*.jpg
• /*.gif
• /*.9.png
➢/anim/*.xml
➢/layout/*.xml
➢/raw/*.*
➢/xml/*.xml
➢/assets/*.*/*.*
Write and View Logs with Logcat

➢Android Monitor includes a logcat Monitor that displays debug messages.


➢The logcat Monitor displays system messages, such as when a garbage collection
occurs, as well as messages that you can add to your app using the Log class.
➢It displays messages in real time and also keeps a history so you can view older
messages.
➢To display just the information of interest, you can create filters, modify how
much information is displayed in messages, set priority levels, display messages
produced by app code only, and search the log.
➢ By default, the logcat Monitor shows the log output related to the most recently
run app only.
➢When an app throws an exception, the logcat Monitor shows a message followed
by the associated stack trace containing links to the code.
logcat Message Format
➢Every Android log message has a tag and a priority associated with
it.
➢The tag of a system log message is a short string indicating the system
component from which the message originates (for
example,ActivityManager).
➢You define it in a Log method call, for example:
Log.d(tag, message);
➢The priority is one of the following values:
✓ V — Verbose (lowest priority)
✓ D — Debug
✓ I — Info
✓ W — Warning
✓ E — Error
✓ A — Assert
➢ Logs messages can be displayed using Log class in Android.
➢ Common logging methods are as follows :
✓ Log.v(String, String) (verbose)
✓ Log.d(String, String) (debug)
✓ Log.i(String, String) (information)
✓ Log.w(String, String) (warning)
✓ Log.e(String, String) (error)
➢In the Log level menu, select one of the following values:
➢Verbose - Show all log messages (the default).
➢Debug - Show debug log messages that are useful during development
only..
➢Info - Show expected log messages for regular usage.
➢Warn - Show possible issues that are not yet errors.
➢Error - Show issues that have caused errors.
➢Assert - Show issues that the developer expects should never happen.
These are very important messages

// for verbose
Log.v(“TAG”, “MESSAGE”);
// for debug
Log.d(“TAG”, “MESSAGE”);
// for information
Log.i(“TAG”, “MESSAGE”);
// for warning
Log.w(“TAG”, “MESSAGE”);
// for error
Log.e(“TAG”, “MESSAGE”);

For Example:
Log.v(“MainActivity”, “We are under the Main Activity”);
Dimension Resources
➢px
Pixels - corresponds to actual pixels on the screen.
➢in
Inches - based on the physical size of the screen.
1 Inch = 2.54 centimeters
➢mm
Millimeters - based on the physical size of the screen.
➢pt
(it depends upon physical size of the screen)
Points - 1/72 of an inch based on the physical size of the screen.
➢dp
Density-independent Pixels - an abstract unit that is based on the physical density of the
screen.

➢sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size
preference.
3. Understanding Content Providers
➢Android uses a concept called content providers for abstracting data
into services.
➢Content Providers manages access to central repository of data.

➢A content provider is a wrapper around data.


➢ A SQLite database on an Android device is an example of a data
source that can be encapsulate into a content provider.
➢To retrieve data from a content provider or save data into a content provider, you
will need to use a set of REST-like URIs.
➢Content-provider abstraction is required only if you want to share data
externally or in between applications.
Content Provider facilitates access to a central data store to allow data sharing
and data manipulation across different applications.
These content providers allow the user abstraction from an underlying database.
➢The role of the content provider in the android system is like a central repository
in which data of the applications are stored.
➢It facilitates other applications to securely access and modifies that data based on
the user requirements.
• Operations in Content Provider
• Four fundamental operations are possible in Content Provider
namely Create, Read, Update, and Delete. These operations are often termed
as CRUD operations.
• Create: Operation to create data in a content provider.
• Read: Used to fetch data from a content provider.
• Update: To modify existing data.
• Delete: To remove existing data from the storage.
• Users can manage to store the application data like images, audio, videos, and
personal contact information by storing them in SQLite Database, in files, or
even on a network.
• Content providers have certain permissions that are used to grant or restrict the
rights to other applications to interfere with the data.
Working of the Content Provider
UI components like Activity and Fragments uses, CursorLoader
object to send query requests to ContentResolver.
The ContentResolver object sends requests (like create, read, update, and
delete) to the ContentProvider as a client. After receiving a request,
ContentProvider object process it and returns the desired result.
• CursorLoader runs asynchronous query in the background.
Architecture of content provider
A content provider coordinates access to the data storage layer in your
application for a number of different APIs and components .
• Sharing access to your application data with other applications
• Sending data to a widget
• Returning custom search suggestions for your application through
the search framework using SearchRecentSuggestionsProvider
• Synchronizing application data with your server using an
implementation of AbstractThreadedSyncAdapter
• Loading data in your UI using a CursorLoader
Built in content providers

Provider Since Usage


Browser SDK 1 Manages your web-searches, bookmarks and browsing-history.
CalendarContract SDK 14 Manages the calendars on the user's device.
CallLog SDK 1 Keeps track of your call history.

The old and deprecated content provider for managing contacts. You
Contacts SDK 1 should only use this provider if you need to support an SDK prior to
SDK 5!

Deals with all aspects of contact management. Supersedes the


ContactsContract SDK 5
Contacts-content provider.

The content provider responsible for all your media files like music,
MediaStore SDK 1
video and pictures.
Settings SDK 1 Manages all global settings of your device.
UserDictionary SDK 3 Keeps track of words you add to the default dictionary.
a). Architecture of Content Providers
➢the content-provider approach has parallels to the following industry
abstractions:
❖ Web sites
❖ REST
❖ Web services
❖ Stored procedures.
Websites
➢Each content provider on a device registers itself like a web site with a
string (akin to a domain name, but called an authority).
➢Like Activities and Services, Content Providers must be registered in
your application manifest before the Content Resolver can discover
them.
➢A Content Provider’s authority is used by the Content Resolver as an
address and used to find the database you want to interact with.
➢Each Content Provider authority must be unique.
➢The general form for defining a Content Provider’s authority is as
follows:
com.<CompanyName>.provider.<ApplicationName>
REST ( Representational State Transfer )
➢Content providers also provide REST-like URLs to retrieve or
manipulate data.
content://com.google.provider.NotePad/Notes
➢The URI to identify a specific note is
content://com.google.provider.NotePad/Notes/3
➢where # is the id of a particular note.
➢Here are some additional examples of URIs that some data providers
accept:
content://media/internal/images
content://media/external/images
content://contacts/people/
content://contacts/people/23
Web Services
➢Content providers exhibit characteristics of web services as well.
➢A content provider, through its URIs, exposes internal data as a
service.
➢However, the output from the URL of a content provider is not typed
data, as is the case for a SOAP-based web-service call.

Stored procedures
➢Stored procedures present service-based access to the underlying
relational data.
b). Structure of Android Content URIs
➢We compared a content provider to a web site because it responds to
incoming URIs.
➢So, to retrieve data from a content provider, all you have to do is
invoke a URI.
➢The retrieved data in the case of a content provider, however, is in the
form of a set of rows and columns represented by an Android cursor
object.
➢Content URIs in Android look similar to HTTP URIs, except that they
start with content and have the general form
content://*/*/*
or
prefix://authority-name/data-type/id
Content URIs

A content URI is a URI that identifies data in a provider. Content URIs include the
symbolic name of the entire provider (its authority) and a name that points to a table
(a path).

Content URI is a URI that is used to query a content provider to get the required
data.
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.

Data type – used to distinguish the kinds of data your content provider

Id - The id is used whenever you want to access a single record.


There are two types of URIs:
directory-based URIs
id-based URIs.
QUERYING

• Now, after accessing provider, and have permission to retrieve data from it. The
next step is to construct the query to request the required action from the
provider. The query returns a cursor .
• Here are the arguments used while querying:
• 1) URI: Uniform Resource Identifier.
• 2) Projection: The query should return a set of columns from the entire
database table. This is known as projection. Passing null will return all columns,
which is inefficient.
• 3) Selection Clause: A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null will return all
rows for the given URI.
• 4) Selection Argument: You may include “?s” in selection, which will be replaced
by the values from selectionArgs, in the order that they appear in the selection.
• 5) SortOrder: SQL ORDER BY clause (excluding the ORDER BY itself). Passing
null will fetch the results which may be unordered.
• Cursor cursor =
getContentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
d). Using the Android Cursor
➢Here are a few facts about an Android cursor:
➢A cursor object provides random read access to rows and columns
it contains.
❖A cursor is a collection of rows.
❖You need to use moveToFirst() before reading any data because
the cursor starts off positioned before the first row.
❖Column names can be accessed.
❖Column types can be accessed.
❖The cursor is random (you can move forward and backward, and
you can jump to a row).
❖Cursor is random, row count can be accessed using cursor.
➢An Android cursor has a number of methods that allows to navigate
through it.
➢To position the cursor on the first row, we use the moveToFirst()
method on the cursor object.
➢This method returns false if the cursor is empty.
➢We then use the moveToNext() method repetitively to walk through
the cursor.
➢To help you learn where the cursor is, Android provides the following
methods:
❖ isBeforeFirst()
❖ isAfterLast()
❖ isClosed()
move(): Moves the position by the given offset
moveToFirst(): Moves the position to the first row
moveToLast(): Moves the position to the last row
moveToNext(): Moves the cursor to the next row relative to the current position
moveToPosition(int position): Moves the cursor to the specified position
moveToPrevious(): Moves the cursor to the previous row relative to the current position
Create Content Provider
• First of all you need to create a Content Provider class that extends
the ContentProviderbaseclass.

• Second, you need to define your content provider URI address which
will be used to access the content.

• Next you will need to create your own database to keep the content.

• Next you will have to implement Content Provider queries to


perform different database specific operations.

• Finally register your Content Provider in your android manifest.xml


using <provider> tag.
The six abstract methods and their description which are essential
to override as the part of ContenProvider class:

Description
Abstract Method

A method that accepts arguments and


fetches the data from the
query()
desired table. Data is retired as a
cursor object.
To insert a new row in the database of
the content provider.
insert()
It returns the content URI of the
inserted row.
This method is used to update the
fields of an existing row.
update()
It returns the number of rows
updated.
This method is used to delete the existing
delete() rows.
It returns the number of rows deleted.

This method returns the Multipurpose Internet


getType() Mail Extension(MIME)
type of data to the given Content URI.
e). Working with the where Clause
➢Content providers offer two ways of passing a where clause:
❖ Through the URI
❖ Through the combination of a string clause and a set of
replaceable string-array arguments
Passing a where Clause Through a URI
➢Imagine you want to retrieve a note whose ID is 23 from the Google
notes database.
Activity someActivity;
//..initialize someActivity
String noteUri = "content://com.google.provider.NotePad/notes/23";
Cursor managedCursor = someActivity.managedQuery( noteUri,
projection, //Which columns to return.
null, // WHERE clause
null); // Order-by clause.
➢The Uri class representing the incoming argument uri has a method to
extract the portions of a URI after the root
content://com.google.provider.NotePad.
➢These portions are called path segments;
f). Inserting Records
➢Android uses a class called android.content.ContentValues to hold
the values for a single record that is to be inserted.
➢ContentValues is a dictionary of key/value pairs, much like column
names and their values.
➢You insert records by first populating a record into ContentValues and
then asking android.content.ContentResolver to insert that record using
a URI.
➢Here is an example of populating a single row of notes in
ContentValues in preparation for an insert:
ContentValues values = new ContentValues();
values.put("title", "New note");
values.put("note","This is a new note");
//values object is now ready to be inserted
g). Updates and Deletes
➢ Performing an update is similar to performing an insert, in which
changed column values are passed through a ContentValues object.

ContentValues updateValues = new ContentValues();


String selectionClause = UserDictionary.Words.LOCALE + " LIKE ?";
String[] selectionArgs = {"en_%"};
updateValues.put(UserDictionary.Words.LOCALE);
int numberOfRowsUpdated = getContentResolver().update(
UserDictionary.Words.CONTENT_URI, updateValues, selectionClause,
selectionArgs )
• Similarly, the signature for the delete method is

String selectionClause = UserDictionary.Words.APP_ID + " LIKE ?";


String[] selectionArgs = {"user"};

int numberOfRowsDeleted = getContentResolver().delete(


UserDictionary.Words.CONTENT_URI, selectionClause,
selectionArgs);

• Provider Data Types

➢ Content providers can offer many different data types. The User Dictionary
Provider offers only text, but providers can also offer the following
formats:
➢ integer
➢ long integer (long)
➢ floating point
➢ long floating point (double)
➢ Another data type that providers often use is Binary Large OBject (BLOB)
implemented as a 64KB byte array.
General syntax for insert, delete, update and query

➢ public int delete (Uri uri,String selectionclause, String[]


selectionArgs)

➢ public int update(Uri uri, ContentValues values, String


selection, String[] selectionArgs)

➢ public Cursor query(Uri uri, String[] projection, String


selection, String[] selectionArgs, String sortOrder)

➢ public Uri insert(Uri uri, ContentValues values)


h). Implementing Content Providers
➢To write a content provider, you have to extend
android.content.ContentProvider and implement the following key
methods:
❖ query
❖ insert
❖ update
❖ delete
❖ getType
➢We will illustrate all the details of a content-provider implementation
by describing the steps you’ll need to take:
1. Plan your database, URIs, column names, and so on, and
create a metadata class that defines constants for all of these
metadata elements.
2. Extend the abstract class ContentProvider.
3. Implement these methods: query, insert, update, delete, and
getType.
4. Register the provider in the manifest file.
Representational State Transfer (REST)
➢Representational State Transfer (REST) is a style of architecture based
on a set of principles that describe how networked resources are defined
and addressed.
➢REST is an architectural style, and an approach to communications
that is often used in the development of Web services.

➢REST'S decoupled architecture, and lighter weight communications


between producer and consumer, make REST a popular building style
for cloud-based APIs, such as those provided by Amazon, Microsoft,
and Google.
➢REST is often used in mobile applications, social networking Web
sites, mash up tools, and automated business processes.
➢The REST style emphasizes that interactions between clients and
services is enhanced by having a limited number of operations (verbs).
➢Because each verb has a specific meaning (GET, POST, PUT and
DELETE), REST avoids ambiguity.
4. Understanding Intents
➢Android introduced a concept called intents to invoke components.
➢ The list of components in Android includes activities (UI
components), services (background code), broadcast receivers (code that
responds to broadcast messages), and content providers (code that
abstracts data).
1. Basics of Android Intents
➢An intent is easily understood as a mechanism to invoke components.
Intent invokes an action.
➢ Intents can be used to invoke external applications from your
application.
➢Intents are used to invoke internal or external components from your
application.
➢Intents are objects of the android.content.Intent type.
➢Intents can be used to raise alarms.
An Intent is a messaging object you can use to request an action from
another app component. The fundamental use cases of android are -
➢ Starting an activity
An Activity represents a single screen in an app. You can start a new instance
of an Activity by passing an Intent to startActivity(). The Intent describes the
activity to start and carries any necessary data. To receives a result from an
activity when it finishes call StartAtivityFor Result().
➢ Starting a service
A Service is a component that performs operations in the background without a
user interface. You can start a service to perform a one-time operation (such as
downloading a file) by passing an Intent to startService(). The Intent describes
the service to start and carries any necessary data.
➢ Delivering a broadcast
A broadcast is a message that any app can receive. The system delivers various
broadcasts for system events, such as when the system boots up or the device
starts charging. To deliver broadcast to other apps pass an intent to
sendBroadcast().
2. Available Intents in Android
➢The set of available applications could include the following:
❖ A browser application to open a browser window
❖ An application to call a telephone number
❖ An application to present a phone dialer so the user can enter the
numbers and make a call through the UI
❖ A mapping application to show the map of the world at a given
latitude and longitude coordinate
❖ A detailed mapping application that can show Google street
views
2. Basics of Intents
An Intent object carries information that the Android system uses to
determine which component to start and information that the recipient
component uses in order to properly perform the action. An Intent object
contains action and data part.
• Action - A string that specifies the generic action to perform (such
as view or pick). The action in an intent can be set by setAction () and
read by getAction () methods. Action is a mandatory part of intent.
• The value must be the literal string value of an action.
• The actions can be ACTION_VIEW,
• ACTION_EDIT
• ACTION_DIAL
• ACTION_SET_WALLPAPER
• ACTION_SET_ALARM etc
➢ Data -- The data to operate on, such as a person record in the contacts database,
expressed as a Uri. The URI is read by getData (). URI refers to the unique
resource identifier that specifics a unique location at which a resource is
available.
➢ With the help of this unique resource identifier, a user can easily access the
resource in the application.

• Some examples of action/data pairs are:

• ACTION_VIEW content://contacts/people/1 -Display information about the


person whose identifier is "1".
• ACTION_DIAL content://contacts/people/1 - Display the phone dialer with
the person filled in.
• ACTION_DIAL tel:123 - Display the phone dialer with the given number
filled in.
• ACTION_EDIT content://contacts/people/1 - Edit information about the
person whose identifier is "1".
• ACTION_VIEW content://contacts/people/ - Display a list of people, which
the user can browse through.
• Category -- Gives additional information about the kind of
component that should handles the intent. For
example, CATEGORY_LAUNCHER means it should appear in the
Launcher as a top-level application,
while CATEGORY_ALTERNATIVE means it should be included in
a list of alternative actions the user can perform on a piece of data.
addCategory() places a category in intent object and
removeCategory() deletes the previously added category,
getCategories() gets the set of all categories currently in the object.

• Type -- Specifies an explicit type (a MIME type) of the intent data.


Normally the type is inferred from the data itself.
• Component -- The name of the component to start. Specifies an
explicit name of a component class to use for the intent.

• Extras -- This is a Bundle of any additional information. This can


be used to provide extended information to the component.

• Flags -- Flags are defined in the Intent class that function as


metadata for the intent. The flags may instruct the Android system
how to launch an activity.

• FLAG_ACTIVITY_CLEAR_TASK,
FLAG_ACTIVITY_NEW_TASK
a). Create an alarm
➢To create a new alarm, use the ACTION_SET_ALARM action and
specify alarm details such as the time and message using extras defined
below.
Action
ACTION_SET_ALARM
Data URI
None
Extras
EXTRA_HOUR :- The hour for the alarm.
EXTRA_MINUTES :- The minutes for the alarm.
EXTRA_DAYS :- An ArrayList including each week day on
which this alarm should be repeated. Each day
must be declared with an integer from
the Calendar class such as MONDAY.For a one-
time alarm, do not specify this extra.
EXTRA_RINGTONE :-A content: URI specifying a ringtone to
use with the alarm,
or VALUE_RINGTONE_SILENT for no
ringtone.To use the default ringtone, do
not specify this extra.
EXTRA_VIBRATE :- A boolean specifying whether to vibrate
for this alarm.
Example intent:
public void createAlarm(String message, int hour, int minutes)
{
Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM)
.putExtra(AlarmClock.EXTRA_MESSAGE, message)
.putExtra(AlarmClock.EXTRA_HOUR, hour)
.putExtra(AlarmClock.EXTRA_MINUTES, minutes);

startActivity(intent);

}
b). Calendar
➢To add a new event to the user's calendar, use
the ACTION_INSERT action and specify the data URI
with Events.CONTENT_URI. You can then specify various event
details using extras defined below.
Action
ACTION_INSERT
Data URI
Events.CONTENT_URI
MIME Type
"vnd.android.cursor.dir/event"
Extras
EXTRA_EVENT_ALL_DAY :- A boolean specifying whether
this is an all-day event.
EXTRA_EVENT_BEGIN_TIME :-The start time of the event
(milliseconds since epoch).
EXTRA_EVENT_END_TIME :- The end time of the event
(milliseconds since epoch).
TITLE :- The event title.
DESCRIPTION :- The event description.
EVENT_LOCATION :-The event location.
EXTRA_EMAIL :-A comma-separated list of email addresses
that specify the invitees.
Intent.EXTRA_CC :- A string array of all "CC" recipient
email addresses.Intent.
EXTRA_BCC :- A string array of all "BCC" recipient email
addresses.Intent.
EXTRA_SUBJECT :- A string with the email subject.Intent.
EXTRA_TEXT :- A string with the body of the email.Intent.
EXTRA_STREAM :- A Uri pointing to the attachment. If
using the ACTION_SEND_MULTIPLE action,
this should instead be an ArrayList containing
multiple Uri objects.
Example intent:
public void composeEmail(String[] addresses, String subject, Uri
attachment) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(“text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_STREAM, attachment);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
• Explicit Intent
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i);

• Implicit Intent
Intent i = new Intent();
i.setActionIntent(android.content.Intent.ACTION_VIEW);
startActivity(i);
• Forcing an app chooser

• When there is more than one app that responds to your implicit intent, the
user can select which app to use and make that app the default choice for
the action.

• However, if multiple apps can respond to the intent and the user might want
to use a different app each time, you should explicitly show a chooser
dialog. The chooser dialog asks the user to select which app to use for the
action (the user cannot select a default app for the action). For example,
when your app performs "share" with the ACTION_SEND action, users
may want to share using a different app depending on their current
situation.
Resolving intents to their components

• When the system receives an implicit intent to start an activity it


searches for the best activity for the intent by comparing it to intent
filters based on three aspects

• Action
• Data
• Category

• Each intent filter specifies the type of intents it accepts based on the
intent's action, data, and category. The system delivers an implicit
intent to your app component only if the intent can pass through one
of your intent filters.
• Each intent filter is defined by an <intent-filter> element in the app's
manifest fileInside the <intent-filter>, you can specify the type of intents to
accept using one or more of these three elements.
• <activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
• To pass this filter the action mentioned in the intent must match one of the
actions mentioned in the filter.
Action test

To specify accepted intent actions, an intent filter can declare zero or


more <action> elements, as shown in the following example:
<intent-filter>
<action android:name="android.intent.action.EDIT" />
<action android:name="android.intent.action.VIEW" />
...
</intent-filter>
To pass this filter, the action specified in the Intent must match one of
the actions listed in the filter.
.
Category test

To specify accepted intent categories, an intent filter can declare zero or


more <category> elements, as shown in the following example:
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE"
/>
...
</intent-filter>
For an intent to pass the category test, every category in the Intent must
match a category in the filter. The reverse is not necessary
• Data test
• To specify accepted intent data, an intent filter can declare zero or
more <data> elements, as shown in the following example:
• <intent-filter>
<data android:mimeType="video/mpeg" android:scheme="http"
... />
<data android:mimeType="audio/mpeg" android:scheme="http"
... />
...
</intent-filter>
4. ACTION_PICK
➢ACTION_PICK is one generic action that returns a value when invoked.
➢The idea of ACTION_PICK is to start an activity that displays a list of
items. ACTION_PICK allows to pick an item from the list.
➢The activity then should allow a user to pick one item from that list.
➢Once the user picks the item, the activity should return the URI of the
picked item to the caller. (Pick an image from camera or gallery data
source)
➢we cannot use startActivity(), because startActivity() does not return a
result.
➢If you want to return data, you can use startActivityForResult(),
which comes with a callback.
➢public void startActivityForResult(Intent intent, int
requestCode)
➢This method launches an activity from which you would like a result.
➢ When this activity exits, the source activity’s onActivityResult()
method will be called with the given requestCode.
➢The requestCode is what you passed in to the startActivityForResult()
method.
➢The resultCode can be RESULT_OK, RESULT_CANCELED, or a
custom code.
➢The custom codes should start at RESULT_FIRST_USER.
➢ The Intent parameter contains any additional data that the invoked
activity wants to return.
➢In the case of ACTION_PICK, the returned data in the intent points to
the data URI of a single item.
5. ACTION_GET_CONTENT
➢ACTION_GET_CONTENT is similar to ACTION_PICK.
➢ In the case of ACTION_PICK, a URI is specified that points to a
collection of items, such as a collection of notes.
➢In the case of ACTION_GET_CONTENT, you indicate to
Android that you need an item of a particular MIME type instead
of URI.
➢Android searches for either activities that can create one of those
items or activities that can choose from an existing set of items that
satisfy that MIME type.
5. Introducing Pending Intents
➢Android has a variation on an intent called a pending intent.
➢In this variation, Android allows a component to store an intent for
future use in a location from which it can be invoked again.
➢For example, in an alarm manager, you want to start a service when the
alarm goes off. It is also used in notifications.
➢Android does this by creating a wrapper pending intent around a normal
corresponding intent and storing it away so that even if the calling process
dies off, the intent can be dispatched to its target.
PendingIntent pi = PendingIntent.getActivity(context,
requestcode,Intent , flag);
pi.send ();
➢ The primary purpose of a Pending Intent is to grant permission to a
foreign application to use the contained Intent as if it were executed
from your app's own process.

➢ A pending intent object Is a wrapper around intent object.

➢ Declaring an intent to be executed at a specified future time (the


Android system's AlarmManager executes the Intent).

➢ PendingIntent.getActivity() for an Intent that starts an Activity.


➢ PendingIntent.getService() for an Intent that starts a Service.
➢ PendingIntent.getBroadcast() for an Intent that starts
a BroadcastReceiver.
Standard Activity Actions
ACTION_MAIN ACTION_ANSWER
ACTION_VIEW ACTION_INSERT
ACTION_ATTACH_DATA ACTION_DELETE
ACTION_EDIT ACTION_RUN
ACTION_PICK ACTION_SYNC
ACTION_CHOOSER ACTION_PICK_ACTIVITY
ACTION_GET_CONTENT ACTION_SEARCH
ACTION_DIAL ACTION_WEB_SEARCH
ACTION_CALL ACTION_FACTORY_TEST
ACTION_SEND
ACTION_SENDTO
Standard Broadcast Actions
ACTION_TIME_TICK ACTION_BATTERY_CHANGED
ACTION_TIME_CHANGED ACTION_POWER_CONNECTED
ACTION_TIMEZONE_CHANGED ACTION_POWER_DISCONNECTED
ACTION_BOOT_COMPLETED ACTION_SHUTDOWN
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_REMOVED
ACTION_PACKAGE_RESTARTED
ACTION_PACKAGE_DATA_CLEARED
ACTION_PACKAGES_SUSPENDED
ACTION_PACKAGES_UNSUSPENDED
ACTION_UID_REMOVED
Data Uri

➢URI refers to the unique resource identifier that specifics a unique location at
which a resource is available.
➢With the help of this unique resource identifier, a user can easily access the
resource in the application.
➢It is a better to explicitly set the type of the data in the intent object by using the
setType() method.
➢You can set the URI of the data by using the setData() method.
➢However, if you want to set both the URI and the type of the Data, then you can
use the setDataAndType() method.
➢In addition, the getData() and getType() methods are used to read URI and Type
of the Data.
MIME Type
➢A MIME type is just a standardized way to define that data type by
giving it a unique name. Multipurpose Internet Mail Extensions

❖Different MIME type Format :

For Text
"text/plain“

For Image
"image/jpeg"
""image/jpg"
"image/png“

For Video
"video/wav" "video/mp4"

You might also like