0% found this document useful (0 votes)
79 views

Android

Android is an open source operating system developed by the Open Handset Alliance led by Google. It is intended to provide a complete software stack for mobile devices. Android Studio is the official IDE for Android development, which allows developers to create, build, and debug Android applications. It provides tools and features within a main window interface to facilitate the development process.

Uploaded by

Kv Nageswarao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Android

Android is an open source operating system developed by the Open Handset Alliance led by Google. It is intended to provide a complete software stack for mobile devices. Android Studio is the official IDE for Android development, which allows developers to create, build, and debug Android applications. It provides tools and features within a main window interface to facilitate the development process.

Uploaded by

Kv Nageswarao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 186

What is Android?

 Android is an open source operating system based on Linux


with a Java programming interface for mobile devices such
as Smartphone (Touch Screen Devices who supports
Android OS) as well for Tablets too.

 Android was developed by the Open Handset Alliance


(OHA), which is led by Google.

 The Open Handset Alliance (OHA) is consortium of


multiple companies like Samsung, Sony, Intel and many
more to provide a services and deploy handsets using
android platform.
What is Android?
 It is intended to be a complete stack that includes
everything from operating system through middleware and
up through applications.
Android History
Release Date Version API Level Version Name

September 23, 2008 Android 1.0 1 Apple Pie

February 9, 2009 Android 1.1 2 Banana Bread

April 30, 2009 Android 1.5 3 Cupcake

September 15, 2009 Android 1.6 4 Donut

October 26, 2009 Android 2.0 5

December 3, 2009 Android 2.0.1 6 Eclair

January 12, 2009 Android 2.1 7


Android History
Release Date Version API Level Version Name

May 20, 2010 Android 2.2 8

January 18, 2011 Android 2.2.1 8


Froyo
January 22, 2011 Android 2.2.2 8

November 21, 2011 Android 2.2.3 8

December 6, 2010 Android 2.3 9

February 9, 2011 Android 2.3.1 9


Gingerbread
July 25, 2011 Android 2.3.3 10

September 2, 2011 Android 2.3.4 10


Android History
Release Date Version API Level Version Name

February 22, 2011 Android 3.0.x 11

May 10, 2011 Android 3.1.x 12 Honeycomb

July 15, 2011 Android 3.2.x 13

October 18,2011 Android 4.0 14

October 19, 2011 Android 4.0.1 14

November 28, 2011 Android 4.0.2 14 Ice Cream Sandwich

December 16, 2011 Android 4.0.3 15

February 4, 2012 Android 4.0.4 15


Android History
Release Date Version API Level Version Name

July 9, 2012 Android 4.1 16

July 23, 2012 Android 4.1.1 16

October 9, 2012 Android 4.1.2 16

November 13, 2012 Android 4.2 17 Jelly Bean

November 27, 2012 Android 4.2.1 17

February 11, 2013 Android 4.2.2 17

July 24, 2013 Android 4.3 18


Android History
Release Date Version API Level Version Name

October 31, 2013 Android 4.4 19


Kitkat
Android 4.4.1, 4.4.2,
June 23, 2014 19
4.4.3, 4.4.4

October 17, 2014 Android 5.0 21


Lollipop
March 09, 2015 Android 5.1 22

October 5, 2015 Android 6.0 23


Marshmallow
December 7, 2015 Android 6.0.1 23
Android History
Release Date Version API Level Version Name

August 22, 2016 Android 7.0 24


Nougat
October 4, 2016 Android 7.1 25

August 21, 2017 Android 8.0 26


Oreo
December 5, 2017 Android 8.1.0 27

August 6, 2018 Android 9 28 Pie

September 3, 2019 Android 10 29 Q ( Quince Tart )

September 8, 2020 Android 11 30 R ( Red Velvet Cake)

October 4, 2021 Android 12 31 S ( Snow Cone )


Android OS Market Value
 Following is the pictorial representation of using an android in
mobile phone market with different versions.
Android Studio Installation
 Android Studio is the official IDE for android development and it’s
based on IntelliJ IDEA software. It’s available for Windows, MAC
and LINUX operating systems.

 We can download latest version of Android Studio from following


URL.
https://developer.android.com/studio/
Android Studio Installation
 The initial android studio setup screen will open like as shown
below in that click Next to continue for further steps of environment
setup.
Android Studio Installation
 Now we need to select a required components to setup an android
environment. Here we selected all three components (Android
Studio, Android SDK and Android Virtual Device) and click Next
like as shown below.
Android Studio Installation
 Now we need to agree the License agreements to proceed further,
click on I Agree button like a shown below.
Android Studio Installation
 Now we need to specify the local machine drive location to install
Android Studio and Android SDK. After selecting the location path
to install required components, click Next like as shown below.
Android Studio Installation
 Now select the start menu folder to create a shortcuts for android
studio and click Install like as shown below.
Android Studio Installation
 Once we click Install button the installation process will start and
click Next after completion of installation like as shown below.
Android Studio Installation
 After that it will show installation completion wizard in that click
Finish to launch android studio like as shown below.
Android Studio Installation
 While launching Android Studio it will give you an option to import
settings from previous version of studio. In case if you don’t have
any previous version, select second option and click OK like as
shown below.
Android Studio Installation
 Now android studio will open a welcome wizard window in that
click Next to validate our current Android SDK and development
environment setup like as shown below.
Android Studio Installation
 Now select a Standard installation type and click Next to install a
common settings and options like as shown below.
Android Studio Installation
 Now verify settings and click Finish to complete android studio
setup process like as shown below.
Android Studio Installation
 After completion of required components installation click on Finish
like as shown below.
Android Studio Installation
 After completion of all required components installation we will be
able to see Android Studio welcome window like as shown below.
Creating New Project in Android Studio
Android Studio Main Window
 Before developing an android application in the android studio the
developer must have knowledge of its tool first.
 The Android studio main window is consists of several logical areas.
Android Studio Main Window
 1. Toolbar : One can find the Toolbar section at the top of the android
studio.
 It contains a wide range of functions including creating a new
