Chapter 5-Activity and Multimedia with Databases
Chapter 5-Activity and Multimedia with Databases
Intent:
“Android application components can connect to other Android
applications. This connection is based on a task description represented by
an Intent object.”
Intent is a messaging object you can use to request an action from another
app component.
Intent is a messaging object which passes between components like services,
content providers, activities etc. Normally startActivity() method is used for
invoking any activity.
1
3. Display web page
4. Display contact list
5. Message broadcasting
METHODS DESCRIPTION
Types of Intent:
There are following two types of intents supported by Android
1. Explicit Intents
2
Explicit intent going to be connected internal world of application, suppose if you
wants to connect one activity to another activity, we can do this quote by explicit
intent, below image is connecting first activity to second activity by clicking
button.
These intents designate the target component by its name and they are typically
used for application-internal messages - such as an activity starting a subordinate
service or launching a sister activity.
3
Java file name: This represents the name of the java file of the Activity you want
to open.
Note: You need to mention the java file name with .class extension
Step 2: Call startActivity() method and pass the intent's object as the parameter.
This method navigates to the java file mentioned in the Intent's object.
startActivity(i);
Step 3: If you need to pass some information or data to the new Activity you are
calling, you can do this by calling putExtra() method before the startActivity()
method. This method accepts key-value pair as its parameter.
i.putExtra("key1", "I am value1");
i.putExtra("key2", "I am value2");
startActivity(i);
Note: To receive the data in the new Activity and use it accordingly, you need to
call the getIntent() method and then getStringExtra() method in the java class of
the Activity you want to open through explicit intent. getStringExtra() method
takes the key as the parameter.
String a = getIntent().getStringExtra("key1");
Doing this, stores the value stored at key1 into the string variable a.
2. Implicit Intents
These intents do not name a target and the field for the component name is left
blank. Implicit intents are often used to activate components in other applications.
4
When you just have to tell what action you want to perform without worrying
which component will perform it, then you can use implicit intent.
Implicit intents do not name a specific component to perform a particular action,
but instead it declares a general action to be performed, which allows any
component, even from another app to handle it.
For example, if you want to show a specific location of the user on a map, you can
use an implicit intent to pass the coordinates through the intent and then any other
app, which is capable of showing the coordinates on a map will accept that intent.
5
Step 2: You need to provide some data for the action to be performed. Data is
typically expressed as a URI(Uniform Resource Identifier) which provides data
to the other app so that any other app which is capable of handling the URI data
can perform the desired action. For example, if you want to open a website through
your app, you can pass the Uri data using setData() method as follows:
i.setData(Uri.parse("http://www.google.co.in"));
Step 3: Call startActivity() method in the end with the intent object as the
parameter.
startActivity(i);
Intent filters
To inform the system which implicit intents they can handle, activities, services,
and broadcast receivers can have one or more intent filters. Each filter describes a
capability of the component, a set of intents that the component is willing to
receive. It, in effect, filters in intents of a desired type, while filtering out unwanted
intents — but only unwanted implicit intents (those that don't name a target class).
An explicit intent is always delivered to its target, no matter what it contains; the
filter is not consulted. But an implicit intent is delivered to a component only if it
can pass through one of the component's filters.
A component has separate filters for each job it can do, each face it can present to
the user. For example, the NoteEditor activity of the sample Note Pad application
has two filters — one for starting up with a specific note that the user can view or
6
edit, and another for starting with a new, blank note that the user can fill in and
save.
An intent filter is an instance of the IntentFilter class. However, since the Android
system must know about the capabilities of a component before it can launch that
component, intent filters are generally not set up in Java code, but in the
application's manifest file (AndroidManifest.xml) as <intent-filter> elements. (The
one exception would be filters for broadcast receivers that are registered
dynamically by calling Context.registerReceiver(); they are directly created as
IntentFilter objects.)
A filter has fields that parallel the action, data, and category fields of an Intent
object. An implicit intent is tested against the filter in all three areas. To be
delivered to the component that owns the filter, it must pass all three tests. If it fails
even one of them, the Android system won't deliver it to the component — at least
not on the basis of that filter. However, since a component can have multiple intent
filters, an intent that does not pass through one of a component's filters might make
it through on another.
Syntax:
7
1.<action>
syntax:
<action android:name="string" />
contained in:
<intent-filter>
description:
Adds an action to an intent filter. An <intent-filter> element must contain
one or more <action> elements. If there are no <action> elements in an
intent filter, the filter doesn't accept any Intent objects.
2. <category>
syntax:
<category android:name="string" />
contained in:
<intent-filter>
description:
3. <data>
syntax:
<data android:scheme="string"
android:host="string"
8
android:port="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />
contained in:
<intent-filter>
description:
Adds a data specification to an intent filter. The specification can be just a
data type (the mimeType attribute), just a URI, or both a data type and a
URI. A URI is specified by separate attributes for each of its parts:
<scheme>://<host>:<port>[<path>|<pathPrefix>|<pathPattern>]
These attributes that specify the URL format are optional, but also mutually
dependent:
If a scheme is not specified for the intent filter, all the other URI attributes
are ignored.
If a host is not specified for the filter, the port attribute and all the path
attributes are ignored.
All the <data> elements contained within the same <intent-filter> element
contribute to the same filter. So, for example, the following filter
specification,
<intent-filter . . . >
<data android:scheme="something" android:host="project.example.com"
/>
...
</intent-filter>
9
Fragments
10
And as the screen size of the Mobile devices are increasing, it makes
more sense to show more stuff at the same time on the screen, hence Fragments are
very useful, and are very popular amongst the Android developers community.
The usage of Fragment in an android app totally depends on the screen size of the
device on which the app is being used. If the screen size is big, then we can easily
show 2 or maybe more fragments on the screen, but if the display size is smaller, it
is advised to use Fragments in separate activities.
11
Main use of Fragments in Android
Following are the 3 main usage of Fragments in Android, for which Fragments
were introduced:
1. Modularity: If a single activity is having too many functional components,
its better to divide it into independent fragments, hence making the code
more organized and easier to maintain.
2. Reusability: If we define aany particular feature in a fragment, then that
feature more or less becomes a reusable component which can be easily
intgerated into any activity.
3. Adaptability: If we break UI components of an app screen into fragments,
then it becomes easier to change their orientation and placement, based on
screen size etc.
Types of Fragments
Basically fragments are divided as three stages as shown below.
Single frame fragments − Single frame fragments are using for hand hold
devices like mobiles, here we can show only one fragment as a view.
List fragments − fragments having special list view is called as list fragment
12
Fragments transaction − Using with fragment transaction. we can move one
fragment to another fragment.
13
Lifecycle Methods for Fragment
This is called when the fragment becomes active or interactive.
Method Name Description
onResume()
14
onStop() This method is called when the fragment is no longer
visible.
activity_main.xml
File: activity_main.xml
15
15. />
16.
17. <fragment
18. android:id="@+id/fragment2"
19. android:name="example.javatpoint.com.fragmentexample.Fragment2"
20. android:layout_width="0px"
21. android:layout_height="match_parent"
22. android:layout_weight="1"
23. />
24.
25. </LinearLayout>
File: fragment_fragment1.xml
1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:background="#F5F5DC"
6. tools:context="example.javatpoint.com.fragmentexample.Fragment1">
7.
8. <!-- TODO: Update blank fragment layout -->
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:text="@string/hello_blank_fragment" />
13.
14. </FrameLayout>
File: fragment_fragment2.xml
1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:background="#F0FFFF"
16
6. tools:context="example.javatpoint.com.fragmentexample.Fragment2">
7.
8. <!-- TODO: Update blank fragment layout -->
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:text="@string/hello_blank_fragment" />
13.
14. </FrameLayout>
MainActivity class
File: MainActivity.java
1. package example.javatpoint.com.fragmentexample;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }
File: Fragment1.java
1. package example.javatpoint.com.fragmentexample;
2. import android.os.Bundle;
3. import android.support.v4.app.Fragment;
4. import android.view.LayoutInflater;
5. import android.view.View;
6. import android.view.ViewGroup;
7.
17
8. public class Fragment1 extends Fragment {
9.
10. @Override
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_fragment1, container, false);
20. }
21. }
File: Fragment2.java
1. package example.javatpoint.com.fragmentexample;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class Fragment2 extends Fragment {
10.
11. @Override
12. public void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_fragment2, container, false);
18
21. }
22.
23. }
Output:
19
What is SQLite?
SQLite is an open-source, embedded, relational database management system,
designed circa 2000. It is a lightweight database, with zero configuration, no
requirements of a server or installation. Despite its simplicity, it is laden with
popular features of database management systems.
Key Features
SQLite is very lightweight (it is less than 500Kb size) compare to other
database management systems like SQL Server, or Oracle.
SQLite is not a client-server database management system. It is an in-
memory library that you can call and use directly. No installation and no
configuration required.
A typical SQLite database is contained on a single file on the computer disk
storage with all the database objects (tables, views, triggers, etc.) included in
that file. No dedicated server required.
20
the records there, and with only one query, you can select the records and
perform calculations.
When you need a database system for learning and training purposes,
SQLite is a good fit. As we explained earlier, no installation or configuration
is required. Copy the SQLite libraries in your computer, and you are ready to
learn.
Following guide will help you determine whether you should choose SQLite for
your next project
21
SQLite limitations and Unsupported Features
The following are the list of unsupported features and limitations in SQLite:
SQLite supports neither RIGHT OUTER JOIN nor FULL OUTER JOIN. It
supports only LEFT OUTER JOIN.
Limitations in ALTER table statement: with ALTER TABLE statement in
SQLite you can only add a column or rename a table (as we will see in the
following tutorials). However, you can't do the following:
o ALTER column.
o DROP a column.
o ADD a constraint.
VIEWs are read-only – you can't write INSERT, DELETE, or UPDATE
statements into the view. However, you can create a trigger on a view and do
the INSERT, DELETE, or UPDATE statements into it.
GRANT and REVOKE commands are not implemented in SQLite. There
are only normal file access permissions implemented in SQLite. This is
because SQLite reads and writes to the disk files, unlike other Database
management systems.
TRIGGERS – As we will see in the incoming tutorials, SQLite only
supports FOR EACH ROW triggers, and it doesn't support FOR EACH
STATEMENT triggers.
22
Differences between SQL and SQLite
SQL SQLite
23
provide a lot of functionalities.
Database - Package
The main package is android.database.sqlite that contains the classes to manage
your own databases
Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase
with your database name and mode as a parameter. It returns an instance of SQLite
database which you have to receive in your own object.Its syntax is given below
Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Table name (Username
VARCHAR,Password VARCHAR);");\
Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call
a method of this class called rawQuery and it will return a resultset with the cursor
pointing to the table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
24
resultSet.moveToFirst();
1
getColumnCount()
This method return the total number of columns of the table.
2
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column
3
getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column
4
getColumnNames()
This method returns the array of all the column names of the table.
5
getCount()
This method returns the total number of rows in the cursor
6
getPosition()
This method returns the current position of the cursor in the table
25
7
isClosed()
This method returns true if the cursor is closed and return false otherwise
}
}
26
Android AsyncTask
AsyncTask is an abstract class which means that the class extending it need to implement
the below mentioned methods and also since the class is generic type the class extending it
should specify these 3 generic types.These are explained below:-
2. Progress → The progress which is used to publish the progress on the main
UI thread.
3. Result → The result which is obtained after the background thread has
finished execution.
AsyncTask is basically used to reduce the load of tasks off the UI thread. It creates a
background thread to perform an operation like that of fetching results from the Internet or
loading data from the database, etc. and then publish the results to the main UI thread.
USAGE:It should generally be used for short operations which should ideally be finished
in a matter of few seconds.
27
Methods of AsyncTask.
1. onPreExecute() --> This method is invoked just before the background
thread is created and here we can do some initialisation that we might
want to do before the background thread starts the task.
It is used to basically setup a task. Ex: showing a Progress Bar,etc.
It runs on the main UI thread.
28
result can be then be used to do anything the developer wants to do with
that result.
It runs on the main UI thread.
The main disadvantage of using an AsyncTask and why they should rarely be
used… (Limitations)
1. Block the main UI thread → one reason for this is the same as mentioned above that
it can block the UI thread thereby freezing the app.
2. Wastage of memory →The creation of another AsyncTask can not only happen
through refresh button but a rather more general and practical example is suppose an
AsyncTask is already running and the user rotates the screen, then another Activity
will created and the former activity will go to the Stopped State and since there is a
completely new Activity a new AsyncTask is created and a new background thread is
29
created and then suppose the user again rotates the screen before the task is
completed, then another AsyncTask is created with a new background thread, and it
can happen again and again creating multiple number of AsyncTasks in the memory
thereby creating a large number of AsyncTask objects is created in the memory which
in turn, wastes a lot of memory and since memory is a very precious resource in
Android and should be used as efficiently as possible, it is not at all recommended.
And if this scenario happens again & again than Android OS will have no coice but to
forcefully destroy your Activity which you definitely do not want to happen.
3. Can lead to Memory Leaks → If the user rotates the screen another AsyncTask is
created and as you know that the previous AsyncTask did not finish executing. Now,
after the 1st AsyncTask completes with the 2nd Activity in the foreground then that
AsyncTask will try to return the result to the onPostExecute() method of an Activity
which does not exist and hence it leads to memory leaks.
Broadcast Receiver:
Definition
A broadcast receiver (receiver) is an Android component which allows
you to register for system or application events. All registered receivers for an event
are notified by the Android runtime once this event happens.
Implementation
A receiver can be registered via the AndroidManifest.xml file.
Alternatively to this static registration, you can also register a receiver dynamically
via the Context.registerReceiver() method.
30
If the event for which the broadcast receiver has registered happens, the onReceive()
method of the receiver is called by the Android system.
When a broadcast message arrives for the receiver, Android calls its onReceive() method
and passes it the Intent object containing the message. The broadcast receiver is
considered to be active only while it is executing this method. When onReceive() returns,
it is inactive.
A process with an active broadcast receiver is protected from being killed. But a process
with only inactive components can be killed by the system at any time, when the memory
it consumes is needed by other processes.
This presents a problem when the response to a broadcast message is time consuming
and, therefore, something that should be done in a separate thread, away from the main
thread where other components of the user interface run. If onReceive() spawns the
thread and then returns, the entire process, including the new thread, is judged to be
inactive (unless other application components are active in the process), putting it in
jeopardy of being killed. The solution to this problem is for onReceive() to start a service
and let the service do the job, so the system knows that there is still active work being
done in the process.
System broadcasts
Several system events are defined as final static fields in the Intent class. Other Android
system classes also define events, e.g., the TelephonyManager defines events for the
change of the phone state.
31
Event Description
32