Professional Documents
Culture Documents
MAD-unit 2,3,4
MAD-unit 2,3,4
Introduction to Android
Android is an operating system which is based on the Linux kernel. Android
system is also called as Android Open Source Project (AOSP), lead by
Google. Android is used for mobile devices, such as smart phones and tablet
computers. The Android application makes life more comfortable and
advanced for the users.
Features of Android
pg. 1
Android Version Description
Android 1.6 Donut This version comes in all shapes and sizes. It allows Android to run on a variety of
IMPORTANT NOTES
screen resolutions Mobile
and aspect ratios.
Application Development
It has a quick search box that searches the result from the web, from your phone's
local content all at once from a single box on the home screen.
Android 2.1 Eclair This version provides Google map navigation. For example, in car navigation
system, a forward looking 3D view, voice guidance and traffic information all for
free.
Android 2.2 Froyo This version provides voice capabilities which let you perform key functions on your
phone like searching, getting directions, making notes, setting alarms and more with
just the sound of your voice.
It provides portable Wi-Fi hotspot into your phone where you could stay connected
even when on the go.
Android 2.3 This version provides gaming APIs. It builds rich, graphics-intensive 3D games. This
Gingerbread version introduces NFC (Near Field Communication) which supports to transmit the
information between devices just by bringing them close together.
This version displays how much battery of your device has been consumed, allows
you to adjust the screen brightness, find out the active applications.
Android 3.0 This version introduces tablet-friendly design with a larger layout pattern. It
Honeycomb enhances the experience of reading books, watching videos, exploring maps and
more.
It provides a new system bar which is enabled on-screen navigation that controls
your Android device. This version gives rights to the user to access essential
information easily like time, date, battery life and connection status of your device
all in one place.
Android 4.0 Ice This version provides Widgets which embed live app content directly on your home
Cream Sandwich screen that becomes more flexible to customize the home screen.
It manages the network data usage. It tracks how much data you used, set warning
levels and hard limits and disable your service if you reach the limit.
Android 4.1 Jelly This version provides actionable notifications which take action directly from the
Bean notification.
Android 4.4 KitKat This version helps to get the things done without touching the mobile screen, just
with the sound of your voice – just say “OK Google” to launch voice search, send a
pg. 2
text, get directions or even play a song.
IMPORTANT NOTES
Mobile Application Development
History of Android
Advantages of Android
Disadvantages of Android
pg. 3
IMPORTANT NOTES
Mobile Application Development
1. Activities
Activity is also known as Widgets.
Activity represents a single screen with a user interface.
It is an individual user interface screen in an Android Application
where visual elements called Views.
It interacts with the user to do only one thing, such as unlock screen,
dial a phone, etc.
If new activity starts, then previous activity is stopped, but the data is
preserved.
An application consists of multiple activities.
For example, an email application has one activity to display a list of
new emails, another activity is to compose email, reading email and
so on.
2. Services
Services performs the action without user interaction in the
background, but does not get initiated without user invocation.
It does not require a user interface.
It is an android application component which runs in a background and
has no visual UI.
It is used to perform the processing part of your application in the
background.
For example, music player application. When the music station is
playing the song, the user can open another application and the song
plays in the background.
3. Content Providers
Content providers are the android application component that provide
a flexible way to make data available across applications.
pg. 4
IMPORTANT NOTES
Mobile Application Development
Android Architecture:-
Android architecture is a stack of software components. It is in the form of a
software application, operating system, run-time environment, middleware,
native libraries and services.
Each part of the stack and the elements within each layer are integrated and
provide optimal application development and execution environment for
mobile devices.
pg. 5
IMPORTANT NOTES
Mobile Application Development
1. Linux Kernel
Linux is the heart of Android architecture.
It provides a level of abstraction between the hardware devices and
the upper layers of the Android software stack.
The Android operating system is based on the Linux kernel.
The Linux kernel is responsible for various device drivers such as
Camera driver, Display driver, Bluetooth driver, Keypad driver,
Memory management, Process management, Power management,
etc.
2. Native Libraries
The native libraries such as Media, WebKit, SQLite, OpenGL, FreeType,
C Runtime library (libc) etc. are situated on the top of a Linux kernel.
Media library is responsible for playing and recording audio and video
formats, FreeType is for font support, WebKit is for browser support,
SQLite is for database, SSL is for Internet security etc.
3. Android Runtime
Android Runtime is the third section of the architecture and situated
on the second layer from the bottom.
Android Runtime includes core libraries and Dalvik Virtual Machine
(DVM) which is responsible to run android application.
Dalvik Virtual Machine (DVM) is like Java Virtual Machine (JVM) in
Java, but DVM is optimized for mobile Devices.
pg. 6
IMPORTANT NOTES
Mobile Application Development
DVM makes use of the Linux core features like memory management
and multi-threading, which are essential in the Java language.
DVM provides fast performance and consumes less memory.
4. Application Framework
Application framework is situated on the top of the Native libraries and
Android runtime.
Android framework provides a lot of classes and interfaces for Android
application development and higher level services to the applications
in the form of Java classes.
It includes Android API's such as Activity manager, Window manager,
Content Provider, Telephony Manager, etc.
Activity manger is responsible for controlling all the aspects of the
application lifecycle and activity stack, Content provider is responsible
for allowing the applications to publish and share the data with the
other applications, View system is responsible for creating application
user interfaces, etc.
5. Applications
Applications are situated on the top of the Application framework.
The applications such as Home, Contact, Alarm, Calender, Camera,
Browsers, etc. use the Android framework which uses Android runtime
and libraries. Android runtime and Native libraries use Linux kernel.
The user can write his/her application to be installed on this layer only.
pg. 7
IMPORTANT NOTES
Mobile Application Development
pg. 8
IMPORTANT NOTES
Mobile Application Development
1. OnCreate()
2. OnStart()
3. OnResume()
4. OnPause()
5. OnStop()
6. OnRestart()
7. OnDestroy()
Activity Description
Methods
OnCreate() This method is called when activity is created. It is used to initialize the activity.
It takes a 'Bundle' parameter which is used for storing and passing state information
and objects between activities.
OnStart() This method is called when activity becomes visible to the user.
OnResume() This method is called when activity will start interacting with the user.
OnPause() This method is called when current activity is being paused and the previous activity is
being resumed.
Activity is not destroyed and not visible to the user. It is used to release resources or
save application data.
OnStop() This method is called when activity is no longer visible to the user.
OnRestart() This method is called after your activity has stopped and restarting.
pg. 9
IMPORTANT NOTES
Mobile Application Development
States of an Activity
Activity Description
State
Running This state defines that the activity is visible and interacts with the user.
Paused This state defines that the activity is still visible but partially hidden and the instance is
running but might be killed by the system.
Stopped This state defines that the activity is not visible and the instance is running but might be
killed by the system.
Killed This state defines that the activity has been terminated by the system call to its finish()
method.
After installing all the plug-ins for an Android file, you can begin to develop
an Android application.
Android uses packages not only to arrange the code in an application but to
manage the application themselves.
pg. 10
IMPORTANT NOTES
Mobile Application Development
pg. 11
IMPORTANT NOTES
Mobile Application Development
pg. 12
Folder Name Description
res The 'res' stands for Resource file. It can store resource files such as pictures,
XML files, etc. It contains some additional folders such as Drawable, Layout and
Values.
anim: It is used for XML files that are compiled into animation objects.
color: It is used for XML files that describe colors.
drawable: It is used to store various graphics files. In Android project structure,
The above drawable folders are required in order to adapt to different screen
resolutions.
layout: It is used for placing the XML layout files, which defines how various
Android objects such as textbox, buttons, etc. are organized on the screen.
menu: It is used for defining the XML files in the application menu.
raw: The 'raw' stands for Raw Asset Files. These files are referenced from the
application using a resource identifier in the R class.
For example, good place for media is MP3 or Ogg files.
values: It is used for XML files which stores various string values, such as titles,
labels, etc.
AndroidManifest.xm This file indicates the Android definition file. This file contains the information
l about the Android application such as minimum Android version, permission to
access Android device capabilities such as Internet access permission, phone
permission etc.
default.properties This file contains the project settings, such as build the target. Do not edit this file
manually. It should be maintained in a Source Revision Control System.
Proguard.cfg This file defines how ProGuard optimizes and makes your code unclear.
MainLayout.xml This file describes the layout of the page. So all the components such as
textboxes, labels, radio buttons, etc. are displaying on the application screen.
Activity class
pg. 13 The application occupies the entire device screen which needs at least one class
inherits from the Activity class. OnCreate() method initiates the application and
loads the layout page.
IMPORTANT NOTES
Mobile Application Development
What is SQLite?
SQLite is an open source database. It supports standard relational database
features like SQL syntax, transactions, prepared statement, etc. It has
methods to create, delete, execute SQL commands and perform other
common database management tasks.
Datatype Description
SQLite in Android
Package The android.database.sqlite is the main package in Android SQLite which contains
the classes to manage your own databases.
pg. 14
IMPORTANT NOTES
Mobile Application Development
Creation The openOrCreateDatabase() method is called for creating a database with your
database name and mode as a parameter.
This method returns an instance of SQLite database.
Syntax
SQLiteDatabse mydatabase = openOrCreateDatabase (“database_name”,
MODE_PRIVATE, null);
Insertion The execSQL() method is used to insert the data into table. This method is defined
in SQLiteDatabse class.
Syntax:
execSQL(String SQL, Object[] bind Args)
The execSQL() method is used not only to insert a data, but also to update or
modify the existing data in database, using bind arguments.
Example:
Fetching An object of the Cursor class is used to fetch the data from the database. Calling a
method of Cursor class is called rawQuery which returns a resultset with the
cursor pointing to the table.
The rawQuery() accepts an SQL SELECT statement as an input.
Example:
resultset.moveToFirst();
SQLiteOpenHelper This class is used for creating a database and version management.
Class
In this class, there are two methods which need to override for creating and
updating the database, they are onCreate() and onUpgrade().
If the database is accessed but not yet created then onCreate() method is called
by the framework.
pg. 15
IMPORTANT NOTES
Mobile Application Development
Internal storage helps users to save or read their data from the device
Internal memory. The FileInputStream and FileOutputStream classes are
used to read and write data into the file.
A. Write Operation
The openFileOutput() method is called for writing the data in the file using
Internal storage. It takes two parameters. First parameter is the file name
and second one is file mode.
Syntax:
FileOutputStreamfopStream = openFileOutput(“file_name”, MODE_PRIVATE);
pg. 16
IMPORTANT NOTES
Mobile Application Development
Example
B. Read Operation
The openFileInput() method is called for reading the data from file with the
name of the file. It takes one parameter as file name. The file name should
be same as you have written in the openFileOutput() method. It returns an
instance of FileInputStream class.
Example
1. Shared Preference
2. Internal Storage
pg. 17
IMPORTANT NOTES
Mobile Application Development
3. External Storage
4. SQLite Database
pg. 18
IMPORTANT NOTES
Mobile Application Development
5. Network Connection
Network Connection is used to store the data on the web with your
own network server.
The user can use the network connection when it's available to store
and retrieve the data on your own web-based services.
Write Operation
pg. 19
IMPORTANT NOTES
Mobile Application Development
Following are the Event Handlers and Event Listeners that handle the
user's interaction with interactive components of Application
pg. 20
IMPORTANT NOTES
Mobile Application Development
smoother view. Hence, the android developers must know the important terminologies
before developing the app. In Android Programming we generally come across the
word Context. So what exactly is this Context and why is it so important? To answer
this question let’s first see what the literal meaning of Context is:
The Circumstances that form the setting for an Event, Statement, or Idea, and in terms
of which it can be fully understood.
Looking at this definition we come across two things:
The Context tells us about the surrounding information.
It is very important to understand the environment which we want to
understand.
Similarly when we talk about Android Programming Context can be understood as
something which gives us the Context of the current state of our application.
It allows us to access resources.
It allows us to interact with other Android components by sending
messages.
It gives you information about your app environment.
The code has been given in both Java and Kotlin Programming Language
for Android.
Understanding Context by a Real World Example
Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a
suitable time. Except for these things there are also many other things, he
wants to do during his time of stay. So how does he get these things? He will
ask the room-service person to bring these things for him. Right? So here
the room-service person is the Context considering you are the single
activity and the hotel to be your app, finally, the breakfast, lunch &
dinner have to be the resources.
How Does this Work?
1. It is the Context of the current/active state of the application.
Usually, the app got multiple screens like display/inquiry/add/delete
screens(A general requirement of a basic app). So when the user is
searching for something, the Context is an inquiry screen in this case.
2. It is used to get information about the activity and application.
The inquiry screen’s Context specifies that the user is in inquiry activity, and
he/she can submit queries related to the app
3. It is used to get access to resources, databases, shared preferences,
etc.
Via Rest services, API calls can be consumed in android apps. Rest
Services usually hold database data and provide the output in JSON format
to the android app. The Context for the respective screen helps to get hold of
database data and the shared data across screens
pg. 21
IMPORTANT NOTES
Mobile Application Development
4. Both the Activity and Application classes extend the Context class.
In android, Context is the main important concept and the wrong usage of it
leads to memory leakage. Activity refers to an individual screen and
Application refers to the whole app and both extend the Context class.
The Overall view of the App hierarchy looks like the following:
It can be seen in the above image that in “Sample Application”, the nearest
Context is Application Context. In “Activity1” and “Activity2”, both Activity
Context (Here it is Activity1 Context for Activity1 and Activity2 Context for
Activity2) and Application Context.The nearest Context to both is their
Activity Context only.
Application Context
This Context is tied to the Lifecycle of an Application. Mainly it is an
instance that is a singleton and can be accessed
via getApplicationContext().
pg. 22
IMPORTANT NOTES
Mobile Application Development
Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.
Services
2
They handle background processing associated with an application.
Broadcast Receivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.
Activities
An activity represents a single screen with a user interface,in-short Activity performs actions
on the screen. For example, an email application might have one activity that shows a list of
new emails, another activity to compose an email, and another activity for reading emails. If
an application has more than one activity, then one of them should be marked as the activity
that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows −
public class MainActivity extends Activity {
}
Services
A service is a component that runs in the background to perform long-running operations. For
example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.
pg. 23
IMPORTANT NOTES
Mobile Application Development
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system. For example, applications can also initiate broadcasts to let other applications
know that some data has been downloaded to the device and is available for them to use, so
this is broadcast receiver who will intercept this communication and will initiate appropriate
action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcaster as an Intent object.
public class MyReceiver extends BroadcastReceiver {
public void onReceive(context,intent){}
}
Content Providers
A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. The data may be stored in
the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider {
public void onCreate(){}
}
We will go through these tags in detail while covering application components in individual
chapters.
Additional Components
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are −
Fragments
1
Represents a portion of user interface in an Activity.
2 Views
pg. 24
IMPORTANT NOTES
Mobile Application Development
UI elements that are drawn on-screen including buttons, lists forms etc.
Layouts
3
View hierarchies that control screen format and appearance of the views.
Intents
4
Messages wiring components together.
Resources
5
External elements, such as strings, constants and drawable pictures.
Manifest
6 Configuration file for the application.
Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.
pg. 25
IMPORTANT NOTES
Mobile Application Development
1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides
information of available components provided by the system that is to be invoked.
For example, you may write the following code to view the webpage.
pg. 26
IMPORTANT NOTES
Mobile Application Development
application that makes user interaction better with the view components.
Android provides us a huge range of UI controls of many types such as
buttons, text views, etc.
TextView
EditText
Button
ImageButton
ToggleButton
RadioButton
RadioGroup
CheckBox
AutoCompleteTextView
ProgressBar
Spinner
TimePicker
DatePicker
SeekBar
AlertDialog
Switch
RatingBar
Android UI Controls
pg. 27
IMPORTANT NOTES
Mobile Application Development
1. TextView
TextView is a UI Component that displays the text to the user on their
Display Screen.
XML file:
For this, we declare it in the layout tag as follows:
<TextView
//attributes to describe it
/>
</LinearLayout>
Activity file:
In this, we declare it using the setText() method as follows:
setContentView(R.layout.activity_main);
pg. 28
IMPORTANT NOTES
Mobile Application Development
linearLayout.addView(textView);
There are various attributes to describe the TextView some of them are
named below:
2. EditText
EditText is a user interface control that allows the users to enter some text.
XML file:
For this, we declare it in the layout tag as follows:
<EditText
//attributes
>
</LinearLayout>
Activity file:
In activity, we declare it using the getText() method as follows:
setContentView(R.layout.activity_main);
edittext_name.setHint(“Hello I am EditText”);
linearLayout.addView(edittext_name);
pg. 29
IMPORTANT NOTES
Mobile Application Development
3. Button
This is a UI that is used to perform some action as soon as the user clicks on
it.
XML file:
For this, we declare it in the layout tag as follows:
<Button
//attributes
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
setContentView(R.layout.activity_main);
btn_name.setText(“Hello I am Button”);
linearLayout.addView(btn_name);
4. ImageButton
It is the same as a Button but it’s used to display an image on the button to
perform an Action. In this, we need to give the source of the image so that
the system can load it.
XML file:
For this, we declare it in the layout tag as follows:
<ImageButton
pg. 30
IMPORTANT NOTES
Mobile Application Development
//other attributes...
android:src= “@drawable/add_icon”/>
</LinearLayout>
Activity file:
In the activity file, we declare it programmatically as below:
setContentView(R.layout.activity_main);
btn_name.setImageResource(R.drawable.add_icon);
linearLayout.addView(btn_name);
5. ToggleButton
The toggle button displays the ON/OFF states of a button with a light
indicator.
XML file:
For this, we declare it in the layout tag as follows:
<ToggleButton
//attributes
android:checked="true"
android:textOff="OFF"
android:textOn="ON"/>
</LinearLayout>
Activity file:
In the activity file we declare it programmatically as below:
setContentView(R.layout.activity_main);
pg. 31
IMPORTANT NOTES
Mobile Application Development
tb_name.setTextOff("OFF");
tb_name.setTextOn("ON");
tb_name.setChecked(true);
linearLayout.addView(btn_name);
6. RadioButton
Radio button in Android is the one that has only two possible states, that
are either checked or unchecked. Initially, it is in the unchecked state, once
it’s checked it can’t be unchecked.
XML file:
For this, we declare it in the layout tag as follows:
<RadioButton
android:text="Radio button"
android:checked="true"/>
</LinearLayout>
Activity file:
In the activity file, we declare it programmatically as below:
setContentView(R.layout.activity_main);
btn_name.setText("Hello");
btn_name.setChecked(true);
linearLayout.addView(btn_name);
pg. 32
IMPORTANT NOTES
Mobile Application Development
7. RadioGroup
It’s a group of Radio buttons that are alike. In this, only one of all the
buttons can be chosen.
XML file:
For this, we declare it in the layout tag as follows:
<RadioGroup android:orientation="vertical">
</RadioGroup>
</LinearLayout>
Activity file:
In the activity file, we declare it programmatically as below:
RadioButton rdb1,rdb2,rdb3;
@override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rdb1 = (RadioButton)findViewById(R.id.rdb_1);
rdb2 = (RadioButton)findViewById(R.id.rdb_2);
rdb3 = (RadioButton)findViewById(R.id.rdb_3);
pg. 33
IMPORTANT NOTES
Mobile Application Development
8. CheckBox
A CheckBox is the UI control that has two states that are either checked or
unchecked. If we have a group of CheckBox, we can select as many as we
want, unlike RadioGroup.
XML file:
For this, we declare it in the layout tag as follows:
<CheckBox
android:checked="true"
android:text="CheckBox"
// other attributes
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
setContentView(R.layout.activity_main);
cb_name.setText("DataFlair");
cb_name.setChecked(true);
layout.addView(cb_name);
9. ProgressBar
In Android, we have a progress bar that shows the progress of some action
that is happening like pasting a file to some location. A progress bar can be
in two modes:
Determinate Mode:
pg. 34
IMPORTANT NOTES
Mobile Application Development
In this, the progress is shown with the percent of action completed. Also,
the time to be taken is already determined.
Indeterminate Mode:
In this, there is no idea of when the task would be completed, therefore, it
functions continuously.
XML file:
For this, we declare it in the layout tag as follows:
<ProgressBar
/>
</LinearLayout>
Activity file:
In activity, we declare it programmatically as below:
setContentView(R.layout.activity_main);
pgsBar = (ProgressBar)findViewById(R.id.pBar);
txtView = (TextView)findViewById(R.id.tView);
Here we need to set the sleep time and override the onClick() and
onCreate() methods
The above were some of the very important UI controls, now we will also
read about some more UI controls :
1. Spinner
The Spinner in Android is a User Interface that is used to select a particular
option from a list of given options. Spinner in Android is the same as
dropdown in HTML. It provides us with a faster way to select an option of
our choice. When we click on the down arrow, it shows a list of values from
pg. 35
IMPORTANT NOTES
Mobile Application Development
which we can select one. By default, the first value would be shown as the
currently selected Value.
2. TimePicker
Time picker is a UI component that works as an intermediate to select a
time of the day. The time chosen by it is shown either in 24 hrs format or in
12hrs format using AM and PM.
It gives a virtual Clock/watch to select it. This virtual clock makes it easy to
choose the time.
3. DatePicker
Like we have time picker, we have a date picker as UI control too. In this,
the System shows a virtual calendar to the users to choose the day.
This enables the user to choose a particular date using either a calendar or a
dropdown. These both are made to make it easier for the user to pick up a
date and a time.
4. SeekBar
In Android, Seekbar is an extended Progress bar. A seekbar comes with a
pointer that is draggable throughout the bar either in left or right. This
pointer helps to set the progress as well. This helps the user to choose a
particular range of values.
5. RatingBar
A rating bar in Android is an extended version of a seekbar. It is used to
give the rating by touching it. In the rating bar, a user can rate at a scale of 5
with a difference of 0.5.
pg. 36
IMPORTANT NOTES
Mobile Application Development
6. AlertDialog
Alert Dialog Box is a UI that gives the users an Alert or Warning of
something. It appears on the screen in a small window. Once it comes, the
user needs to decide or choose an option that it shows.
For example, when you enter the wrong password for email id.
7. Switch
In Android, a switch is a two-state UI element that holds either ON or OFF
state. ON generally means Yes and OFF means No. By default, a switch is in
the OFF state. A user can change its state many times.
8. AutoCompleteTextView
AutoCompleteTextView is an extension of EditText. In this UI element, the
user is provided with a few suggestions of some values/texts. The value can
be chosen by the user while filling AutoCompleteTextView.
Android UI Layouts
Android Layout is used to define the user interface that holds the UI controls or
widgets that will appear on the screen of an android application or activity screen.
Generally, every application is a combination of View and ViewGroup. As we know,
an android application contains a large number of activities and we can say each
activity is one page of the application. So, each activity contains multiple user
interface components and those components are the instances of the View and
ViewGroup. All the elements in a layout are built using a hierarchy
of View and ViewGroup objects.
View
pg. 37
IMPORTANT NOTES
Mobile Application Development
View
A ViewGroup act as a base class for layouts and layouts parameters that hold other
Views or ViewGroups and to define the layout properties. They are Generally Called
layouts.
ViewGroup
The Android framework will allow us to use UI elements or widgets in two ways:
Use UI elements in the XML file
Create elements in the Kotlin file dynamically
pg. 38
IMPORTANT NOTES
Mobile Application Development
android:layout_marginTop Used to declare the extra space used in the top side
pg. 39
IMPORTANT NOTES
Mobile Application Development
Here, we are going to see two examples of option menus. First, the simple option
menus and second, options menus with images.
pg. 40
IMPORTANT NOTES
Mobile Application Development
Andorid Toast can be used to display information for the short period of time. A
toast contains message to be displayed quickly and disappears after sometime.
You can also create custom toast as well for example toast displaying image. You can
visit next page to see the code for custom toast.
Toast class
Toast class is used to show notification for a particular interval of time. After
sometime it disappears. It doesn't block the user interaction.
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
Method Description
pg. 41
IMPORTANT NOTES
Mobile Application Development
public static Toast makeText(Context context, CharSequence makes the toast containing text and
text, int duration) duration.
public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.
Android AlertDialog can be used to display the dialog message with OK and Cancel
buttons. It can be used to interrupt and ask the user about his/her choice to continue
or discontinue.
Android AlertDialog is composed of three regions: title, content area and action
buttons.
public AlertDialog.Builder setTitle(CharSequence) This method is used to set the title of AlertDialog.
pg. 42
IMPORTANT NOTES
Mobile Application Development
public AlertDialog.Builder setIcon(int) This method is used to set the icon over
AlertDialog.
Android Service
pg. 43
IMPORTANT NOTES
Mobile Application Development
Play Video
1. Started
2. Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now it
runs in the background indefinitely. It is stopped by stopService() method. The
service can stop itself by calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method.
The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.
pg. 44
IMPORTANT NOTES
Mobile Application Development
Suppose, I want to play music in the background, so call startService() method. But I
want to get information of the current song being played, I will bind the service that
provides information about the current song.
pg. 45
IMPORTANT NOTES
Mobile Application Development
Android SQLite
SQLite is an open-source relational database i.e. used to perform database
operations on android devices such as storing, manipulating or retrieving persistent
data from the database.
Here, we are going to see the example of sqlite to store and fetch the data. Data is
displayed in the logcat. For displaying data on the spinner or listview, move to the
next page.
pg. 46
IMPORTANT NOTES
Mobile Application Development
SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used for database creation
and version management. For performing any database operation, you have to
provide the implementation of onCreate() and onUpgrade() methods of
SQLiteOpenHelper class.
Constructor Description
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
Method Description
public abstract void onCreate(SQLiteDatabase db) called only once when database is
created for the first time.
public abstract void onUpgrade(SQLiteDatabase db, int called when database needs to be
oldVersion, int newVersion) upgraded.
pg. 47
IMPORTANT NOTES
Mobile Application Development
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update,
delete, select etc.
There are many methods in SQLiteDatabase class. Some of them are as follows:
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table specifies the
nullColumnHack, ContentValues table name, nullColumnHack doesn't allow completely null
values) values. If second argument is null, android will store null
values if values are empty. The third argument specifies the
values to be stored.
SQLiteDatabase
In Android, the SQLiteDatabase namespace defines the functionality to connect
and manage a database. It provides functionality to create, delete, manage and
display database content.
pg. 48
IMPORTANT NOTES
Mobile Application Development
Create a Database
Before you can use the above object, you must import
the android.database.sqlite.SQLiteDatabase namespace in your application.
1. db=openOrCreateDatabase(String path, int mode, SQLiteDatab
ase.CursorFactory factory)
This method is used to create/open database. As the name suggests, it will open
a database connection if it is already there, otherwise, it will create a new one.
Example,
1. db=openOrCreateDatabase("XYZ_Database",SQLiteDatabase.CREA
TE_IF_NECESSARY,null);
Arguments:
This command is used to execute a single SQL statement that doesn't return any
data means other than SELECT or any other.
1. db.execSQL("Create Table Temp (id Integer, name Text)");
pg. 49
IMPORTANT NOTES
Mobile Application Development
In the above example, it takes "CREATE TABLE" statement of SQL. This will create
a table of "Integer" & "Text" fields.
Try and Catch block is required while performing this operation. An exception
that indicates there was an error with SQL parsing or execution.
This class is used to store a set of values. We can also say, it will map
ColumnName and relevant ColumnValue.
1. values.put("id", eid.getText().toString());
2. values.put("name", ename.getText().toString());
This method returns a long. The row ID of the newly inserted row, or -1 if an
error occurred.
Example,
1. db.insert("temp", null, values);
This interface provides random read-write access to the result set returned by a
database query.
1. Cursor c=db.rawQuery(String sql, String[] selectionArgs)
pg. 50
IMPORTANT NOTES
Mobile Application Development
Example,
1. Cursor c=db.rawQuery("SELECT * FROM temp",null);
Methods
Example,
1. c.moveToFirst();
2. while(!c.isAfterLast())
3. {
4. //statement…
5. c.moveToNext();
6. }
Step 6: Close Cursor and Close Database connectivity
pg. 51