project which is inside the File Section.
 Reformat your code which is inside the Code Section, Rebuild your
project which is inside the Build section, running your android app
which is inside the Run section, and many more.

 2. Editor : In this window, the users can create, write, and modify their
code.

 3.Tool Window Bar: The tool window bar operates around the outside
of the IDE window and includes the buttons that allow users to
expand or collapse individual tool windows.
Android Studio Main Window
 4. Navigation Bar : The navigation bar helps the users to navigate
throughout the project and open files for editing. It helps us to navigate and
modify the required file easily.

 5. Status Bar : The status bar displays the current status of the project and
the IDE itself, as well as any warnings or messages during the execution of
the project.

 6.Tool Windows: The tool windows give access to specific tasks like project
management, search, version control, and more.
 It provides a lot of powerful things. For example, at the second last (From right) of the
Toolbar section, the user can find a search icon where the users can search anything inside
android studio such as searches for:
 Classes
 Files
 Tool Windows
 Actions
 Settings, etc
Android Studio Tool window
 We can use keyboard shortcuts to open tool windows. The below table
provides the list of shortcuts for the most common windows.

Tool window Windows and Linux Mac


Project Alt+1 Command+1
Version Control Alt+9 Command+9
Run Shift+F10 Control+R
Debug Shift+F9 Control+D
Logcat Alt+6 Command+6
Return to Editor Esc Esc
Hide all Tool Windows Control+Shift+F12 Command+Shift+F12
Android Studio Project Structure
 The Android Studio project contains one or more modules with
resource files and source code files. These include different types of
modules.
Manifests Folder
 This folder will contain a manifest file (AndroidManifest.xml) for
our android application.
 This manifest file will contain information about our application
such as android version, access permissions, metadata, etc. of our
application and its components.
 The manifest file will act as an intermediate between android OS and
our application.
Java Folder
 This folder will contain all the java source code (.java) files which
we’ll create during the application development, including JUnit test
code.
 Whenever we create any new project / application, by default the
class file MainActivity.java will create automatically under the
package name “com.example.pratap.myapplication” like as shown
below.
res (Resources) Folder
 It’s an important folder which will contain all non-code resources,
such as bitmap images, UI strings, XML layouts like as show below.
Drawable Folder (res/drawable)
 It will contains the different type of images as per the requirement of
application.
 It’s a best practice to add all the images in drawable folder other than
app / launcher icons for the application development.
Layout Folder (res/layout)
 This folder will contain all XML layout files which we used to define
the user Interface of our application.
 Following is the structure of layout folder in android application.
Mipmap Folder (res/mipmap)
 This folder will contain app / launcher icons which are used to show
on the home screen.
 It will contain different density type of icons such as hdpi, mdpi,
xhdpi, xxhdpi, xxxhdpi, to use different icons based on the size of
device.
Values Folder (res/values)
 This folder will contain a various XML files, such as strings, colors,
styles definitions and static array of strings or integers.
Gradle Scripts
 In android, Gradle means automated build system and by using this
we can define a build configuration that apply to all modules in our
application.
 In gradle build.gradle (Project), build.gradle (Module) are used to
build configurations that apply to all our app modules or specific to
one app module.
Create Android Virtual Device
 To test our android application we should have an Android Virtual
Device (AVD).
 We can create virtual device by click on AVD Manager like as shown
below.
Create Android Virtual Device
 When we click on AVD Manager, new window will open in that
click on Create Virtual Device like as shown below.
Create Android Virtual Device
 Now select the required device type and Click Next to create a
virtual device like as shown below.
Different Types of Activities
 In android, an activity is a class that represents a single screen. It is
like a Frame in AWT.
 Generally, when a developer wants to create a new project in the
android studio he/she needs to select a project template which is
consisting of many activities.
 The following are the list of activities:
1. No Activity 13. Tabbed Activity
2. Basic Activity 14. Fragment + ViewModel
3. Bottom Navigation Activity 15. Native C++
4. Empty Activity
5. Full screen Activity
6. Google Admob Ads Activity
7. Google Maps Activity
8. Login Activity
9. Master/Detail Flow
10. Navigation Drawer Activity
11. Settings Activity
12. Scrolling Activity
Different Types of Activities
 No Activity: As the name suggests No Activity means creating a new
empty project. When the developer selects this activity there will be
neither an XML file nor a Java/Kotlin file.
 No files are automatically generated when you select No Activity.
Different Types of Activities
 Basic Activity: It creates a new basic
activity with the navigation component.
When the developer selects the basic
activity, then you will be getting a menu
button, and you will also get a floating
action button.
 These files are automatically created
when you select Basic Activity:
 activity_main.xml
 content_main.xml
 menu_main.xml
 FirstFragment.java
 SecondFragment.java
 MainActivity.java
Different Types of Activities
 Bottom Navigation Activity: It creates a
new activity with bottom navigations.
We all have come across apps that contain
a Bottom Navigation Bar. Some popular
examples include Instagram, WhatsApp,
etc.
 Use this template when your application
has three to five top-level destinations.
Different Types of Activities
 Empty Activity: It creates an empty
activity and a single layout file with
sample text content. It allows you to start
from scratch when building your app
module or activity.
 This is a popular activity and we
frequently select this activity when we
start developing an android project.
Different Types of Activities
 Full screen activity: It creates a new
activity that toggles the visibility of the
system UI (status and navigation bars)
and action bar upon user interaction. .
 Many apps are using Full-Screen Activity
to have an attractive screen to show slides
etc.
Different Types of Activities
 Google Admob Ads Activity: To earn
money from the Android app or game,
there are many ways such as in-App
Purchases, Sponsorship, Advertisements,
and many more. But there is another
popular method to earn money from the
Android app is by integrating an
advertisement e.g known as Google
AdMob.
Different Types of Activities
 Google Maps Activity: Android permits
to integrate google maps in our
application. One can show any location
on the map or can show various routes on
the map etc. One can also customize the
map according to the choices.
 So Google Maps Activity creates a new
activity with a Google Map. These files
are automatically created when you select
Google Maps Activity .
Different Types of Activities
 Login Activity: As the name suggests
