0% found this document useful (0 votes)
10 views46 pages

2nd Module

The document outlines the structure and types of resources used in Android applications, focusing on the res/ directory and its subdirectories, which include images, layouts, drawables, and string resources. It details how to define string resources, string arrays, and quantity strings (plurals) in XML, as well as how to reference them in Java code. Additionally, it explains the layout resource structure for defining user interfaces using XML, including the use of View and ViewGroup elements.

Uploaded by

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

2nd Module

The document outlines the structure and types of resources used in Android applications, focusing on the res/ directory and its subdirectories, which include images, layouts, drawables, and string resources. It details how to define string resources, string arrays, and quantity strings (plurals) in XML, as well as how to reference them in Java code. Additionally, it explains the layout resource structure for defining user interfaces using XML, including the use of View and ViewGroup elements.

Uploaded by

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

RESOURCES IN ANDROID :

The res/ directory contains all the resources in its subdirectories: an


image resource, two layout resources, a mipmap/ directory for
launcher icons, and a string resource file. The resource directory
names are important and are described in table 1.
The following are the most common types of resources within
Android apps:

Name Folder Description

Property
animator XML files that define property animations.
Animations

Tween
anim XML files that define tween animations.
Animations

Bitmap files or XML files that act as


Drawables drawable
graphics

XML files that define a user interface


Layout layout
layout

XML files that define menus or action bar


Menu menu
items

XML files with values such as strings,


Values values
integers, and colors.

In addition, note the following key files stored within


the values folder mentioned above:
Name File Description

For color definitions such as text


Colors res/values/colors.xml
color

For dimension values such as


Dimensions res/values/dimens.xml
padding

For string values such as the text for


Strings res/values/strings.xml
a title

For style values such as color of the


Styles res/values/styles.xml
AppBar

String resources
A string resource provides text strings for your application with
optional text styling and formatting. There are three types of resources
that can provide your application with strings:

String
XML resource that provides a single string.
A single string that can be referenced from the application or from
other resource files (such as an XML layout).
file location:
res/values/filename.xml
The filename is arbitrary. The <string> element's name is used as the
resource ID.
compiled resource datatype:Resource pointer to a String.
resource reference:
In Java: R.string.string_name
In XML:@string/string_name
syntax:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string
name="name1" font=”98 px” font-type=”calibiri” > hi</string>
</resources>
elements:
<resources>
Required. This must be the root node.
No attributes.
<string>
A string, which can include styling tags. Beware that you
must escape apostrophes and quotation marks.
attributes:
name
A name for the string. This name is used as the resource ID.
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:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

This application code retrieves a string:


String string = getString(R.string.hello);

String Array
XML resource that provides an array of strings.
An array of strings that can be referenced from the application.
file location:
res/values/filename.xml

The filename is arbitrary. The <string-array> element's name is used


as the resource ID.
compiled resource datatype:
Resource pointer to an array of Strings.
resource reference:
In Java: R.array.string_array_name
In XML: @[package:]array/string_array_name
syntax:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array
name="name2">
<item >item1</item>
</string-array>
</resources>
elements:
<resources>
Required. This must be the root node.
No attributes.
<string-array>
Defines an array of strings. Contains one or more <item> elements.
attributes:
name
String. A name for the array. This name is used as the resource ID to
reference the array.
<item>
A string, which can include styling tags. The value can be a reference
to another string resource. Must be a child of a <string-
array> element. Beware that you must escape apostrophes and
quotation marks. .
No attributes.
example:
XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
</string-array>
</resources>
This application code retrieves a string array:
Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);

Quantity Strings (Plurals)


