MD Notes
MD Notes
Class:III BCA
There are two dominant platforms in the modern smart phone market. One is the
iOS platform from Apple Inc. The iOS platform is the operating system that powers
Apple's popular line of iPhone smart phones. The second is Android from Google. The
Android operating system is used not only by Google devices but also by many other
OEMs to built their own smart phones and other smart devices.
Although there are some similarities between these two platforms when building
applications, developing for iOS vs. developing for Android involves using different
software development kits (SDKs) and different development tool chain. While Apple
uses iOS exclusively for its own devices, Google makes Android available to other
companies provided they meet specific requirements such as including certain Google
applications on the devices they ship. Developers can build apps for hundreds of millions
of devices by targeting both of these platforms.
There are four major development approaches when building mobile applications
Each of these approaches for developing mobile applications has its own set of
advantages and disadvantages. When choosing the right development approach for their
projects, developers consider the desired user experience, the computing resources and
native features required by the app, the development budget, time targets, and resources
available to maintain the app.
Native Applications:-
Cross-Platform Applications:-
Hybrid-Web Applications:-
Hybrid mobile applications are built with standard web technologies - such as
JavaScript, CSS, and HTML5 - and they are bundled as app installation packages.
Contrary to the native apps, hybrid apps work on a 'web container' which provides a
browser runtime and a bridge for native device APIs via Apache Cordova.
At the highest level, there are four main ways that native apps differ from hybrid
apps as illustrated in the following table.
Native Hybrid
Platform Specific Cross Platform
Compiled Language Scripting / Compiled
Access to Device Hardware Plugins / Native Modules
Platform Frameworks Web Frameworks
Why Choose the Hybrid/Cross-platform Approach?
There are two interlinked core components of a mobile application: 1) the mobile
application “Front-End” that resides on the mobile device, and 2) the services “Back-
End” that supports the mobile front-end.
Front-end vs. Back-end:-
In the early days of the modern smartphone applications era, mobile applications
went through a similar evolution as first websites. At first, the applications and sites
where wholly contained within themselves and acted as little more than static
advertisements for the brand, company, product, or service.
The mobile front-end obtains the data from the back-end via a variety of service
calls such as APIs. In some cases, these APIs may be owned and operated by the same
entity developing the mobile application. In other cases, the API may be controlled by a
third party and access is granted to the mobile application via a commercial arrangement.
For most of the applications, mobile developers are responsible for creating and
managing the back-end services for their application. The mobile developer may not be
an expert or even particularly skilled in spinning up and running a back-end
infrastructure.
The mobile front-end is the visual and interactive part of the application the user
experiences. It usually resides on the device, or there is at least an icon representing the
app that is visible on the home screen or is pinned in the application catalog of the device.
The application can be downloaded from the platform app store, side-loaded directly onto
the device, or can be reached through the device’s browser, as in the case for PWAs.
When a developer says they are a mobile application programmer, they are most
often referring to this front-end part of the application, and they are skilled in the
languages and technologies that are used to create this front-end application.
Depending on the size of the team producing the app, there may be many different
people involved in the design and development of the front-end mobile app. The team
size can range from a single developer who does everything associated with building the
app, to tens, hundreds, and more people with specialized skills.
Alternatively, the developer can utilize a specialized API when interacting with
the database; the developer may only have to know the parameters needed in a method
call to get or updated the needed information. In some cases, the mobile developer may
develop these APIs themselves or use the API definition provided to them by the
owner/operator of the back-end resource.
Typically, a REST API is used to interact with data sources on the cloud, such as a
cloud database. A GraphQL API is also another option for developers, as it makes easy to
work with backend data in a mobile application. GraphQL provides querying support
through a single API endpoint, and a data schema that can be used to build and easily
extend data models that are used in the app.
Given the critical importance of back-end services for the success of the mobile
application, the developers have several important architectural decisions that they must
consider. These decisions include which services should they build themselves and which
third party services should they leverage, and then should they run and maintain their
own services or should they take advantage of 3rd party services.
The answer is increasingly clear; to improve developer productivity and efficiency,
mobile app programmers should only build their own services if they are highly specific
to the domain of the application and embody unique intellectual property. Also, even for
the services they build themselves, they should almost always leverage cloud-based
services to build and maintain their backend infrastructure.
There are hundreds of cloud and 3rd party services that mobile application
developers can leverage to speed up the development and delivery of their applications.
However, it’s unlikely that a developer is going to be able to become an expert in each of
these individual services.
Instead, the mobile developers should look for a development environment that makes it
easier for them to integrate, use, and consume the most commonly required capabilities
into their application quickly and easily, while still preserving the freedom to take
advantage of the many individual services available.
Essential:-
Data Services:-
• Cloud Storage:-
Cloud storage is a cloud computing model that enables storing data and files on
the internet through a cloud computing provider that you access either through the public
internet or a dedicated private network connection.
• Real-time and Offline Data:-
Offline data entry allows compilation and synchronization of data and information
from all sources. Data entry clerks read and enter data from papers, CDs, DVDs,
electronic gadgets, files, documents, bills, books and online resources, among others.
Even data collected from online sources can also be assigned to offline clerks for
compilation with greater accuracy. Offline data entry also enables clients to save almost
half of their operational and overhead costs as outsourcing vendors offer combined data
conversion and compilation package services.
Online data entry is the compilation of data from internet sources and compiling it
in a format suitable for online storage and accessibility. This data entry method involves
processes such as:
Data entry
Data mining
Data extraction
Typing
Web research
These processes help find relevant information online and it is then arranged in an
orderly manner. The collected data and information are converted into a digital format
and is compiled for use on computers. In online data entry, a database is created to store
and access the information from any location
Machine Learning:-
• Conversational Bots:-
Chatbots are able to automate human tasks by translating fluidly between
unstructured language and structured data. Imagine a customer service chat via instant
message, email, or voice where the bot has answers before you can ask the question.
• Image and Video Recognition:-
Image recognition is the process of identifying an object or a feature in an image or
video. It is used in many applications like defect detection, medical imaging, and security
surveillance.
Image & Video Recognition solutions tailored to customer needs.
Starting from visual data we offer services of:
Identification of licence plates
Identification of people
Vehicle identification
Object identification
Animal identification
Emotion recognition
Recognition and segmentation of people by age
Recognition and segmentation of people by gender
Check facial features of people even within groups
Face / name matching
• Speech Recognition:-
Speech recognition, or speech-to-text, is the ability of a machine or program to
identify words spoken aloud and convert them into readable text. Rudimentary speech
recognition software has a limited vocabulary and may only identify words and phrases
when spoken clearly.
Android Versions
The development of the Android operating system was started in 2003 by
Android, Inc. Later on, it was purchased by Google in 2005. The beta version of Android
OS was released on November 5, 2007, while the software development kit (SDK) was
released on November 12, 2007.
The first Android mobile was publicly released with Android 1.0 of the T-Mobile
G1 (aka HTC Dream) in October 2008.
Google announced in August 2019 that they were ending the confectionery
scheme, and they use numerical ordering for future Android versions.
The first Android version which was released under the numerical order format was
Android 10.
Internal Version
Name
codename[9] number(s)
2.0
Android HYPERLINK
Eclair 2.0.1
"https://en.wikipedia.org/wiki/Android_Eclair"Eclair
2.1
Android HYPERLINK
Froyo 2.2 – 2.2.3
"https://en.wikipedia.org/wiki/Android_Froyo"Froyo
2.3 – 2.3.2
Android Gingerbread Gingerbread
2.3.3 – 2.3.7
3.0
Android Honeycomb Honeycomb
3.1
3.2 – 3.2.6
4.0 – 4.0.2
Ice Cream
Android Ice Cream Sandwich
Sandwich
4.0.3 – 4.0.4
4.1 – 4.1.2
4.3 – 4.3.1
4.4 – 4.4.4
Android HYPERLINK
Key Lime Pie
"https://en.wikipedia.org/wiki/Android_KitKat"KitKat 4.4W –
4.4W.2
5.0 – 5.0.2
Lemon
Android Lollipop
Meringue Pie
5.1 – 5.1.1
Macadamia Nut
Android Marshmallow 6.0 – 6.0.1
Cookie
7.0
New York
Android Nougat
Cheesecake
7.1 – 7.1.2
8.0
Android Oreo Oatmeal Cookie
8.1
Pistachio Ice
Android Pie 9
Cream[20]
Red Velvet
Android 11 11
Cake[21]
Android 13 Tiramisu[23] 13
• Accessibility: Perceptive apps help us to control and navigate our phone using
voice command.
• Device controls: Android 11 allows us to control all our connected devices (IOT)
from a single point.
• Content capture: Android 11 comes with a screen recording feature that captures
our phone's current screen activity.
• Predictive tools: By predicting our habits and patterns of working, it suggests
accordingly.
• Privacy & security: Android 11 gives more security and privacy fixes to our
smartphone straight from Google Play.
• Media: We can play music from other devices connected to our phones.
Android version 12
Google officially launched the final version of Android 12 in October 2021 and
started rolling the software out to its own Pixel devices soon after — alongside the launch
of its new Pixel 6 and Pixel 6 Pro phones. Android 12's design principles will stretch into
both apps on your phone and Google services on the web. The same principles will show
up on Chromebooks, Smart Displays, and Google-associated wearables as well.
Android version 13
Android 13, launched in August 2022, is one of Google's strangest Android
versions yet. The software is simultaneously one of the most ambitious updates in
Android history and one of the most subtle version changes to date. It's an unusual
duality, and it ultimately all comes down to what type of device you're using to
experience the software. On the former front, Android 13 introduces a whole new
interface design for both tablets and foldable phones, with a renewed focus on creating an
exceptional large-screen experience in the operating system itself and within apps (as first
observed and reported by Computerworld in January). The enhancements in that area
include a fresh framework and series of guidelines for app optimizations along with a
more capable split-screen mode for multitasking and a ChromeOS-like desktop-style
taskbar that makes it easy to access frequently used apps from anywhere.
Android 13 started rolling out to Google's current Pixel phones in August. If past Android
upgrade trends are any indication, it'll likely reach the first non-Google-made devices
later this year and then continue rolling out slowly to more phones and tablets as the
months progress.
AndroidStudio
ThefirstandmostimportantpieceofsoftwareyouneedtodownloadisAndroidStudio2.Afte
ryouhavedownloadedandinstalledAndroidStudio2,youcanusetheSDKManagertodow
nloadandinstallmultipleversionsoftheAndroidSDK.HavingmultipleversionsoftheSDK
availableenablesyoutowriteprogramsthattargetdifferentdevices.Forexample,youcanw
riteoneversionofanapplicationthatspecificallytargetsAndroidNougat,butbecausethatfl
avorofAndroidis
on less than 1% of devices, with multiple versions of the SDK you can also write a
version of yourapp that uses older features and targets Marshmallow or Lollipop
users. You can use the AndroidDeviceManagertosetupdeviceemulators.
AndroidStudio2ispackagedinanexecutable.RuntheinstallprocesstosetupAndr
oidStudio
AndroidSDK
Themostimportantpieceofsoftwareyouneedtodownloadis,ofcourse,theAndroidSDK.
TheAndroidSDKcontainsallofthepackagesandtoolsrequiredtodevelopafunctionalAn
droidapplication.TheSDKsarenamedaftertheversionofAndroidOStowhichtheycorres
pond.Bydefault,theMarshmallowSDKwasinstalledwithAndroidStudio2,whichmeans
youcandevelopapplicationsthatwillrunseamlesslyondeviceswithAndroidMarshmallo
w.
However,ifyouwanttoinstalladifferentAndroidSDK,youcandosousingtheSDKManag
erfromtheAndroidStudiowelcomescreenFromthisscreen,clicktheConfiguredrop-
downmenuinthelower-rightcorner.TheConfigureselectionmenuopens.
ChooseSDKManagerfromthismenu.
TheSDKconfigurationscreen,showsthattheMarshmallowSDKisalreadyinsta
lled.AndroidNisavailabletobeinstalled.
LaunchingYourFirstAndroidApplication
New terminologies:-
Method - A block of code that only runs when called and performs an action.
Activity - This is one screen on an Android App’s user interface.
Fragment - A Fragment represents a reusable portion of your app’s UI.
We find the Java classes for the Activities in the Java Folder -> first folder with
the Application’s package name
In the first activity outside the onCreate method, call the onClick you created in
the XML on the button.
Inside this method, convert the text input from the user to a String.
Then create an extra that will facilitate parsing of the data.
Finally, create an intent that refers to a messaging object used to request an action
from another app component. The action requested in this case is Activity
navigation.
To start debugging, click Debug in the toolbar. Android Studio builds an APK,
signs it with a debug key, installs it on your selected device, then runs it and opens
the Debug pane with the Debugger and Console tabs.
The Debugger tab is selected, showing the Debugger pane with the following
features:
• Frames tab: Click to show the Frames pane with the current execution stack frames
for a given thread. The execution stack shows each class and method that have been
called in your app and in the Android runtime, with the most recent method at the top.
Click the Threads tab to replace the Frames pane with the Threads pane.
• Watches button: Click to show the Watches pane within the Variables pane, which
shows the values for any variable watches you have set. Watches allow you to keep
track of a specific variable in your program, and see how that variable changes as your
program runs.
• Variables pane: Shows the variables in the current scope and their values. Each
variable in this pane has an expand icon to expand the list of object properties for the
variable. Try expanding a variable to explore its properties.
If your app is already running on a device or emulator, start debugging that app
with these steps:
• Select Run > Attach debugger to Android process or click the Attach icon in the
toolbar.
• In the Choose Process dialog, select the process to which you want to attach the
debugger.
By default, the debugger shows the device and app process for the current project, as
well as any connected hardware devices or virtual devices on your computer. Check
the Show all processes option to show all processes on all devices.
• Click OK. The Debug pane appears as before.
To resume executing an app after debugging it, select Run > Resume Program or
click the Resume icon.
To stop debugging your app, select Run > Stop or click the Stop icon in the toolbar.
Using breakpoints
Android Studio supports several types of breakpoints that trigger different debugging
actions. The most common type is a breakpoint that pauses the execution of your app
at a specified line of code. While paused, you can examine variables, evaluate
expressions, then continue execution line by line to determine the causes of runtime
errors.
You can set a breakpoint on any executable line of code.
Add breakpoints
To view all the breakpoints you've set and configure breakpoint settings, click
the View Breakpoints icon on the left edge of the Debug pane.
The Breakpoints window appears.
In this window all the breakpoints you have set appear in the left pane, and you
can enable or disable each breakpoint with the checkboxes. If a breakpoint is disabled,
Android Studio does not pause your app when execution reaches that breakpoint.
Select a breakpoint from the list to configure its settings. You can configure a
breakpoint to be disabled at first and have the system enable it after a different
breakpoint is encountered. You can also configure whether a breakpoint should be
disabled after it has been reached.
To set a breakpoint for any exception, select Exception Breakpoints in the list of
breakpoints.
Conditional breakpoints are breakpoints that only stop execution of your app if
the test in the condition is true. To define a test for a conditional breakpoint, use these
steps:
• Right-click (or Control-click) a breakpoint, and enter a test in the Condition field.
The test you enter in this field can be any Java expression as long as it returns a
boolean value. You can use variable names from your app as part of the expression.
You can also use the Breakpoints window to enter a breakpoint condition.
• Run your app in debug mode. Execution of your app stops at the conditional
breakpoint, if the condition evaluates to true.
Setting watches:-
The Watches pane provides similar functionality to the Variables pane except
that expressions added to the Watches pane persist between debugging sessions. Add
watches for variables and fields that you access frequently or that provide state that is
helpful for the current debugging session.
To use watches:
• Begin debugging your app.
• Click the Show Watches icon . The Watches pane appears next to
the Variables pane.
• In the Watches pane, click the plus (+) button. In the text box that appears, type the
name of the variable or expression you want to watch and then press Enter.
Remove an item from the Watches list by selecting the item and then clicking the
minus (–) button.
Change the order of the elements in the Watches pane list by selecting an item and
then clicking the up or down icons.
PUBLISHINGYOURAPPLICATION
Afteryouhavecreated,andfullydebugged,yourapplication,youmightwanttodeployittot
heGoogleStoreforotherstoenjoy.Thefollowingsectionsoutlinethestepsforpublishingyourapp
lications.
GeneratingaSignedAPK
TopublishyourfinishedapplicationontheGooglePlayStore,youmustgenerateasignedA
PK
(theAndroidapplicationpackage).TheAPKisthecompiled,executableversionofyourap
plication.Signingitismuchlikesigningyournametoadocument.Thesignatureidentifiest
heapp’sdevel-
opertoGoogleandtheuserswhoinstallyourapplication.Moreimportantly,unlessyourAn
droidStudioisindevelopermode,unsignedapplicationswillnotrun.Usethefollowingstep
stogenerateasignedAPK:
• GenerateasignedAPKfromyourcodebyselectingBuild➪GenerateSig
nedAPKfromtheMenubartobringuptheGenerateSignedAPKwindow
asshowninFigure2-17.
FIGURE2-17
• AssumingyouhaveneverpublishedanapplicationfromAndroidStudio,youneedt
ocreateanewkeystore.ClicktheCreateNewbuttontodisplaytheNewKeyStorewin
dow(seeFigure2-18).
• Filloutalloftheinformationonthisformbecauseitpertainstoyourentityandapplica
tion.
Notice that there are two places for a password. These are the passwords for
your key storeand your key, respectively. Because a key store can hold
multiple keys, it requires a separatepasswordthanthatofthekeyforaspecificapp.
4. ClickOK to return tothe Generate Signed APKwindow.
5.
IntheGenerateSignedAPKwindows,clickNexttoreviewandfinishtheprocess.
NowthatyouhaveasignedAPK,youcanuploadittotheGooglePlayStoreusingth
edeveloperconsoleathttps://play.google.com/apps/publish/.
UNIT-III
USINGBASICVIEWS
Views:-
View is the basic building block of UI(User Interface) in android. In
Android Application the commonly used views such as the TextView, EditText, and Button
Views are called Basic Views. Some of the basic views that can be used in Android
applications are
➤ TextView
➤ EditText
➤ Button
➤ ImageButton
➤ CheckBox
➤ ToggleButton
➤ RadioButton
➤ RadioGroup
Syntax:-
<ViewName
Attribute1=Value1
Attribute2=Value2
Attribute3=Value3
.
.
AttributeN=ValueN/>
These basic views enable you to display text information,as well as perform
some basic selection.
TextView View:-
TextView is the most widely used view used to show pre-defined text on display
screen.
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello"
android:textSize="45sp"
android:padding="20dp"
android:textColor="#DD2C00"/>
Attributes:-
1.android:id="@+id/name"
This gives an id(identification) to this textview which can be used in Java files to
access this textview and to make any changes to it dynamically.
2. android:text="Hello"
The TextView will show the given value in the attribute as the text.
3.android:textSize="45sp"
This is used to determine the size of the text displayed in the TextView.
4.android:padding="20dp"
This provides a padding of 20dp arround the text.
5.android:textColor="#DD2C00"
This sets the color of the text. #DD2C00 is the hexa code for color some dark
red shade.
O/P:-
EditText View:-
EditText is used to get data from user in android application. It can be either single
line or multi-line. Touching a text field places makes the field active, places a cursor and
automatically displays the keyboard.
<EditText
android:id="@+id/et_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Write your email Address here"
android:textSize="20sp"
android:inputType="textWebEmailAddress"
android:maxLines="3"/>
Attributes:-
android:hint:-
This attribute gives a hint to the user about what should be entered in the box. This
is a temporary message that goes off as soon as the user starts to write anything in
the field.
android:inputType-This attribute specifies what the text entered should be like and for
what purpose it will be used.
Text- Used to display content.
textAutoComplete - This provides with suggestions as user is typing in text.
textAutoCorrect - This will enable auto correct on user input text.
textPassword - Display the entered text in form of dots or stars.
phone - This will present only the numeric keyboard to users.
android:maxLines="3"
This displays at max. only 3 lines of text.
O/P:-
Button: It is a component which can be pressed or clicked by the user to perform an action. It
has the same properties as a TextView, with a few Button specific properties.
<Button
android:id="@+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:gravity=”Center”
android:textColor="@android:color/holo_blue_dark" />
Attributes:-
android:gravity: This can be used to set the position of any View on the app screen.
The available value are right, left, center, center_vertical etc. It can also be use to
values together, using the | symbol.
}
});
}
}
ToggleButton:-
A control of type ToggleButton is a type of button that can remain in two possible
states, pressed or not-presses so that’s why we need to declare the properties of textOn
and TextOff If we want two different text in the button.
The ToggleButton displays a rectangular button that users can toggle on and off by
clicking:
<ToggleButton
android:id="@+id/toggle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
O/P:-
imageButton = (ImageButton)findViewById(R.id.imgButton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do anything here
}
});
ImageView: The ImageView control allows displaying images in the application. The most
interesting property is android: src, which allows you to indicate the image to be displayed.
Again, the normal thing will be to indicate as the origin of the image the identifier of a
resource of our folder / res / drawable.
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/img_nature"/>
Attributes:-
android:maxHeight -Used to specify a maximum height for this view.
android:maxWidth -Used to specify a maximum width for this view.
android:src -Sets a drawable as the content for this ImageView.
android:scaleType -Controls how the image should be resized or moved to match the size of
the ImageView.
Radio buttons: Like the checkbox controls, a radio button can be marked or unmarked, but
in this case they are usually used within a group of options where one, and only one, of them
must be marked, that is, if the options, the one that was previously active will be
automatically unchecked. You need to regroup all these button in a RadioGroup to make it
know the group. RadioButton is used when you have to allow selection of only one option
among the list of multiple options. It is used under its parent view – RadioGroup so that we
can get one selected value out of all the listed radio buttons.
<RadioGroup
android:id="@+id/rg_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp">
<RadioButton
android:id="@+id/rb_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:textColor="@android:color/black"/>
<RadioButton
android:id="@+id/rb_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:text="Female"/>
</RadioGroup>
AutoCompleteTextView View
The AutoCompleteTextView is a view that is similar to EditText except that it
automatically shows a list of completion suggestions while the user is
typing.
<AutoCompleteTextView
android:id="@+id/txtCountries"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
String[] presidents = {
"Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon",
"Gerald Ford",
"Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush",
"Barack Obama"
};
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Picker Views
Date Picker
Android DatePicker is a widget to select date. It allows you to select date by day,
month and year.If we use DatePicker in our application, it will ensure that the users will
select a valid date.In android DatePicker available in two modes, one is to show the complete
calendar and another one is to show the dates in spinner view.
Common Atrributes:-
android:id -It is used to uniquely identify the control
android:datePickerMode -It is used to specify datepicker mode either spinner or calendar
android:background- It is used to set the background color for the date picker.
android:padding -It is used to set the padding for left, right, top or bottom of the date
picker.
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:datePickerMode="calendar" />
DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>
public class MainActivity extends AppCompatActivity {
DatePicker picker;
Button btnGet;
TextView tvw; protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker1);
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ picker.getDayOfMonth()+"/"+
(picker.getMonth() + 1)+"/"+picker.getYear());
}
});
}
}
TimePicker:-TimePicker is a widget used for selecting the time of the day in either
AM/PM mode or 24 hours mode. The displayed time consist of hours, minutes and clock
format. If we need to show this view as a Dialog then we have to use a TimePickerDialog
class.
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
1 is24HourView()
This method returns true if this is in 24 hour view else false
2 isEnabled()
This method returns the enabled status for this view
3 setCurrentHour(Integer currentHour)
This method sets the current hour
4 setCurrentMinute(Integer currentMinute)
This method sets the current minute
5 setEnabled(boolean enabled)
This method set the enabled state of this view
6 setIs24HourView(Boolean is24HourView)
This method set whether in 24 hour or AM/PM mode
7 setOnTimeChangedListener(TimePicker.OnTimeChangedListeneronTimeChangedLis
This method Set the callback that indicates the time has been adjusted by the user
publicclassMainActivityextendsAppCompatActivity{
TimePickertimePicker;
publicvoidonCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);
timePicker=(TimePicker)findViewById(R.id.timeP
icker);timePicker.setIs24HourView(true);
}
}
Using a Dialog to Display the TimePicker View
public class MainActivity extends AppCompatActivity
{TimePickerDialog.OnTimeSetListenerdialogListener=newTimePickerDialog
.OnTimeSetListener(){
@Override
publicvoidonTimeSet(TimePickertimePicker,inti,inti1){
}
};
Calendarcal=Calendar.getInstance();
@Override
Public void
onCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showTimeDialog();
}
ListViewlstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lstView.setTextFilterEnabled(true);
setListAdapter(newArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked,presidents));
}
Using the SpinnerView
The SpinnerView displays one item at a time from a list and enables users to
choose from them.
<Spinner
android:id="@+id/spinner1"android:layout_
width="wrap_content"android:layout_height="
wrap_content"android:drawSelectorOnTop="tr
ue"/>
Addthefollowinglinestothestrings.xmlfilelocatedintheres/valuesfolder:
<resources>
<string-arrayname="presidents_array">
<item>DwightD.Eisenhower</item>
<item>JohnF.Kennedy</item>
<item>LyndonB.Johnson</item>
<item>RichardNixon</item>
<item>GeraldFord</item>
</string-array>
</resources>
Using a ListFragment
A list fragment is a fragment that contains a ListView, which displays a list of
items from a data source, such as an array or a Cursor. A listfragment is useful
because it’s common to have one fragment that contains a list of items,and
another fragment that displays details about the selected posting. To create a list
fragment,you need to extend the ListFragment baseclass.
import android.app.ListFragment;
public class Fragment1 extends ListFragment {
String[] presidents = {
"Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon",
"Gerald Ford",
"Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush",
"Barack Obama"
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
}
Using a DialogFragment
A dialog fragment floats on top of an activity and is displayed
modally.Dialogfragments are usefull when you need to obtain the user’s
response before continuing with execution. To create a dialogfragment,you must
extend the DialogFragmentbaseclass.
1. Create an Android project and name it DialogFragmentExample.
2. AddaJavaClassfileunderthepackageandnameitFragment1.
publicvoiddoPositiveClick(){
Log.d("DialogFragmentExample","UserclicksonOK");
}
publicvoiddoNegativeClick(){
Log.d("DialogFragmentExample","UserclicksonCancel");
}
}
Using a PreferenceFragment
In Android,you can use the Preference Activity base class to display an activity for the user
to edit the preferences.
<PreferenceScreenxmlns:android="http://schemas.android.com/apk/res/a
ndroid">
<PreferenceCategory
android:title="Category1">
<CheckBoxPreference
android:title="Checkbox"
android:defaultValue="false"
android:summary="TrueofFalse"
android:key="checkboxPref"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Category2">
<EditTextPreference
android:name="EditText"
android:summary="Enterastring"
android:defaultValue="[Enterastringhere]"
android:title="Edit Text"
android:key="editTextPref"/>
<RingtonePreference
android:name="RingtonePreference"
android:summary="Selectaringtone"
android:title="Ringtones"
android:key="ringtonePref"/>
<PreferenceScreen
android:title="SecondPreferenceScreen"
android:summary=
"ClickheretogotothesecondPreferenceScreen"
android:key="secondPrefScreenPref">
<EditTextPreferenceandroid:name="EditText"
android:summary="Enterastring"
android:title="EditText(secondScreen)"
android:key="secondEditTextPref"/>
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
FragmentManager fragmentManager =
getFragmentManager();
FragmentTransactionfragmentTransaction=
fragmentManager.beginTransaction();
Fragment1fragment1=newFragment1();
fragmentTransaction.replace(android.R.id.content,fragment
1);
fragmentTransaction.addToBackStack(null);fragmentTrans
action.commit();
}
}
USINGIMAGEVIEWSTODISPLAYPICTURES
In Android, ImageView class is used to display an image file in application. In general
user can use the ImageView, ImageSwitcher, and GridView views for displaying images.
ImageView View
The ImageView is a view that shows images on the device screen.
<LinearLayout
android:id="@+id/activity_main"
android:layout_width="wrap_content"
android:layout_height="match_parent"
</LinearLayout>
ImageSwitcher
User may want to apply some animation to an image when it transitions from
one image to another.
In this case,you need to use the ImageSwitcher.
<Button
android:text="View Windows"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
/>
<ImageSwitcher
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="@+id/button2"
android:id="@+id/imageSwitcher">
</ImageSwitcher>
<Button
android:text="View Butterfly"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
/>
@Override
Protected void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgSwitcher=(ImageSwitcher)findViewById(R.id.imageSwit
cher);
imgSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
imgSwitcher.setOutAnimation(AnimationUtils.load
Animation(this,
android.R.anim.fade_out));
btnViewWindows = (Button)
findViewById(R.id.button2);
btnViewButterfly=(Button)findViewById(R.id.butto
n);
imgSwitcher.setFactory(new
ViewSwitcher.ViewFactory() {@Override
publicViewmakeView(){
ImageViewmyView = new
ImageView(getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CEN
TER);myView.setLayoutParams(newImageSwitcher.La
youtParams(
ActionBar.LayoutParams.WRAP_CONTENT,ActionBar.LayoutParams.
WRAP_CONTENT));returnmyView;
}
});
btnViewWindows.setOnClickListener(newView.OnClickLi
stener(){@Override
public void onClick(View v)
{Toast.makeText(getApplicationCon
text(), "View
Windows",Toast.LENGTH_LONG).
show();imgSwitcher.setImageResourc
e(R.mipmap.windows);
}
});
btnViewButterfly.setOnClickListener(newView.OnClickListe
ner(){@Override
public void onClick(View v)
{Toast.makeText(getApplicationContext(),"ViewButt
erfly"
,Toast.LENGTH_LONG).show();
imgSwitcher.setImageResource(R.mipmap.butterfly);
}
});
}
}
GridView:-
The GridView shows items in a two-dimensional scrolling grid. Use the
GridView together with an ImageView to display a series of images.
<GridView
android:layout_width="384dp"/>
getView(int
P IImageView imageView;
u if(convertView==null){
b imageView=new
l ImageView(context);
i imageView.setLayoutParams(new
c GridView.L
V ayoutParams(150,1
i 50));
e imageView.
w
s
e
t
S
c
a
l
e
T
y
p
e
(
I ROP)
m ieetPadding(5,5,5,5)
a ;
g }else{
e imageView=(ImageView)convertView;
V }
i imageView.setImageReso
e urce(imageIDs[position]);
w return imageView;
. }
_ }
C }
USINGMENUS WITH VIEWS
Menu is an important part of the UI component which is used to provide some
common functionality around the application.
Menus are useful for displaying additional options that are not directly visible on
the main user interface(UI) of an application. There are two main types of menus
in Android:
➤ Optionsmenu—This menu displays information related to the current
activity. In Android, you activate the options menu by pressing the
Menubutton.
➤ Contextmenu—This menu displays information related to a particular view
on an activity.
In Android, you tap and hold a contextmenu to activate it.
OptionsMenu
To define the menu_file.xml file, first create a menu directory under res folder. This is
done by right clicking on res --> new --> Android resource directory.
android:id
A resource ID that's unique to the item, which allows the application to recognize the
item when the user selects it.
android:icon
android:title
If we want to add a submenu in menu item, then we need to add a <menu> element as the
child of an <item>.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http:// schemas.android.com/apk/res/android">
<item android:id="@+id/file"
android:title="@string/file" >
<!-- "file" submenu -->
<menu>
<item android:id="@+id/create_new"
android:title="@string/create_new" />
<item android:id="@+id/open"
android:title="@string/open" />
</menu>
</item>
</menu>
ContextMenu
A context menu is usually associated with a view on an activity.A contextmenu
is displayed when the user taps and holds an item. For example,if the user taps a
Button view and holds it for a few seconds, a context menu can be displayed.
To make a floating context menu, you need to follow the following steps:
Register the View to which the context menu should be associated by
calling registerForContextMenu() and pass it the View.
If your activity uses a ListView or GridView and you want each item to provide the same
context menu, you can register all items for a context menu by passing the ListView or
GridView object to registerForContextMenu() method.
Implement the onCreateContextMenu() method in your Activity.
When the registered view receives a long-click event, the system calls
your onCreateContextMenu() method. This is where you define the menu items, usually by
inflating a menu resource. For example:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_file, menu);
}
MenuInflater allows you to inflate the menu_file.xml file from a menu resource. The method
parameters include the View that the user selected and aC
ontextMenu. ContextMenuInfo object provides additional information about the item
selected. If your activity has several views such that each provide a different context menu,
you might use these parameters to determine which context menu to inflate.
Handling Click Events
When the user selects a menu item, the system calls onContextItemSelected() method so that
you can perform the appropriate action. For example:
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.i1:
//Perform any action;
return true;
case R.id.a:
//Perform any action;
return true;
case R.id.b:
//Perform any action;
return true;
default:
return super.onContextItemSelected(item);
}
}
USINGWEBVIEW
WebView:-
WebView is a view that display web pages inside your application. You can also
specify HTML string and can show it inside your application using WebView.
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
In AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
Methods:-
1.loadUrl() – Load a web page in our WebView
loadUrl(String url)
This function is used to load a web page in a web view of our application. In this method
we specify the url of the web page that should be loaded in a web view.
Email is messages distributed by electronic means from one system user to one or
more recipients via a network. Intent is carrying data from one component to another
component with-in the application or outside the application. Write an Activity that launches
an email client, using an implicit Intent with the right action and data.
1 EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.
2 EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3 EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.
4 EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to
supply an alternative to EXTRA_TEXT as HTML formatted text.
5 EXTRA_SUBJECT
A constant string holding the desired subject line of a message.
6 EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent.
7 EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a
ACTION_CHOOSER.
Here is an example showing you how to assign extra data to your intent −
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"Recipient"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject");
i.putExtra(Intent.EXTRA_TEXT , "Message Body");
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
In Android, use SmsManager API or devices Built-in SMS application to send SMS's. Use an
implicit Intent to launch a messaging app with the ACTION_SENDTO intent action. Send the
SMS message using the sendTextMessage() method or other methods of the SmsManager
class.
SmsManager API
In AndroidManifest.xml:-
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editText);
txtMessage = (EditText) findViewById(R.id.editText2);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
}
}
i.setData(Uri.parse("smsto:"));
i.setType("vnd.android-dir/mms-sms");
Intent Object - Extra to send SMS
Android has built-in support to add phone number and text message to send an SMS
Displaying Maps:-
Android provides facility to integrate Google map in our application. Google map
displays your current location, navigate location direction, search location etc.
In AndroidManifest.xml file.
Fine Location :
The Fine location provides better and accurate locations.
Coarse Location :
The Coarse location provides less accurate locations.
Adding Marker:-
User can place a maker with some text over it displaying your location on the map. It
can be done by via addMarker() method.
Syntax:-
LatLng ll= new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
.position(l1).title("TutorialsPoint"));
Enable/Disable zoom:-
User can enable or disable the zoom gestures in the map by calling the
setZoomControlsEnabled(boolean) method.
Syntax:-
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Zoom Gestures:-
ZoomIn: Double tap to increase the zoom level by 1.
Zoom Out: Two finger tap to decrease the zoom level by 1.
animateCamera:-This method Moves the map according to the update with an animation.
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomIn());
MapsActivity.java
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
private GoogleMap mMap;
In activitymain.xml:
<TextView
android:text="Please enter some text."
android:layout_width="245dp"
android:layout_height="wrap_content"
android:id="@+id/textView"/>
<EditText
android:layout_width="241dp"
android:layout_height="wrap_cont
ent"android:inputType="text"
android:ems="10"
android:id="@+id/editText"
/>
<Button
android:text="Save"
android:layout_width="240dp"
android:layout_height="wrap_cont
ent"android:id="@+id/btnSave"
android:onClick="onClickSave"/>
In the MainActivity.javafile:
Public class MainActivity extends AppCompatActivity{
EditText textBox;
Static final int READ_BLOCK_SIZE=100;
Protected void onCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textBox=(EditText)findViewById(R.id.editText);
}
OutputStreamWriterosw = newOutputStreamWriter(fOut);
osw.write(str);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(),
"File saved
successfully!",Toast.LEN
GTH_SHORT).show();
textBox.setText("");
}
}
SQLitedatabasethatyoucreateprogrammaticallyinanapplicationisalwaysstoredinthe/data
/data/<package_name>/databasesfolder.
Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class.
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)
{
Log.w(TAG,"Upgradingdatabasefromversion"+oldVersion+"to"
+ newVersion + ", which will destroy all old
data");db.execSQL("DROPTABLEIFEXISTScontacts");
onCreate(db);
}
}
//---insertacontactintothedatabase---
publiclonginsertContact(Stringname,Stringemail)
{
ContentValuesinitialValues=newContentValues();initialValues.p
ut(KEY_NAME, name);initialValues.put(KEY_EMAIL,email);
returndb.insert(DATABASE_TABLE,null,initialValues);
}
//---deletes a particular contact---
publicbooleandeleteContact(longrowId)
{
returndb.delete(DATABASE_TABLE,KEY_ROWID+"="+rowId,null)>0;
}
//---updatesacontact---
publicbooleanupdateContact(longrowId,Stringname,Stringemail)
{
ContentValuesargs=newContentValues();args
.put(KEY_NAME,
name);args.put(KEY_EMAIL,email);
returndb.update(DATABASE_TABLE,args,KEY_ROWID+"="+rowId,null)>
0;
}
}
UNIT V
Characteristics:-
1. Web services are XML – based. They use it at its data representational layer and its
transportational layer as it removes networking, operating system or even the platform
binding. These services are highly interoperable at their core level.
2. Web services are loosely coupled. That means the consumer web services and
providers of web service are not tied together directly.
4. Web Services supports Remote Procedure Calls. Remote Procedure calls can often be
referred to as RPCs. These RPCs let the clients invoke various functions, methods, and
services on remote objects using XML.
5. There is support to Document exchange in Web Services. In fact, XML has a very
generic way to represent data as well as complex documents. Along with that, it has got
various ways to represent these documents.
1. XML-RPC
In XML-RPC, RPC stands for remote procedure calls. It is an XML based protocol for
the exchange of data between a huge range of devices over the internet.
2. UDDI
UDDI stands for Universal Descriptive, discovery, and integration. It is an XML- based
standard used for detailing, publishing and discovering new web services.
3. SOAP
SOAP here stands for Simple object access protocol. It is an XML based web service
protocol used for the exchange of data or documents over HTTP(Hypertext transfer
protocol) or SMTP(Simple Message Transfer Protocol). It allows the communication of
independent processes that operate on disparate systems.
4. REST
Here, REST is Representational State Transfer. It provides communication and
connectivity between devices and the internet.
JSON stands for JavaScript Object Notation. It is a format for data exchange and storage.
When compared to XML, it is very simple and easy to parse information interchange
format. JSON is extensively used for data exchange between the device and server in
android applications.
1. JSON Objects
2. JSON Array
3. JSON Key-Value
This data is stored as a pair of keys and values. Here the keys can be a name, a number
for which the values can be Seema, 98767586 etc.
Examples:-
{ “students”: [
{ “name”: “Sia Sharma”, “city”: “Chandigarh”},
{ “name”: “Prachi D’Souza”, “city”: “Nagpur”},
{ “name”: “Annas Jones”, “city”: “Mumbai”}
]}
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = employee.getString("name");
salary = employee.getString("salary");
employeeSalary.setText("Salary: "+salary);
1. Foreground Services:
Services that notify the user about its ongoing operations are termed as Foreground
Services. Users can interact with the service by the notifications provided about the
ongoing task. Such as in downloading a file, the user can keep track of the progress in
downloading and can also pause and resume the process.
2. Background Services:
Background services do not require any user intervention. These services do not notify
the user about ongoing background tasks and users also cannot access them. The
process like schedule syncing of data or storing of data fall under this service.
3. Bound Services:
This type of android service allows the components of the application like activity to
bound themselves with it. Bound services perform their task as long as any application
component is bound to it. More than one component is allowed to bind themselves
with a service at a time. In order to bind an application component with a
service bindService() method is used.
Life Cycle of Android Service
There can be two forms of a service.The lifecycle of service can follow two different
paths: started or bound.
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.
Understanding Threading
Threads are the mini-processes running within a main process, the purpose of
which is to enable at least the appearance of parallel execution paths within applications.
When an Android application is first started, the runtime system creates a single thread in
which all application components will run by default. This thread is generally referred to
as the main thread. The primary role of the main thread is to handle the user interface in
terms of event handling and interaction with views in the user interface.
Threading in Android
In Android, you can categorize all threading components into two basic categories:
1. Threads that are attached to an activity/fragment: These threads are tied to the
lifecycle of the activity/fragment and are terminated as soon as the
activity/fragment is destroyed. Eg: AsyncTask , Loaders
2.Threads that are not attached to any activity/fragment: These threads can continue
to run beyond the lifetime of the activity/fragment (if any) from which they were
spawned. Eg:- Service
Intent Service
ASYNCTASK:-
AsyncTask is the most basic Android component for threading. It’s simple to use and can
be good for basic scenarios.
private class MyTask extends AsyncTask<String, Void, String> { @Override
protected String doInBackground(String... params) { String url = params[0];
return doSomeWork(url);
}
@Override protected void onPostExecute(String result) {
super.onPostExecute(result); // do something with result }
LOADERS:-
Loaders can automatically stop when the activity is destroyed, and can also restart
themselves after the activity is recreated.
SERVICE:-
Service is a component that is useful for performing long (or potentially long) operations
without any UI.
Service runs in the main thread of its hosting process; the service does not create its own
thread and does not run in a separate process unless you specify otherwise.
doSomeLongProccesingWork();
stopSelf();
return START_NOT_STICKY; }
return null;