Login Activity creates a new login
activity, allowing users to enter an email
address and password to log in or to
register with the application.
 Login Activity is one of the most common
activities that almost every application
contains this activity. These files are
automatically created when you select
Login Activity.
Different Types of Activities
 Master/Detail Flow: Master/Detail
Flow creates a new master/detail
flow, enabling users to view a
collection of objects as well as details
for each object.
 This flow is presented using two
columns on tablet-sized screens and
one column on handsets and smaller
screens. This template creates two
activities, a master fragment, and a
detailed fragment. These files are
automatically created when you
select Master/Detail Flow.
Different Types of Activities
 Navigation Drawer Activity:
Android Navigation Drawer is a
sliding left menu that is used to
display the important links in the
application.
 The Navigation drawer makes it
easy to navigate to and fro between
those links. It’s not visible by default
and it needs to open either by
sliding from left or clicking its icon
in the ActionBar.
 In broader terms, Navigation
Drawer is an overlay panel, which is
a replacement of an activity screen
that was especially dedicated to
showing all the options and links in
the application.
Different Types of Activities
 Settings Activity: Setting Activity creates a new activity that allows a user to
configure application settings.
 These files are automatically created when you select Settings Activity.
Different Types of Activities
 Scrolling Activity: Scrolling activity is an essential activity to have in the app as
it provides the users with a perfect view when the layout is long. It creates a
new vertical scrolling activity.
Different Types of Activities
 Tabbed Activity: In Android, TabLayout gives a horizontal layout to display
tabs. If TabLayout is used then along with it, Fragment is also used, because
fragments are lightweight and the app can have more functionality on a single
screen if more fragments are added.
 Whenever the user clicks on the tab it will lead to the transaction of one
Fragment to another. ViewPager is used to swipe between the tabs. WhatsApp,
Facebook, etc. are a perfect example of TabLayout with ViewPager..
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.example.prabu.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Applications
 This is where all applications get reside.

 It includes the home application, contact application and browser


etc.
Android Application Components
 In android, application components are the basic building blocks of
an application and these components will act as an entry point to
allow system or user to access our app.

 Following are the basic core application components that can be


used in Android application.
Android Application Components
 Activities: It represents a single screen with a user interface (UI) and it
will acts an entry point for user’s to interact with app.

 Intents: It is a messaging object which is used to request an action from


another component.

 Content Providers: They are used to exchange the data between the
apps based on the requests.

 Broadcast Receivers: It is a component which will allow a system to


deliver events to the app like sending a low battery message to the app.

 Services: It is a component which keep an app running in the


background to perform long running operations based on our
requirements.
Additional Components
Component Description

These are used to represent the portion of user interface in an


Fragments
activity

Layouts These are used to define the user interface (UI) for an activity or app

These are used to build user interface for an app using UI elements
Views
like buttons, lists, etc.

To build android app we required external elements like images,


Resources
audio files, etc. other than coding
It’s a configuration file (AndroidManifest.xml) for the application
Manifest File and it will contain the information about Activities, Intents, Content
Providers, Services, Broadcast Receivers, permissions, etc.
Android Activity Lifecycle
 In android, Activity represents a single screen with a user
interface (UI) of an application and it will acts an entry point for
users to interact with an app.

 Generally, the android apps will contain multiple screens and


each screen of our application will be an extension of Activity
class.
Android Activity Lifecycle
 By using activities, we can place all our android application UI
components in a single screen.

 For example, a contacts app which is having a multiple


activities, in that the main activity screen will show a list of
contacts and from the main activity screen we can launch other
activities that provides a screens to perform a tasks like add a
new contact and search for the contacts.
Android Activity Lifecycle
 Generally, the activities in our android application will go
through a different stages in their life cycle.

 In android, Activity class have a 7 callback methods like


onCreate(), onStart(), onPause(), onRestart(), onResume(),
onStop() and onDestroy() to describe how the activity will
behave at different stages.
Activity Lifecycle Callback Methods
 In android, an activity goes through a series of states during its
lifetime. By using callback methods we can get the activity
transitions between the states.

 Android system initiates its program within an Activity starting


with a call on onCreate() callback method.
onCreate()
 This is the first callback method and it fires when the system
creates an activity for the first time.

 During the activity creation, activity entered into a Created


state.
onStart()
 The onStart() callback method will invoke when an activity
entered into Started State by completing onCreate() method.

 The onStart() method will make an activity visible to the user


and this method execution will finish very quickly.
onResume()
 When an activity entered into Resumed state, the system invoke
onResume() call back method.

 The app will stays in this Resumed state until an another


activity happens to take focus away from the app like getting a
phone call or screen turned off, etc.
onPause()
 Whenever the user leaves an activity or the current activity is
being Paused then the system invoke onPause() method.

 The onPause() method is used to pause an operations like stop


playing the music when the activity is in paused state or pass an
activity while switching from one app to another app because
every time only one app can be focused.
onStop()
 The system will invoke onStop() callback method when an
activity no longer visible to the user, the activity will enter into
Stopped state.

 This happens due to current activity entered into Resumed state


or newly launched activity covers complete screen or it’s been
destroyed.
onRestart()
 The system will invoke onRestart() method when an activity
restarting itself after stopping it.

 The onRestart() method will restore the state of activity from the
time that is being stopped.
onDestroy()
 The system will invoke onDestroy() method before an activity is
destroyed and this is the final callback method which received
by the android activity.
activity_main.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.529"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.136" />

</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("ActivityLifeCycle","onCreate is called");
}
@Override
protected void onStart()
{
super.onStart();
Log.i("ActivityLifeCycle","onStart is called");
}
@Override
protected void onResume()
{
super.onResume();
Log.i("ActivityLifeCycle","onResume is called");
}
@Override
protected void onPause()
{
super.onPause();
Log.i("ActivityLifeCycle","onPause is called");
}

@Override
protected void onStop()
{
super.onStop();
Log.i("ActivityLifeCycle","onStop is called");
}

@Override
protected void onDestroy()
{
super.onDestroy();
Log.i("ActivityLifeCycle","onDestroy is called");
}
}
Output in Logcat
Intents
 Intent is the message that is passed between components such