XML resource that carries different strings for pluralization.
Quantity strings (plurals)
Different languages have different rules for grammatical agreement
with quantity. In English, for example, the quantity 1 is a special case.
We write "1 book", but for any other quantity we'd write "n books".
This distinction between singular and plural is very common, but
other languages make finer distinctions. The full set supported by
Android is zero, one, two, few, many, and other.
The rules for deciding which case to use for a given language and
quantity can be very complex, so Android provides you with methods
such as getQuantityString() to select the appropriate resource for you.
file location:
res/values/filename.xml
The filename is arbitrary. The <plurals> element's name is used as the
resource ID.
resource reference:
In Java: R.plurals.plural_name
syntax:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals
name="plural_name">
<item
quantity=["zero" | "one" | "two" | "few" | "many" | "other"]
>text_string</item>
</plurals>
</resources>
elements:
<resources>
Required. This must be the root node.
No attributes.
<plurals>
A collection of strings, of which, one string is provided depending on
the amount of something. Contains one or more <item> elements.
attributes:
name
String. A name for the pair of strings. This name is used as the
resource ID.
<item>
A plural or singular string. The value can be a reference to another
string resource. Must be a child of a <plurals> element. Beware that
you must escape apostrophes and quotation marks. See Formatting
and Styling, below, for information about to properly style and format
your strings.
attributes:
quantity
Keyword. A value indicating when this string should be used. Valid
values, with non-exhaustive examples in parentheses:
Valu
Description
e
zero When the language requires special treatment of the number
0 (as in Arabic).
one When the language requires special treatment of numbers
like one (as with the number 1 in English and most other
languages; in Russian, any number ending in 1 but not
ending in 11 is in this class).
two When the language requires special treatment of numbers
like two (as with 2 in Welsh, or 102 in Slovenian).
few When the language requires special treatment of "small"
numbers (as with 2, 3, and 4 in Czech; or numbers ending 2,
3, or 4 but not 12, 13, or 14 in Polish).
many When the language requires special treatment of "large"
numbers (as with numbers ending 11-99 in Maltese).
other When the language does not require special treatment of the
given quantity (as with all numbers in Chinese, or 42 in
English).
example:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals name="numberOfSongsAvailable">
<!--
As a developer, you should always supply "one" and "other"
strings. Your translators will know which strings are actually
needed for their language. Always include %d in "one"
because
translators will need to use %d for languages where "one"
doesn't mean 1 (as explained above).
-->
<item quantity="one">%d song found.</item>
<item quantity="other">%d songs found.</item>
</plurals>
</resources>
XML file saved at res/values-pl/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals name="numberOfSongsAvailable">
<!--
As a developer, you should always supply "one" and "other"
strings. Your translators will know which strings are actually
needed for their language. Always include %d in "one"
because
translators will need to use %d for languages where "one"
doesn't mean 1 (as explained above).
-->
<item quantity="one">%d song found.</item>
<item quantity="other">%d songs found.</item>
</plurals>
</resources>
Usage:
int count = getNumberOfSongsAvailable();
Resources res = getResources();
String songsFound =
res.getQuantityString(R.plurals.numberOfSongsAvailable, count,
count);

Defining a String Resource


For every piece of text you want to display within your application
(i.e the label of a button, or the text inside a TextView), you should
first define the text in the res/values/strings.xml file. Each entry is a
key (representing the id of the text) and a value (the text itself). For
example, if I want a button to display "Submit", I might add the
following string resource to res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello!</string>
<string name="submit_label">Submit</string>
</resources>

