AP M2
AP M2
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
• 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.
➢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.
➢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
For example:
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.
/>
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.
➢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
// 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.
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!
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
• 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.
Description
Abstract Method
➢ 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
• 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
• 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
➢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
For Text
"text/plain“
For Image
"image/jpeg"
""image/jpg"
"image/png“
For Video
"video/wav" "video/mp4"