as activities, content providers, broadcast receivers, services etc.

 Intent is a messaging object which is used to request an action


from another app component such as activities, services,
broadcast receivers and content providers.

 Intents will help us to maintain the communication between


app components from the same application as well as with the
components of other applications.
Intents
 Android intents are mainly used to:
 Start the service

 Launch an activity

 Display a screen, web page

 Display a list of contacts

 Broadcast a message

 Dial a phone call etc.


Intents
Intents are the objects of android.content.Intent

Component Description

Starting an By passing an Intent object to startActivity() method we can start a


Activity new Activity or existing Activity to perform required things.

Starting a Service By passing an Intent object to startService() method we can start a


new Service or send required instructions to an existing Service.

Delivering a By passing an Intent object to sendBroadcast() method we can


Broadcast deliver our messages to other app broadcast receivers.
Building an Intent Object
 Generally, in android Intent object contains the information that
required to determine which component to start and the
information about the action to be performed by recipient
component.

 The Intent object in android is having a following characteristics


to help android system to understand which component should
start.
 Component Name
 Action
 Data
 Category
Building an Intent Object
Component Name: It defines a name of the component to start
and by using component name android system will deliver intent
to the specific app component defined by the component name.
Action: It defines a name of the action to be performed to start an
activity.
Action Description
We can use this action in an intent with startActivity(),
ACTION_VIEW when we have information that an activity can show to the
us
We can use this action in an intent with startActivity(),
when we have a some data that the user can share through
ACTION_SEND another app such as email app, social sharing app.
Building an Intent Object
Data: It specify a type of the data to an intent filter. When we
create an intent, it’s important to specify the type of data (MIME
type) in addition to its URI.

Category: Generally, in android category is an optional for intents


and it specify the additional information about type of the
component that should handle an intent.
Intent Types

There are two types of intents available in android,


1. Implicit Intents and
2. Explicit Intents.
Implicit Intents
 Implicit Intents won’t specify any name of the component to
start, instead it declare an action to perform and it allow a
component from other app to handle it.
Implicit Intents
activity_main.xml
<android.support.constraint.ConstraintLayout
.
.
tools:context=".MainActivity">
<EditText
.
.
android:id="@+id/editText“
.
.
/>
<Button
android:id="@+id/submit"
android:text="Click"
/>
</android.support.constraint.ConstraintLayout>
Implicit Intents
MainActivity.java
package com.example.prabu.intent;
import……..
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText)findViewById(R.id.editText);
Button btn = (Button) findViewById(R.id.submit);
Implicit Intents
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String url = editText.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});

}
}
Implicit Intents
Explicit Intents
 Explicit Intent specifies the component, it helps to invoke
external class.

 Explicit intents explicitly specify the name of component to be


invoked by an activity and we use explicit intents to start a
component in our own app.

 For example we can start a new activity in response to a user


action using explicit intents.

 By using explicit intents we can send or share data / content


from one activity to another activity based on our requirements.
Explicit Intents
activity_main.xml
<android.support.constraint.ConstraintLayout
tools:context=".MainActivity">
<TextView
android:id="@+id/fstTxt"
android:text="First Number" />
<EditText
android:id="@+id/firstNum“
</EditText>
<TextView
android:id="@+id/secTxt"
android:text="Second Number" />
<EditText
android:id="@+id/secondNum" />
<Button
android:id="@+id/addBtn"
android:text="Add“ />
</android.support.constraint.ConstraintLayout>
Explicit Intents
MainActivity.java
package com.example.prabu.explicitintent;
import…..
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText firstNum = (EditText)findViewById(R.id.firstNum);
final EditText secNum = (EditText)findViewById(R.id.secondNum);
Button btnAdd = (Button)findViewById(R.id.addBtn);
Explicit Intents
btnAdd.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
int num1 = Integer.parseInt(firstNum.getText().toString());
int num2 = Integer.parseInt(secNum.getText().toString());
Intent intent = new Intent(MainActivity.this,ResultActivity.class);
intent.putExtra("SUM",num1+" + "+num2+" = "+(num1+num2));
startActivity(intent);
}
});
}
}
Explicit Intents
result.xml
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/resultView"/>
android:textStyle="bold"
android:textSize=“30dp"
</android.support.constraint.ConstraintLayout>
Explicit Intents
ResultActivity.java
package com.example.prabu.explicitintent;
import ……
public class ResultActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView sum = (TextView)findViewById(R.id.resultView);
Intent intent = getIntent();
String addition = (String)intent.getSerializableExtra("SUM");
sum.setText(addition);
}
}
Explicit Intents
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prabu.explicitintent">
<application
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ResultActivity"
android:label="Explicit Intent - Activity2">
</activity>
</application>
</manifest>
Explicit Intents
Intent Filters
 Intent Filter is an expression in app’s manifest file
(ActivityMainfest.xml) and it is used to specify the type of
intents that the component would like to receive.

 In case if we create Intent Filter for an activity, there is a


possibility for other apps to start our activity by sending a
certain type of intent otherwise the activity can be started only
by an explicit intent.

 Generally, the Intent Filters (<intent-filter>) whatever we define


in manifest file can be nested in the corresponding app
components and we can specify the type of intents to accept
using the three elements.
Intent Filters
<action>
 It defines the name of an intent action to be accepted and it
must be a literal string value of an action, not the class constant.

<category>
 It defines the name of an intent category to be accepted and it
must be the literal string value of an action, not the class
constant.

<data>
 It defines the type of data to be accepted and by using one or