Layout resource
A layout resource defines the architecture for the UI in an Activity or
a component of a UI.
file location:
res/layout/filename.xml
The filename is used as the resource ID.
compiled resource datatype:
Resource pointer to a View (or subclass) resource
resource reference:
In Java: R.layout.filename
In XML: @[package:]layout/filename
elements:
<ViewGroup>
<View>
<requestFocus>
<include>
1.ViewGroup
A container for other View elements. There are many different kinds
of ViewGroup objects, and each one lets you specify the layout of the
child elements in different ways. Different kinds
of ViewGroup objects include LinearLayout, RelativeLayout,
and FrameLayout.
Attributes:
android:id
Resource ID. A unique resource name for the element, which you can
use to obtain a reference to the ViewGroup from your application. .
android:layout_height
Dimension or keyword. Required. The height for the group, as a
dimension value (or dimension resource) or a keyword
("match_parent" or "wrap_content").
android:layout_width
Dimension or keyword. Required. The width for the group, as a
dimension value (or dimension resource) or a keyword
("match_parent" or "wrap_content")
2.View
An individual UI component, generally referred to as a widget.
Different kinds of View objects include TextView, Button,
and CheckBox.
Attributes:
android:id
Resource ID. A unique resource name for the element, which you can
use to obtain a reference to the View from your application.
android:layout_height
Dimension or keyword. Required. The height for the element, as a
dimension value (or dimension resource) or a keyword
("match_parent" or "wrap_content”)
android:layout_width
Dimension or keyword. Required. The width for the element, as a
dimension value (or dimension resource) or a keyword
("match_parent" or "wrap_content")
<requestFocus>
Any element representing a View object can include this empty
element, which gives its parent initial focus on the screen. You can
have only one of these elements per file.
<include>
Includes a layout file into this layout.
Attributes:
layout
Layout resource. Required. Reference to a layout resource.
android:id
Resource ID. Overrides the ID given to the root view in the included
layout.
android:layout_height
Dimension or keyword. Overrides the height given to the root view in
the included layout. Only effective if android:layout_width is also
declared.
android:layout_width
Dimension or keyword. Overrides the width given to the root view in
the included layout. Only effective if android:layout_height is also
declared.
You can include any other layout attributes in the <include> that are
supported by the root element in the included layout and they override
those defined in the root element
Value for android:id
For the ID value, you typically use this syntax form: "@+id/name", as
shown in the following example. The plus symbol, +, indicates that
this is a new resource ID, and the aapt tool creates a new resource
integer in the R.java class, if it doesn't already exist.
<TextView android:id="@+id/nameTextbox"/>
The nameTextbox name is now a resource ID attached to this element.
You can then refer to the TextView to which the ID is associated in
Java:
TextView textView = findViewById(R.id.nameTextbox);
Custom view elements
You can create custom View and ViewGroup elements and apply
them to your layout the same as a standard layout element. You can
also specify the attributes supported in the XML element.
example:
XML file saved at res/layout/main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
This application code loads the layout for an Activity in
the onCreate() method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
Layouts in views
A layout defines the structure for a user interface in your app, such as
in an activity. All elements in the layout are built using a hierarchy
of View and ViewGroup objects. A View usually draws something the
user can see and interact with. A ViewGroup is an invisible container
that defines the layout structure for View and
other ViewGroup objects, as shown in figure 1.

Figure 1. Illustration of a view hierarchy, which defines a UI layout.

You can declare a layout in two ways:


 Declare UI elements in XML. Android provides a
straightforward XML vocabulary that corresponds to
the View classes and subclasses, such as those for widgets and
layouts. You can also use Android Studio's Layout Editor to
build your XML layout using a drag-and-drop interface.
 Instantiate layout elements at runtime. Your app can
create View and ViewGroup objects and manipulate their
properties programmatically.
Declaring your UI in XML lets you separate the presentation of your
app from the code that controls its behavior. Using XML files also
makes it easier to provide different layouts for different screen sizes
and orientations.
Attributes
Every View and ViewGroup object supports its own variety of XML
attributes. Some attributes are specific to a View object.Some are
common to all View objects, because they are inherited from the
root View class
 ID
Any View object can have an integer ID associated with it to uniquely
identify the View within the tree. When the app is compiled, this ID is
referenced as an integer, but the ID is typically assigned in the layout
XML file as a string in the id attribute. This is an XML attribute
common to all View objects, and it is defined by the View class. You
use it very often. The syntax for an ID inside an XML tag is the
following:
android:id="@+id/my_button"
The at symbol (@) at the beginning of the string indicates that the
XML parser parses and expands the rest of the ID string and identifies
it as an ID resource. The plus symbol (+) means this is a new resource
name that must be created and added to your resources in
the R.java file.
The Android framework offers many other ID resources. When
referencing an Android resource ID, you don't need the plus symbol,
but you must add the android package namespace as follows:
android:id="@android:id/empty"
To create views and reference them from your app, you can use a
common pattern as follows:
1. Define a view in the layout file and assign it a unique ID, as in
the following example:
<Button android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/>
2. Create an instance of the view object and capture it from the
layout, typically in the onCreate() method, as shown in the
following example:
Button myButton = (Button) findViewById(R.id.my_button);

Layout parameters:
XML layout attributes named layout_something define layout
parameters for the View that are appropriate for the ViewGroup it
resides in.
Every ViewGroup class implements a nested class that
extends ViewGroup.LayoutParams. This subclass contains property
types that define the size and position of each child view, as
appropriate for the view group. As shown in Figure 2, the parent view
group defines layout parameters for each child view, including the
child view group.

All view groups include a width and height,


using layout_width and layout_height, and each view is required to
define them. Many LayoutParams include optional margins and
borders.
You can specify width and height with exact measurements, but you
might not want to do this often. More often, you use one of these
constants to set the width or height:
 wrap_content: tells your view to size itself to the dimensions
required by its content.
 match_parent: tells your view to become as big as its parent
view group allows
Common layouts
Each subclass of the ViewGroup class provides a unique way to
display the views you nest within it. The most flexible layout type,
and the one that provides the best tools for keeping your layout
hierarchy shallow, is ConstraintLayout.
The following are some of the common layout types built into the
Android platform.

Linear Layout

A layout that organizes its children into a single horizontal or vertical


row. It creates a scrollbar if the length of the window exceeds the
length of the screen.

Relative Layout
Enables you to specify the location of child objects relative to each
other (child A to the left of child B) or to the parent (aligned to the top
of the parent).

Web View

Displays web pages.


Building Layouts with an Adapter
When the content for your layout is dynamic or not pre-determined,
you can use a layout that subclasses AdapterView to populate the
layout with views at runtime. A subclass of the AdapterView class
uses an Adapter to bind data to its layout. The Adapter behaves as a
middleman between the data source and the AdapterView layout—
the Adapter retrieves the data (from a source such as an array or a
database query) and converts each entry into a view that can be added
into the AdapterView layout.
Common layouts backed by an adapter include:
List View

Displays a scrolling single column list.

Grid View

Displays a scrolling grid of columns and rows.

Android supports the following ViewGroups:


➤ LinearLayout
➤ AbsoluteLayout
➤ TableLayout
➤ RelativeLayout
➤ FrameLayout
➤ ScrollView

LINEAR LAYOUT:
In main.xml:

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


<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical/horizontal” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>

AbsoluteLayout
The AbsoluteLayout enables you to specify the exact location of its
children. Consider the
following UI defi ned in main.xml:
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
<Button
android:layout_width=”113dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”12px”
android:layout_y=”361px” />
</AbsoluteLayout>
TableLayout
The TableLayout groups views into rows and columns. You use the
<TableRow> element to designate
a row in the table. Each row can contain one or more views. Each
view you place within a row forms
a cell. The width of each column is determined by the largest width of
each cell in that column.
Consider the content of main.xml shown here:
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
<TableRow>
<TextView
android:text=”Password:”
/>
<EditText
android:id=”@+id/txtPassword”
android:password=”true”
/>
</TableRow>
<TableRow>
<TextView />
<CheckBox android:idd=”@+id/chkRememberPassword”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Remember Password”
/>
</TableRow>
<TableRow>
<Button
android:id=”@+id/buttonSignIn”
android:text=”Log In” />
</TableRow>
</TableLayout>

colors.xml
The colors.xml is an XML file that is used to store the colors for the
resources. An Android project contains 3 essential colors namely:

colorPrimary
colorPrimaryDark
colorAccent
These colors are used in some predefined resources of the Android
studio as well. These colors need to be set opaque otherwise it could
result in some exceptions to arise.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#1294c8</color>
<color name="colorPrimaryDark">#1294c8</color>
<color name="colorAccent">#FF4081</color>

<color name="text_color">#555555</color>

<color name="colorText">#FFFFFF</color>
<color name="colorTextHint">#51d8c7</color>
</resources>

dimens.xml
The dimens.xml is used for defining the dimensions for different
widgets to be included in the Android project. It is a good coding
practice to use dimens.xml to define a dimension rather than just
writing the dimension in the resource, due to the fact that if ever any
need arises to change the dimension, instead of making a change to
all, only the dimens.xml can be changed once and the change is
reflected in all.
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="nav_header_vertical_spacing">8dp</dimen>
<dimen name="nav_header_height">176dp</dimen>
<dimen name="fab_margin">16dp</dimen>
</resources>
styles.xml
Another important file in the values folder is the styles.xml where all
the themes of the Android project are defined. The base theme is
given by default having the option to customize or make changes to
the customized theme as well. Every theme has a parent attribute
which defines the base of the theme. There are a lot of options to
choose from depending on the need of the Android project.
<resources>
<!-- Base application theme. -->
<style name="AppTheme"
parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item
name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay"
parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay"
parent="ThemeOverlay.AppCompat.Light" />
</resources>

CONTENT PROVIDERS:

Content providers can help an application manage


access to data stored by itself, stored by other apps,
and provide a way to share data with other apps. They
encapsulate the data, and provide mechanisms for
defining data security. Content providers are the
standard interface that connects data in one process
with code running in another process.
two scenarios to use content providers:
1.to access an existing content provider in another app
2.create new content provider in your app to share data

Advantages:
1.control over data access permissions
2.to abstract the details of different data sources
3.CursorLoader object used to run asynchronous
querries,rely on content providers
Functions of content providers:
1.sharing access to your app data with other apps
2.sending data to a widget
3.return custom search suggestions using
SearchRecentSuggestionProvider framework
4.sychronizing app data with the server using
AbstractThreadedSyncAdapter
5.loading data using a Cursorloader

Accessing a provider:
1.A class that Extends ContentProvider
Public class A extends ContentProvider{
}
2.Content Provider object is to communicate with a
ContentResolver object which will provide all the
methods for data
storage(create,retrieve,update,delete)

3.content provider object will communicate with cursor


loader in UI(activity or fragment) via content resolver

Retrieve data from a provider:


1.read access permission for the provider
<uses-permission>
2.define the query and send it to the provider
Request read access permission
To retrieve data from a provider, your application needs
read access permission for the provider. You can't
request this permission at runtime. Instead, you have to
specify that you need this permission in your manifest,
using the <uses-permission> element and the exact
permission name defined by the provider.
Construct the query
The next step in retrieving data from a provider is to
construct a query. The following snippet defines some
variables for accessing the User Dictionary Provider:
4. Protect against malicious input
If the data managed by the content provider is in a SQL
database, including external untrusted data into raw
SQL statements can lead to SQL injection.
5. Display query results
The ContentResolver.query() client method always
returns a Cursor containing the columns specified by
the query's projection for the rows that match the
query's selection criteria. A Cursor object provides
random read access to the rows and columns it
contains.
Using Cursor methods, you can iterate over the rows in
the results, determine the data type of each column,
get the data out of a column, and examine other
properties of the results.
6. Get data from query results
In addition to displaying query results, you can use
them for other tasks. For example, you can retrieve
spellings from the User Dictionary Provider and then
look them up in other providers. To do this, you iterate
over the rows in the Cursor

Also,we can perform the Insert,Update,Delete


operations as above.
Insert data
To insert data into a provider, you call
the ContentResolver.insert()method. This method
inserts a new row into the provider and returns a
content URI for that row.
Update data
To update a row, you use a ContentValues object with
the updated values, just as you do with an insertion,
and selection criteria, as you do with a query. The client
method you use is ContentResolver.update(). You only
need to add values to the ContentValues object for
columns you're updating. If you want to clear the
contents of a column, set the value to the null.
Delete data
Deleting rows is similar to retrieving row data. You
specify selection criteria for the rows you want to
delete, and the client method returns the number of
deleted rows. The following snippet deletes rows whose
app ID matches "user". The method returns the number
of deleted rows.

Built in Content Providers:


Android provides some built-in content providers that
manage the data available through certain APIs or
system components. For example, the Contacts
Provider manages a database of contacts, and the
Calendar Provider manages a calendar database. Other
built-in content providers include MediaStore, which
manages media files such as audio and video, and
Settings, which manages system settings.
How to view and locate SQLite database in
Android Studio using device file explorer
is an open-source relational database that is used to
perform database operations on android devices such
as storing, manipulating, or retrieving persistent data
from the database.
Step by Step Procedures
Step 1: Open android studio project which has SQLite
database connection

Open existing android studio project which has


connected to SQLite database and already having some
saved records.
Step 2: Connect a device

Connect external device or emulator with android


studio make sure the name of the device must be
shown on android studio screen.
Step 3: Search for Device File Explorer in android studio

Device file explorer can be found in the bottom-right


corner of the android studio screen. Click on Device file
explorer.
Step 4: Search application package name

To search your package name go to data > data>


package name. Click on package name.
Step 5: Download the database
Now, select database and download database whose
extension will be .sqlite, for that right-click on the
database name and save file at any desired location
but remember the location then click on ok in Save As
dialog
Step 6: Download SQLite browser
Now to view the database we required SQLite browser,
you can download SQLite browser from
https://sqlitebrowser.org/dl/. Download a suitable SQLite
browser for your device from the above link and open
it.
Step 7: Search saved database file

Click on the open database this will open a dialog box


choose a database file. Now go to that location where
you have saved the database previously and then
select the database file and click on open.

INTENTS and INTENT FILTERS

An Intent is a messaging object you can use


to request an action from another app
component. Although intents facilitate
communication between components in
several ways, there are three fundamental
use cases:
 starting an activity:
u can start a new instance of an activity
by passing an intent to
startActivity(Intent).
 Starting a
service:Context.startService(Intent) or
Context.bindService(Intent,ServiceConne
ction,int)
 Delivering a broadcast:broadcastIntent
to send it to any BroadcastReceiver

public class Intent


extends Object implements Parcelable,
Cloneable

Structure:
Two pieces of info(primary):
o Action: string
o Data:on which the action to be
performed(Uri==MIME type)
o Category:string addCategory()
o Type
o Component(optional but critical for
explicit):ComponentNamesetComp
onent(),setClass()
o Extras:putExtra(key,value)/Bundle
using putextras()
o Flags:setFlags()

Eg:-for explicit:

Intent i=new
Intent(this,DownloadService.class);
i.setData(Uri.parse(fileUri));
startService(i);
startActivity(i);
eg:-for implicit
ACTION_SEND
Activity c:
Intent i=new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT,textMe
ssage);
i.setType(“text/plain”);
startActivity(i);