more attributes we can specify various aspects of the data URI
(scheme, host, port, path) and MIME type.
Intent Filters
activity_main.xml
<android.support.constraint.ConstraintLayout
tools:context=".MainActivity">
<Button
android:id="@+id/sendMail"
android:text="Send Mail"
/>
</android.support.constraint.ConstraintLayout>
Intent Filters
MainActivity.java
package com.example.prabu.intentfilters;
import…..
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSend = (Button)findViewById(R.id.sendMail);
Intent Filters
btnSend.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL,new String[]{“[email protected]"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Newsletter");
intent.putExtra(Intent.EXTRA_TEXT, "Sir, I have read this month's newsletter of KL
University. I would like to subscribe to the newsletter");
startActivity(Intent.createChooser(intent,"Choose Mail App"));
}
});
}
}
Intent Filters
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prabu.intentfilters">
<application
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"/>
</intent-filter>
</activity>
</application>
</manifest>
Intent Filters
Android Architecture
Linux Kernel
 Android is based on Linux 2.6 kernel.

 Linux kernel is used as hardware abstraction layer.

 It has proven driver model.

 It also provides memory management, process management,


security model, networking and lot of core operating system
infrastructure that are robust and have been proven over time.
Native Libraries
 It is written in C and C++.

Surface Manager:
 It is responsible for composing different drawing surfaces onto the
screen.

 It is responsible for taking different windows that are owned by


different applications that are running in different processes.
Native Libraries
Open GL/ES and SGL:
 These two make the core of graphics libraries.

Open GL/ES:
 Open GL/ES is a 3D library.
 We have a software implementation that accelerates hardware if the
device has 3D chip on it.

SGL:
 SGL are for 2D Graphics and that is what most of our application
drawing is based on.
 In android 2D and 3D can be combined in the same application.
Native Libraries
Media Framework:
 It is provided with Packet Video, one of the members of the Open
Handset Alliance and that contains all of the CODECs that make up
the core of media experience.
 MPEG4, H.264, MP3, AAC, all the audio and video CODEC’s are
found which are needed to build rich media experience.

Free type: It is used to render font.

SQLite: It is used as core of data storage.

Webkit: It is open source browser engine. It’s same browser that’s


powering safari from apple.
Android Runtime
Dalvik Virtual Machine (DVM)
 It is a register-based virtual machine like Java Virtual Machine
(JVM).

 It is specially designed and optimized for android to ensure that a


device can run multiple instances efficiently.

 It relies on the Linux kernel for threading and low-level memory


management.

 It optimizes the virtual machine for memory, battery life and


performance.
Android Runtime
Dalvik Virtual Machine (DVM)
 It runs .dex files.

 These are byte codes that are the results of converting at build time(.class
and .jar files).

 These files when they are converted to .dex become a much efficient byte
code that can run well on small processors.

 They use memory very efficiently, the data structures are designed to be
shared across processes whenever possible and uses a highly CPU
optimized interpreter.

 The result of that is to have multiple instances of the Dalvik virtual


machine running on the device at the same time.
Android Runtime
Core Libraries:
 It is written in Java.

 It contains all of collection classes, utilities, I/O


Application Framework
 It is written in Java.

 It is the toolkit that all applications use.

 These applications use the one that come with the phone like the
home application and phone application includes application
written by Google and us.
Application Framework
Activity Manager:
 It manages the lifecycle of application.
 It also maintains the common back stack so that applications
running in different processes have a smoothly integrated
navigation experience.

Package Manager:
 It keeps track of which applications are installed in the device.
 It is responsible for the what are the applications installed and
capabilities of each application.
Application Framework
Window Manager:
 It manages windows, it’s mostly a JAVA programming language
abstraction on top of lower level services that are provided by
surface manager.

Telephony Manager:
 It contains the API’s that we use to build the phone application that’s
central to the phone application.
Application Framework
Content Providers:
 It is a unique piece of the android platform.
 It is the framework that the application shares the data with other
application.

Resource Manager:
 It is used to store localized strings, Bitmaps, layout file descriptions,
all of the external parts of an application that are hard-coded.
Application Framework
View System:
 It contains buttons, lists, all the building blocks of User Interfaces
(UI) and also can handle things like event dispatch, layout, drawing.

Location Manager, Notification Manager, XMPP Service:


 These API’s allows developers to create really innovative and
exciting applications.
User Interface Layouts
 Layout is used to define the user interface for an app or activity
and it will hold the UI elements that will appear to the user.

 The user interface in android app is made with a collection of


View and ViewGroup objects.

 Generally, the android apps will contain one or more activities


and each activity is a one screen of app.

 The activities will contain a multiple UI components and those


UI components are the instances of View and ViewGroup
subclasses.
User Interface Layouts
 The View is a base class for all UI components in android and it
is used to create an interactive UI components such as TextView,
EditText, Checkbox, Radio Button, etc. and it responsible for
event handling and drawing.

 The ViewGroup is a subclass of View and it will act as a base


class for layouts and layouts parameters.

 The ViewGroup will provide an invisible containers to hold


other Views or ViewGroups and to define the layout properties.
Layout Types
 Following are the commonly used layouts in android
applications to implement required designs.
 Linear Layout
 Relative Layout
 Frame Layout
 Table Layout
 Constraint Layout
Layout Types
 Following are the commonly used layouts in android
applications to implement required designs.
 Linear Layout
 Relative Layout
 Frame Layout
 Table Layout
 Constraint Layout
Linear Layout
 LinearLayout is a ViewGroup subclass which is used to render
all child View instances one by one either in Horizontal
direction or Vertical direction based on the orientation property.

 We can specify the linear layout orientation using


android:orientation attribute.
Linear Layout
Following is the pictorial representation of linear layout

Horizontal Vertical
Linear Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/To"
android:hint="To" />
<EditText
android:id="@+id/Subject"
android:hint="Subject" />
<EditText
android:id="@+id/Message"
android:hint="Message" />
<Button
android:id="@+id/Send"
android:layout_gravity="right"
android:text="Send" />
</LinearLayout >
Linear Layout
Relative Layout
 Relative Layout is a ViewGroup which is used to specify the
position of child View instances relative to each other (Child A
to the left of Child B) or relative to the parent (Aligned to the
top of parent).
Relative Layout
Following is the pictorial representation of relative layout
Relative Layout
<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android
tools:context=".MainActivity">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
Relative Layout
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />

<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
Relative Layout
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn4"
android:layout_centerHorizontal="true"
android:text="Button6" />
Relative Layout
<Button
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:text="Button7" />

</RelativeLayout>
Relative Layout
Frame Layout
 Frame layout is a ViewGroup subclass which is used to specify
the position of View instances it contains on the top of each
other to display only single View inside the Frame Layout.

 In simple manner, we can say FrameLayout is designed to block


out an area on the screen to display a single item.
Frame Layout
Following is the pictorial representation of frame layout
Frame Layout
<FrameLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation="vertical“
tools:context=".MainActivity">

<ImageView
android:id="@+id/imgvw1"
android:layout_width="match_parent"
android:layout_height="505dp"
android:scaleType="fitEnd"
android:src="@drawable/paris" />

<TextView
android:id="@+id/txtvw1"
android:background="#4C374A"
android:padding="10dp"
android:text="Eiffel Tower"
android:textColor="#FFFFFF"
android:textSize="20sp" />
Frame Layout
<TextView
android:id="@+id/txtvw2"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:text="25/Aug/2018"
android:textColor="#FFFFFF"
android:textSize="18sp" />

</FrameLayout>
Frame Layout
Table Layout
 Table Layout is a ViewGroup subclass which is used to display
the child View elements in rows and columns.
 Following is the pictorial representation of table layout
Table Layout
<TableLayout xmlns:android=http://schemas.android.com/apk/res/android
tools:context=".MainActivity">
<TableRow
android:background="#0079D6"
android:padding="5dp">

<TextView
android:layout_weight="1"
android:text="User ID" />

<TextView
android:layout_weight="1"
android:text="User Name" />

<TextView
android:layout_weight="1"
android:text="Location" />
</TableRow>
Table Layout
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_weight="1"
android:text="1" />

<TextView
android:layout_weight="1"
android:text="ARU N" />

<TextView
android:layout_weight="1"
android:text="Hyderabad" />

</TableRow>
Table Layout
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_weight="1"
android:text="3" />

<TextView
android:layout_weight="1"
android:text="CHANDRU" />

<TextView
android:layout_weight="1"
android:text="GUNTUR" />
</TableRow>

</TableLayout>
Table Layout
Constraint Layout
 Constraint Layout allows you to create large and complex
layouts with a flat view hierarchy (no nested view groups).

 It's similar to Relative Layout in that all views are laid out
according to relationships between sibling views and the parent
layout, but it's more flexible than Relative Layout.
Constraint Layout
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Constraint Layout
Android Menus
 Menus are a common user interface component in many types
of applications.

 Menus expose apps functionality without consuming ‘much’


view space.

 To provide a familiar and consistent user experience, you


should use the Menu APIs to present user actions and other
options in your activities.

 In order to use menu, we should define it in separate XML file


and use that file in our application based on our requirements.
Types of Menu’s
 Android provides three types of menus known as:
 Popup menu, options menu and contextual menu.

 A popup menu displays a list of items in a vertical list that's anchored


to the view that invoked the menu.

 The options menu is the primary collection of menu items for an


activity. It's where you should place actions that have a global impact
on the app, such as "Search," "Compose email," and "Settings.".

 A context menu is a floating menu that appears when the user


performs a long-click on an element. It provides actions that affect the
selected content or context frame.
Contd.
How to define Menu in XML File?
 Android Studio provides a standard XML format for type of menus to define
menu items.

 We can simply define the menu and all its items in XML menu resource
instead of building the menu in the code and also load menu resource as menu
object in the activity or fragment used in our android application.

 We should create a new folder menu inside of our project directory


(res/menu) to define the menu and also add a new XML file to build the menu
with following elements.
Contd.
 Following is the example of defining a menu in an XML file
(menu_example.xml).
Contd.
 The <item> element in menu supports different type of attributes to define
item’s behavior and appearance. Following are the some of commonly used
<item> attributes in android applications.
Contd.
 In case if we want to add submenu in menu item, then we need to add a
<menu> element as the child of an <item>. Following is the example of
defining a submenu in menu item.
Load Android Menu from an Activity
 Once we are done with creation of menu, we need to load the menu resource
from our activity using MenuInflater.inflate() like as shown:
Handle Android Menu Click Events
 In android, we can handle a menu item click events using ItemSelected()
event based on the menu type. Following is the example of handling a context
menu item click event using onContextItemSelected().
Option Menu
 Android Option Menus are the primary menus of
android. They can be used for settings, search,
delete item etc.
 In android, Options Menu is a primary collection
of menu items for an activity and it is useful to
implement actions that have a global impact on
the app, such as Settings, Search, etc.
 By using Options Menu, we can combine multiple
actions and other options that are relevant to our
current activity. We can define items for the
options menu from either our Activity or
Fragment class.
 In case, if we define items for the options menu in
both activity or fragment, then those items will be
combined and display in UI.
Popup Menu
 In android, Popup Menu displays a list of items in a
modal popup window that is anchored to the view.

 The popup menu will appear below the view if there


is a room or above the view in case if there is no space
and it will be closed automatically when we touch
outside of the popup.

 The android Popup Menu provides an overflow style


menu for actions that are related to specific content.

 In android, the Popup Menu provides an overflow of


actions that are related to specific content and the
actions in the popup menu won’t affect the
corresponding content. The popup menu won’t
support any item shortcuts and item icons.
Contextual Menu
 In android, Context Menu is like a floating menu
and that appears when the user performs a long
press or click on an element and it is useful to
implement actions that affect the selected content
or context frame.

 The android Context Menu is more like the menu


which displayed on right-click in Windows or
Linux.

 In android, the Context Menu offers actions that


affect a specific item or context frame in the UI and
we can provide a context menu for any view. The
context menu won’t support any item shortcuts
and item icons.
Databases & Content Providers

Unit IV Chapter 2