Two types:-
Explicit intents,Implicit intents
EXPLICIT INTENT(do not carry the class
name specifications for identifying the app
of the component)
Explicit intents are communicated between
two activities inside the same application.
We can use explicit intents when we need to
move from one activity to another activity.
Example:- when a user wants to start a
service to download a file or when a new
activity gets started in response to a user
action.
//Explicit Intent
Intent send = new Intent(FirstActivtiy.this,
SecondActivity.class);
//Starts TargetActivity
startActivity(send);
implicit intents: IMPLICIT INTENT(carry class
name specifications)
Implicit intent is communicated between
two activities of different application. One
thing to note here is we should not name a
specific component. In place of that we can
declare a general action to perform which
allows a component from another app to
handle it.
Example:- To show the user a location on a
map, we can use an implicit intent.
//Implicit intent
Intent intent = new Intent();

intent.setAction(android.content.Intent.ACTI
ON_VIEW);
intent.setData(Contract.Contacts.CONTENT_
URL);

startActivity(intent);
They do not specify any component name.
Receiving an implicit intent:
to receive an intent,declare one or more intent filters
for each of your app components in your apps manifest
file with <intent-filter> tag. 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. An app
component should declare separate filters for each
unique job it can do.
For example, one activity in an image gallery app may
have two filters: one filter to view an image, and
another filter to edit an image. When the activity starts,
it inspects the Intent and decides how to behave based
on the information in the Intent (such as to show the
editor controls or not).
Each intent filter is defined by an <intent-filter>
element in the app's manifest file, nested in the
corresponding app component (such as an <activity>
element). Inside the <intent-filter>, you can specify the
type of intents to accept using one or more of these
three elements:
:

<action>
Declares the intent action accepted, in the name
attribute. The value must be the literal string value of
an action, not the class constant.
<data>
Declares the type of data accepted, using one or more
attributes that specify various aspects of the data URI
(scheme, host, port, path) and MIME type.
<category>
Declares the intent category accepted, in the name
attribute. The value must be the literal string value of
an action, not the class constant.
For example, here's an activity declaration with an
intent filter to receive an ACTION_SEND intent when the
data type is text:
<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>
<intent-filter>
<action
android:name="android.intent.action.EDIT"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
<intent-filter>
<action
android:name="android.intent.action.DELETE"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>

</activity>
An implicit intent is tested against a filter by comparing
the intent to each of the three elements. To be
delivered to the component, the intent must pass all
three tests. If it fails to match even one of them, the
Android system won't deliver the intent to the
component.

LINKING ACTIVITIES USING INTENTS:


An Android application can contain zero or more
activities. When your application has more than
one activity, you often need to navigate from one to
another. In Android, you navigate between
activities through what is known as an intent.
The best way to understand this very important but
somewhat abstract concept in Android is to
experience it first hand and see what it helps you to
achieve.
how to add another activity to an existing project and
then navigate between the two activities.
Linking Activities with Intents
4. Add the following statements in bold to the
AndroidManifest.xml fi le:
<?xml version=”1.0” encoding=”utf-8”?>
<manifest
xmlns:android=”http://schemas.android.com/apk/res/an
droid”
package=”net.learn2develop.UsingIntent”
android:versionCode=”1”
android:versionName=”1.0” >
<uses-sdk android:minSdkVersion=”14” />
<application
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name” >
<activity
android:label=”@string/app_name”
android:name=”.UsingIntentActivity” >
<intent-filter >
<action
android:name=”android.intent.action.MAIN” />
<category
android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
<intent-filter>
<action
android:name="android.intent.action.VIEW"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>

</activity>
<activity
android:label=”Second Activity”
android:name=”.SecondActivity” >
<intent-filter >
<action
android:name=”net.learn2develop.SecondActivity” />
<category
android:name=”android.intent.category.DEFAULT” />
</intent-filter>
</activity>
</application>
</manifest>
5. Make a copy of the main.xml fi le (in the res/layout
folder) by right-clicking on it and selecting Copy.
Then, right-click on the res/layout folder and select
Paste.
Name the fi le. The res/layout
folder will now contain the fi le

6. Modify the fi le as follows:


<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/an
droid”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”This is the Second Activity!” />
</LinearLayout>
7. In the .java fi le, add the following statements in
bold:
package net.learn2develop.UsingIntent;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
}
8. Add the following lines in bold to the main.xml fi le:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/an
droid”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<Button
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Display second activity”
android:onClick=”onClick”/>

</LinearLayout>
9. Modify the .java fi le as shown in bold:
package net.learn2develop.UsingIntent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class SecondActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

public void onClick(View view) {


Intent i= new
Intent(“net.learn2develop.SecondActivity”));

startActivity(i)
}
}
.10.When the fi rst activity is loaded,
click the button and the second activity will now be
loaded .

You might also like