Data Storage 1
Storage Options
• Android provides several options to save persistent application data depends on your
specific needs, such as whether data should be private to your application or
accessible to other applications (and user) and how much space your data requires.
• Android provides a way to expose even your private data to other applications — with
a content provider. A content provider is an optional component that exposes
read/write access to your application data, subject to whatever restrictions you want to
impose.
1. Shared Preferences
• Store private primitive data in key-value pairs.
• The SharedPreferences class provides a general framework that allows you to save
and retrieve persistent key-value pairs of primitive data types. You can use
SharedPreferences to save any primitive data: booleans, floats, ints, longs, and
strings. This data will persist across user sessions (even if your application is killed).
2. Internal Storage
• Store private data on the device memory.
• You can save files directly on the device's internal storage. By default, files saved to
the internal storage are private to your application and other applications cannot
access them (nor can the user). When the user uninstalls your application, these files
are removed.
• Saving cache files
• These are temporary files which may be deleted by system when internal storage
is low.
Storage Options
• These are removed when application is uninstalled.
• However, you should not rely on the system to clean up these files for you. You
should always maintain the cache files yourself and stay within a reasonable limit of
space consumed, such as 1MB. When the user uninstalls your application, these
files are removed.
3. External Storage
• Store public data on the shared external storage.
• Every Android-compatible device supports a shared "external storage" that you can use
to save files. This can be a removable storage media (such as an SD card) or an
internal (non-removable) storage. Files saved to the external storage are world-
readable and can be modified by the user when they enable USB mass storage to
transfer files on a computer.
• CAUTION! External storage can become unavailable without warning, if it is removed.
4. SQLite Databases
• Store structured data in a private database.
5. Network Connection
• Store data on the web with your own network server.
• To do network operations, use classes in the following packages:
• java.net.* • android.net.*
Data Base Management using SQLite
• SQLite is an open-source SQL database that stores data to a text file on a
device.
• SQLite is a software library that implements a self-contained, server-less, zero-
configuration, transactional SQL database engine. SQLite is the most widely
deployed SQL database engine in the world. It was designed in year 2000.
• SQLite supports all the relational database features. In order to access this
database, you don't need to establish any kind of connections for it like
JDBC,ODBC etc.
• SQLite transactions are fully ACID-compliant.
• ACID(Atomicity, Consistency, Isolation, Durability)
• SQLite is case insensitive.
SQLite Database
• Android applications can have application databases
powered by SQLite
– It is a open source relational SQL database that stores data to a
text file on a device.
– Lightweight and file-based, ideal for mobile devices
– Databases are private for the application that creates them
– Databases should not be used to store files
– It performs database operations on android device such as storing,
manipulating or retrieving persistent data from the database.
• SQLite is a light weight database
– Atomic
– Stable
– Independent
– Enduring
– Only several kilobytes
– Only partly support some SQL commands such as ALTER, TABLE.
• SQLite is included as part of Android’s soIware stack
• More info about SQLite at http://www.sqlite.org
5
Contd.
• It is embedded in android by default. So there is no
need to perform any database setup or administration
task.
• Here, we are going to see the example of SQLite to
store and fetch data.
• Steps involved for using SQLite databases:
1. Create a database
2. Open the database
3. Create a table
4. Create and insert interface for datasets
5. Create a query interface for datasets
6. Close the database
• Good practice to create a Database Adapter class to
simplify your database interactions
Data Storage 6
Data Base Management using SQLite
Examining the Database Files
• Databases are stored in the /data/data/<package-name>/databases
directory.
• Run your app in emulator and click on Tools > Android > Android Device
Monitor from Android Studio.
• All steps are given in next slide.
• This database is saved on mobile. If you want to see its contents in your
local PC, you can export it by clicking the button Pull a file from the Device.
Save it wherever you want.
• If you have SQLite installed on your computer, you can use its terminal to
view this database.
• Another way is to use FireFox plugin. Open FireFox, go to settings. Click on
AddOns. Search for AddOns called SQLite.
• If you don’t see it, go to following link;
• https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
• Install the SQLite Manager from there. Restart your browser now.
• Go to Settings, and click on Customize. Drag and drop SQLite Manager in
Tools to quickly view it every time.
• Now you can Browse you database. Be sure to select All Files before
browsing otherwise your database will not be shown.
Contd.
SQLiteOpenHelper
android.database.sqlite.SQLiteOpenHelper
• It is a helper class to manage database creation and version management.
Public Constructor
SQLiteOpenHelper(Context context, String name, Create a helper object to create,
SQLiteDatabase.CursorFactory factory, int version) open, and/or manage a database.

Public Methods
synchronized void close() Close any open database object.
Return the name of the SQLite database
String getDatabaseName()
being opened, as given to the constructor.
SQLiteDatabase getReadableDatabase() Create and/or open a database.
Create and/or open a database that will
SQLiteDatabase getWritableDatabase()
be used for reading and writing.
Called when the database is created for
abstract void onCreate(SQLiteDatabase db)
the first time.
onDowngrade(SQLiteDatabase db, int Called when the database needs to be
void
oldVersion, int newVersion) downgraded.
Called when the database has been
void onOpen(SQLiteDatabase db)
opened.
onUpgrade(SQLiteDatabase db, int Called when the database needs to be
abstract void
oldVersion, int newVersion) upgraded.
SQLiteDatabase
android.database.sqlite.SQLiteDatabase
• Database names must be unique within an application, not across all
applications.
Public Methods
static SQLiteD create(SQLiteDatabase.CursorFactory fact Create a memory backed SQLite database.
atabase ory)
int delete(String table, String whereClause, Str Convenience method for deleting rows in the
ing[] whereArgs) database.
static boolean deleteDatabase(File file) Deletes a database including its journal file and other
auxiliary files that may have been created by the
database engine.
void execSQL(String sql) Execute a single SQL statement that is NOT a
SELECT or any other SQL statement that returns data.
void execSQL(String sql, Object[] bindArgs) Execute a single SQL statement that is NOT a
SELECT/INSERT/UPDATE/DELETE.
long getMaximumSize() Returns the maximum size the database may grow to.
final String getPath() Gets the path to the database file.
int getVersion() Gets the database version.
long insert(String table, String nullColumnHack, Convenience method for inserting a row into the
ContentValues values) database.

static SQLiteD openDatabase(String path, SQLiteDatabas Open the database according to the
atabase e.CursorFactory factory, int flags OPEN_READWRITE OPEN_READONLY CREA
flags, DatabaseErrorHandler errorHandler) TE_IF_NECESSARY and/or NO_LOCALIZED_COLLA
TORS.
Contd.
Public Methods
static SQLiteData openDatabase(String path, SQLiteDatabase.CursorFa Open the database according to the
base ctory factory, int flags) flags OPEN_READWRITE OPEN_REA
DONLY CREATE_IF_NECESSARY an
d/or NO_LOCALIZED_COLLATORS.
static SQLiteData openOrCreateDatabase(String path, SQLiteDatabase. Equivalent to openDatabase(path,
base CursorFactory factory, DatabaseErrorHandler errorHan factory, CREATE_IF_NECESSARY,
dler) errorHandler).
Cursor query(String table, String[] columns, String selection, S Query the given table, returning
tring[] selectionArgs, String groupBy, String having, Stri a Cursor over the result set.
ng orderBy, String limit)
Cursor rawQuery(String sql, String[] selectionArgs, Cancellatio Runs the provided SQL and returns
nSignal cancellationSignal) a Cursor over the result set.
Runs the provided SQL and returns
a Cursor over the result set.
long setMaximumSize(long numBytes) Sets the maximum size the database
will grow to.
void setVersion(int version) Sets the database version.
String toString() Returns a string containing a concise,
human-readable description of this
object.
int update(String table, ContentValues values, String wher Convenience method for updating rows
eClause, String[] whereArgs) in the database.
Cursor
android.database.Cursor
• This interface provides random read-write access to the result set returned by
a database query.
Public Methods
Closes the Cursor, releasing all of its resources and making it
abstract void close()
completely invalid.
copyStringToBuffer(int
Retrieves the requested column text and stores it in the buffer
abstract void columnIndex, CharArrayBuffer
provided.
buffer)
abstract int getColumnCount() Return total number of columns
getColumnIndex(String Returns the zero-based index for the given column name, or -
abstract int
columnName) 1 if the column doesn't exist.
Returns a string array holding the names of all of the columns
abstract
getColumnNames() in the result set in the order in which they were listed in the
String[]
result.
abstract int getCount() Returns the numbers of rows in the cursor.
abstract
getDouble(int columnIndex) Returns the value of the requested column as a double.
double
abstract
getExtras() Returns a bundle of extra values.
Bundle
abstract float getFloat(int columnIndex) Returns the value of the requested column as a float.
abstract int getInt(int columnIndex) Returns the value of the requested column as an int.
abstract int getPosition() Returns the current position of the cursor in the row set.
abstract
getString(int columnIndex) Returns the value of the requested column as a String.
String
Cursor
Public Methods
Returns data type of the given column's
abstract int getType(int columnIndex)
value.
Returns whether the cursor is pointing to
abstract boolean isAfterLast()
the position after the last row.
Returns whether the cursor is pointing to
abstract boolean isBeforeFirst()
the position before the first row.
abstract boolean isClosed() return true if the cursor is closed
Returns whether the cursor is pointing to
abstract boolean isFirst()
the first row.
Returns whether the cursor is pointing to
abstract boolean isLast()
the last row.
Returns true if the value in the indicated
abstract boolean isNull(int columnIndex)
column is null.
abstract boolean moveToFirst() Move the cursor to the first row.
abstract boolean moveToLast() Move the cursor to the last row.
abstract boolean moveToNext() Move the cursor to the next row.
abstract boolean moveToPosition(int position) Move the cursor to an absolute position.
abstract boolean moveToPrevious() Move the cursor to the previous row.
ContentValues
android.content.ContentValues
• This class is used to store a set of values.
Public Constructors
ContentValues() Creates an empty set of values using the default initial size
ContentValues(int size) Creates an empty set of values using the given initial size

Public Methods
void clear() Removes all values.
Returns true if this object has the named
boolean containsKey(String key)
value.
Compares this instance with the specified
boolean equals(Object object)
object and indicates if they are equal.
Object get(String key) Gets a value.
Boolean getAsBoolean(String key) Gets a value and converts it to a Boolean.
Byte getAsByte(String key) Gets a value and converts it to a Byte.
byte[] getAsByteArray(String key) Gets a value that is a byte array.
Double getAsDouble(String key) Gets a value and converts it to a Double.
Float getAsFloat(String key) Gets a value and converts it to a Float.
Integer getAsInteger(String key) Gets a value and converts it to an Integer.
String getAsString(String key) Gets a value and converts it to a String.
void put(String key, Byte value) Adds a value to the set.
void put(String key, Integer value) Adds a value to the set.
SQLite Example: Contact data?
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){ }
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}

public Contact(String name, String _phone_number){


this._name = name;
this._phone_number = _phone_number;
}

Data Storage 15
Contd.
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getPhoneNumber(){
return this._phone_number;
}
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
Data Storage 16
Contd.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {


private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String TABLE_CONTACTS = "contacts“
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION); }

Data Storage 17
Contd.
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS +
"(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again


onCreate(db);
}

Data Storage 18
Contd.

/ code to add the new contact


void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
//2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}

Data Storage 19
Contd.
// code to get the single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,


KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),


cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}

Data Storage 20
Contd.
// code to update the single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}

// Deleting single contact


public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
Data Storage 21
Content Providers
• Store and retrieve data and make it available to all applications
– Only way to share data across applications
• Standard content providers part of Android:
– Common data types (audio, video, images, personal contact
information)
• Applications can create their own content providers to make
their data public
– Alternatively add the data to an existing provider
• Implement a common interface for querying the provider,
adding, altering and deleting data
• Actual storage of data is up to the designer
• Provides a clean separation between the application layer and
data layer

Data Storage 22
Accessing Content
• Applications access the content through a
ContentResolver instance
– ContentResolver allows querying, inserting, deleting and
updating data from the content provider
ContentResolver cr = getContentResolver();

cr.query(People.CONTENT_URI, null, null, null, null); //querying


contacts

ContentValues newvalues = new ContentValues();


cr.insert(People.CONTENT_URI, newvalues);

cr.delete(People.CONTENT_URI, null, null); //delete all contacts

Data Storage 23

You might also like