Mobile Programming Basics
Mobile Programming Basics
i) Portable
A mobile device has to be portable, meaning that we can carry it without any special
considerations. We can take it to the gym, to the university, to work; we can carry it with us
everywhere, all the time.
ii) Personal
We’ve all heard it: “Don’t touch my phone!” A mobile device is absolutely personal. My mobile
is mine; it’s not property of the family, nor is it managed by the company who manufactured
it. I choose the ringtone, the visual theme, the games and applications installed, and which
calls I should accept. My wife has her own mobile device, and so do my kids. This personal
feature will be very important in our projects. You can browse a desktop website from any
computer—your familiar home PC, your computer at work, or even a desktop at a hotel or
Internet café—and numerous people may have access to those machines. However, you will
almost always browse a mobile website from the same device, and you are likely to be the
only person who uses that device.
iii) Companion
Your mobile device can be with you anytime! Even in the bathroom, you probably have your
mobile phone with you. You may forget to take lots of things with you from your home in the
morning, but you won’t forget your wallet, your keys, and your mobile device. The
opportunity to be with the user all the time, everywhere, is really amazing.
1
v) Connected device
A mobile device should be able to connect to the Internet when you need it to. This can be a
little difficult sometimes, so we will differentiate between fully connected devices that can
connect any time in a couple of seconds and limited connected devices that usually can
connect to the network but sometimes cannot.
A classic iPod (non-Touch) doesn’t have a network connection, so it’s out of our list too, like
the notebooks.
i) Mobile Phones
Those devices which have call and SMS support can be categorized as mobile phones. We still
have mobile phones in some markets. They don’t have web browsers or connectivity, and
they don’t have any installation possibilities.
After some years, because of device recycling, such phones will probably not be on the market
anymore. The Nokia 1100 was the most widely distributed device in the world, with over 200
million sold since its launch in 2003. In terms of features, it offers nothing but an inbuilt
flashlight. The problem is that we can’t create web content for it. Some companies may
continue to make very low-end entry devices in the future, but hopefully Nokia and most
other vendors will stop creating this kind of device. Even newer, cheaper mobile devices now
have inbuilt browser support.
This is because the mobile ecosystem (vendors, carriers, integrators, and developers) wants
to offer services to users, and a browser is the entry point. For example, through its OVI
Services Nokia offers OVI Mail, an email service for non-Internet users in emerging markets.
Thanks to this service, many, many people who have never before had access to email can
gain that access, with a mobile device costing very low amount. This widespread solution
meets a real need for many people in emerging markets, like some countries in Africa and
Latin America.
2
In this category, devices typically offer a medium-sized screen, basic HTML-browser support,
sometimes 3G, a decent camera, a music player, games, and application support.
One of the key features of mid-end devices is the operating system (OS). They don’t have a
well-known OS; they have a proprietary one without any portability across vendors. Native
applications generally aren’t available publicly and some runtime, like Java ME, is the
preferred way to develop installed applications. The same vendors develop these devices as
the low-end devices.
v) Smartphones
This is the most difficult category to define. Why aren’t some mid-end and high-end devices
considered “smart” enough to be in this category? The definition of smart evolves every year.
Even the simplest mobile device on the market today would have been considered very smart
15 years ago.
A smartphone, as defined today, has a multitasking operating system, a full desktop browser,
Wireless LAN (WLAN, also known as Wi-Fi) and 3G connections, a music player, and several
of the following features:
• GPS (Global Positioning System) or A-GPS (Assisted Global Positioning System)
• Digital compass
• Video-capable camera
• TV out
• Bluetooth
• Touch support
• 3D video acceleration
• Accelerometer
3
or even a pair of glasses. The LG GD910 in Figure 1-1 is a watch with 3G support. It’s on the
market now, so it’s not sci-fi.
“OK,” you may be thinking, “but are we really going to create a website for a one-inch
screen?” Maybe not. But we can create small widgets to update information presented to the
users, and this falls under the category of mobile web work.
4
Following are the landmarks in mobile history:
• 1926: The first successful mobile telephony service was offered to first class
passengers on the Deutsche Reichsbahn on the route between Berlin and Hamburg.
• 1946: The first calls were made on a car radiotelephone in Chicago. Due to the small
number of radio frequencies available, the service quickly reached capacity.
• 1956: The first automated mobile phone system for private vehicles launched in
Sweden. The device to install in the car used vacuum tube technology with rotary dial
and weighed 40Kg.
• 1969: The Nordic Mobile Telephone (NMT) Group was established. It included
engineers representing Sweden, Denmark, Norway and Finland. Its purpose was to
develop a mobile phone system that, unlike the systems being introduced in the US,
focused on accessibility.
• 1973: Dr Martin Cooper general manager at Motorola communications system
division made the first public mobile phone call on a device that weighed 1.1Kg.
• 1982: Engineers and administrators from eleven European countries gathered in
Stockholm to consider whether a Europe wide digital cellular phone system was
technically and politically possible. The group adopted the Nordic model of
cooperation and laid the foundation of an international standard.
• 1985: Comedian Ernie Wise made the first “public” mobile phone call in the UK from
outside the Dicken’s Pub in St Catherine’s dock to Vodafone’s HQ. He made the call in
full Dickensian coachman’s garb.
• 1987: The Technical specifications for the GSM standard are approved. Based on
digital technology, it focused on interoperability across national boundaries and
consequent different frequency bands, call quality and low costs.
• 1992: The world’s first ever SMS message was sent in the UK. Neil Papworth, aged 22
at the time was a developer for a telecom contractor tasked with developing a
messaging service for Vodafone. The text message read “Merry Christmas” and was
sent to Richard Jarvis, a director at Vodafone, who was enjoying his office Christmas
party.
• 1996/97: UK phone ownership stood at 16% of households. A decade later the figure
was 80%. The explosion in growth was in part driven the launch of the first pay as you
go, non-contract phone service, Vodafone Prepaid, in 1996.
• 1998: The first downloadable content sold to mobile phones was the ringtone,
launched by Finland's Radiolinja, laying the groundwork for an industry that would
eventually see the Crazy Frog ringtone rack up total earnings of half a billion dollars
and beat stadium-filling sob-rockers Coldplay to the number one spot in the UK charts.
• 1999: Emoji’s were invented by Shigetaka Kurita in Japan. Unlike their all-text
predecessor’s emoticons, emoji’s are pictures.
• 2000: The all-conquering Nokia 3310 crash landed on shop shelves. Naturally it was
unscathed and went on to sell 126 million units. Over in Japan, the first commercially
available camera phones The Sharp J-SH04, launched in November 2000 in Japan. The
only snag? you could only use it in Japan. Europe wouldn’t get its first camera phone
until the arrival of the Nokia 6750 in 2002.
• 2003: The 3G standard started to be adopted worldwide, kicking off the age of mobile
internet and paving the way for the rise of smartphones. Nepal was one of the first
countries in southern Asia to launch 3G services. One of Nepal’s first companies to
offer the service, Ncell, also covered Mount Everest with 3G.
5
• 2007: The iPhone debuted. Solely available on O2 at launch in the UK and priced at a
then eye-watering $499.
• 2008: The first Android phone turned up, in the form of the T-Mobile G1. Now dubbed
the O.G of Android phones, it was a long way from the high-end Android smartphones
we use today. Not least because it retained a physical keyboard and a BlackBerry-style
trackball for navigation. This year also saw the advent of both Apple’s App Store and
Android Market, later renamed Google Play Store.
• 2009: O2 publicly announced that it had successfully demonstrated a 4G connection
using six LTE masts in Slough, UK. The technology, which was supplied by Huawei,
achieved a peak downlink rate of 150Mbps.
• 2010: Samsung launched its first Galaxy S smartphone. Usurping former Android
giants, HTC, the Samsung Galaxy S range is still the most popular Android brand.
• 2017: The Nokia 3310 had a revival, sporting a fresh version equipped with basic web
browsing, a colourful screen and even a camera. Despite this, it still retained our
favourite features from the original 3310, including the iconic design, super-long
battery life and even an updated version of Snake.
Apple
We are going to start with Apple, not because its devices are the best or because it has the
greatest market share, but because Apple has caused a revolution in the market. It changed
the way mobile devices are seen by users, and it is the reason why many developers (web or
not) have turned their attention to the mobile world.
Apple, a well-known desktop computer company, entered the mobile world with a
revolutionary device: the iPhone. Luckily for us, all of Apple’s devices are quite similar. They
6
have a multi touch screen, a 3.5ʺ screen size, WLAN connections, and Safari on iOS (formerly
Mobile Safari) as the browser.
Apple’s devices have a great feature: an operating system called iOS (formerly iPhone OS) that
is based on Mac OS X (a Unix-based desktop OS). Up to this writing, even the first version of
the iPhone can be upgraded to the latest operating system version. By default, the iPhone
and iPod Touch are charged using USB; when you charge your device, iTunes (the Apple
software for managing your device’s content and music) will detect automatically if an OS
update is available for your device, and you can install the update in minutes without any
technical skill needed. That is why today, for a mobile web developer, it’s more important to
know what OS version an Apple device has installed than which device it is. For those of us
whose aim is to create great web experiences for the iPhone, it doesn’t matter if the device
is an iPhone (the basic phone), an iPhone 3GS (S for speed, a device with more power and
speed), an iPhone 4 or an iPod Touch (like the iPhone without the phone). Even within each
device type, we have many generations.
Today, we can develop applications for iOS devices on only two platforms: using mobile web
techniques, and using the framework built using Objective-C or Swift.
Nokia
Nokia was the most popular brand and had the largest market share in mobile devices and
smartphones worldwide. Nokia has devices in all the mobile categories, from very low-end
devices to very high-end smartphones.
Nokia has the best support for developers, compared to all the other companies. Hundreds
of documents and a huge amount of sample code, ideas, and best practices for many
technologies, including technologies used for mobile web development are available on its
website for developers, Forum Nokia.
The bad news for developers is that hundreds of different Nokia devices are available today.
The good news is that they are very well organized by platform into different series, making
it easier for us to develop, test, and port our web applications to most of them.
BlackBerry
Research in Motion (RIM) is the Canadian manufacturer of the BlackBerry devices, mobile
devices focused on being “always connected” with push technologies that are primarily used
by corporate users who need to remain connected to intranets and corporate networks. RIM
calls all its devices “smartphones.”
RIM has few devices aimed at the mass market, so most of them have QWERTY keyboards
and aren’t designed for gaming. Many of them have proprietary input devices, like a scroll
wheel or a touchpad; some touch-enabled devices have also been launched in the last few
years. All BlackBerrys have the RIM OS, a proprietary operating system compatible with Java
ME with extensions, and, of course, a mobile browser. We can categorize the devices by
operating system version.
BlackBerry has become very popular in the corporate market because of its integration with
Exchange and other corporate servers. A BlackBerry user can browse the Internet via the
corporate Internet connection though a proxy, and many other manufacturers, such as Nokia,
LG, HTC, and Sony Ericsson, support the BlackBerry email client.
7
Samsung
Samsung has many devices on the market, most of which are divided into three different
series: native devices, Symbian devices, and Windows devices. At the end of 2009, Samsung
surprised the market with a new platform for the devices launching from 2010: Bada.
Samsung’s native devices are low- and mid-end mobile devices with a proprietary OS including
a browser and Java ME support, and typically a camera and a music player. Prior to 2010, the
smartphones and high-end devices were divided into two categories by operating system
Symbian and Windows Mobile each having its own set of features.
The latest devices on the market have touch support, with a UI layer installed over the
operating system. For newer devices, there is one feature that is available on all the three
platforms: Samsung Widgets. These are small applications created using mobile web
technologies that can operate on all the operating systems Samsung uses.
Starting in 2010, Samsung had delivered mobile devices with Bada, Android, and Windows
Phone.
Sony Ericsson
Ericsson built many mobile phones in the 1990s, and in 2001 it merged with Sony and created
the Sony Ericsson company. Today, Sony Ericsson produces a range of low and mid-end
devices and a couple of smartphones. Sony Ericsson, like Samsung, has decided to offer
devices with different operating systems. It offers low- and mid-end devices using a
proprietary Sony Ericsson operating system, as well as Windows Mobile devices, Android
devices, and Symbian devices.
Before 2009, the Symbian devices used UIQ as the UI layer for the operating system. Since
2009, there are Symbian Foundation devices using the same UI layer as Nokia’s and Samsung’s
devices. So, in terms of developing web applications for them, they are very similar. The
proprietary OS devices support Java ME and Flash Lite development (and also both at the
same time, thanks to a project called Capuchin), and they are divided in series according to
the Java ME APIs they support.
So, today we have Sony Ericsson devices from Java Platform 1 (JP-1) to Java Platform 8 (JP-8),
with each category differing in terms of the API support and the screen resolution. All the
devices have a camera, a music player and, of course, a web browser built in. The Symbian
Foundation–based devices are touch-enabled.
Motorola
For many years, Motorola was a leading manufacturer of low- and mid-end devices.
Motorola’s devices were the first mobile devices on the market, and the company pioneered
the clamshell design with the classic Motorola StarTac. Motorola’s mobile devices have
traditionally used either a proprietary operating system (like the well-known Motorola v3),
Symbian UIQ, Windows Mobile, or a Linux-based operating system the company created for
its devices. On the proprietary OS–based devices, Java ME and the browser were the only
supported development platforms. The Linux-based OS supports Java ME, web, and native
development.
8
The Windows-based Motorola devices, like the Motorola Q, which has a QWERTY keyboard,
are intended for the corporate market. The company also has some touch devices on the
market, all with a built-in camera and music player, and some mobile devices for the two-way
radio market, like the Nextel network. These devices have a proprietary OS and the model
names usually start with an “i.”
There are no series divisions in Motorola, unlike in the Nokia and Sony Ericsson lines, so we
will need to use other information (such as the browser used in each device) to test and make
decisions about the devices.
LG Mobile
LG Mobile has many low to high-end devices on the market today. Some are based on a
proprietary OS with Java ME, Flash, and web support. Some them support web widgets based
on WebKit. Most of the new one’s are based on Android.
LG participated in the creation of the Symbian Foundation and has two Symbian devices based
on the S60 platform, but later on it decided to support Android, which we can see many
Android-based LG devices currently.
HTC
HTC has become very popular in the mobile market since it created the first and second
Android devices in the world and the first Google phone, the Nexus One. But HTC doesn’t only
create Android devices; it also produces a lot of Windows Mobile ones. Many HTC devices
have touch support, and a key feature is that HTC tries to emulate the same user experience
on all its devices. We can think of HTC devices as either Android devices or Windows devices;
that’s the only distinction that’s needed.
9
This simplicity is reflected in the HTC website for developers: it only contains kernel files for
Android devices and links to the Android and Windows Mobile generic websites.
Android
Android is an open source, Linux-based operating system created and maintained by a group
of software and hardware companies and operators called the Open Handset Alliance. Google
mainly maintains it, so it is sometimes known as the “Google Mobile Operating System.” As
with any open source software, any manufacturer could theoretically remove all the Google-
specific stuff from the operating system before installing it on their devices. However, as of
this writing no vendor has done this, which is why every Android device is very “Google
friendly.”
Android is a software stack including a Linux-core, multitasking operating system based on
the concept of a virtual machine that executes bytecode, similar to .NET or JVM (Java Virtual
Machine). Google chose Java as the main language to compile (not compatible with Java ME)
with Web 2.0 users in mind. Android includes a full HTML browser based on WebKit and, in
fact, is very similar to the iPhone Safari browser, and all Android devices to date ship with
Google Maps, Google Calendar, and an email client and provide connections to many free
Google web services. It’s not an obligation, but as of today every Android device is touch-
based, and many of them have a QWERTY physical keyboard, GPS, a digital compass, and an
accelerometer.
(Source: Wikipedia)
10
Windows Mobile
One of the older mobile operating systems on the market is Windows Mobile (formerly
Windows CE for Pocket PC and Smartphones). For many years, its market included the well-
known Pocket PCs as Personal Digital Assistants (PDAs) without phone features. The “mobile
revolution” pushed Microsoft to create a smartphone version of its mobile operating system,
now called Windows Mobile, which is available in two flavours: The Professional (formerly
Pocket PC) and Smartphone editions.
Windows Mobile has its own unique features, like Android, and as developers we can consider
it as a platform without regard to who the device manufacturer is. Windows Mobile devices
are produced by HP, Toshiba, Motorola, Sony Ericsson, Samsung and Palm.
Palm
USRobotics bought Palm Computing Inc. in 1995. At the time, it was the pioneer launching
PDA devices. USRobotics later merged with 3Com, and as 3Com was dedicated to network
cards and accessories, Palm Inc. was created as a subsidiary. Palm Inc. was very successful,
and other manufacturers (including IBM) created other devices licensing its Palm OS. In 1998,
a couple of Palm’s directors left to create another company, HandSpring, which releases the
Treo devices to the market. Half PDA and half mobile phone, they can be considered the first
smartphones on the market.
A few years later, Palm decided to divide the company into a hardware manufacturer,
palmOne, and an operating system developer, PalmSource. This idea didn’t work out:
customers didn’t accept the palmOne trademark, so the company again acquired the Palm
trademark and the operating system became the Garnet OS. In the meantime, Palm acquired
HandSpring, so now we have Palm Treo devices.
In 2005, ACCESS (who also had other mobile technologies) acquired PalmSource and the
operating system. Suddenly, the new-old Palm company made a difficult decision: it started
to manufacture Treo devices with Windows Mobile, killing all hopes for the future of the
Garnet OS (formerly Palm OS).
The Treo series was the only type of Palm device that survived in the mobile world, and
BlackBerrys, the Nokia E Series, and other devices soon pushed Palm to the bottom of the
market. In response, Palm created another operating system for mobile devices, aimed at
being a web-oriented platform for iPhone-killer devices. webOS came to the market in 2009
with the first device, the Palm Pre. Other devices, such as the Palm Pixi, followed.
The company didn’t go so-well in the market, so in 2010, Palm was acquired by HP, who
promised evolution of webOS, so we should expect HP netbooks, tablets and more mobile
phones with this operating system in the following years.
Palm’s new webOS devices are touch and multitouch devices with a very smooth user
interface, excellent web support, and all the functions of a modern mobile device. The
operating system and all the device applications are web-based. That’s because any “native”
application developed for webOS is created using web technologies.
11
Symbian Foundation
Today there are many Symbian Foundation–based devices on the market (from Nokia, Sony
Ericsson, and Samsung), all with similar operating system features. The Symbian Foundation’s
OS allows us to develop applications using the native C++ framework, Java ME, Adobe Flash,
web applications, widgets using web technologies, Python, and Qt, a free C-based framework
owned by Nokia.
The open source OS is versioned as Symbian^1, Symbian^2, Symbian^3, etc. As with Android
and Windows Mobile devices, if we are talking about a Symbian device we know that it will
be very similar to all other Symbian devices, no matter which manufacturer created it.
There are several languages used for mobile programming. Languages like Java, Kotlin, C#,
Python etc. are popular for android platform and Objective-C, Swift etc. are popular languages
for iOS platform. Programmers can select any of the language of their choice for writing
mobile programs.
12
There are four major development approaches when building mobile applications:
• Native Mobile Applications
• Cross-Platform Native Mobile Applications
• Hybrid Mobile Applications
• Progressive Web Applications
Native Applications
Native mobile applications are written in the programming language and frameworks
provided by the platform owner and running directly on the operating system of the device
such as iOS and Android.
Cross-Platform Applications
Cross-platform native mobile applications can be written in variety of different programming
languages and frameworks, but they are compiled into a native application running directly
on the operating system of the device.
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.
13
• 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 catlog 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.
• Regardless of what front-end platform or development methodology is being used,
delivering high-quality mobile applications that delight and retain users requires
reliable back-end services.
• 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.
Exercise
14
Unit -2
Introduction to Android Programming [4 Hrs]
Android Platform
Android is a mobile operating system currently developed by Google, based on the Linux
kernel and designed primarily for touchscreen mobile devices such as smartphones and
tablets. And as we said before, Android offers a unified approach to application development
for mobile devices.
Android is an open-source operating system named Android. Google has made the code for
all the low-level "stuff" as well as the needed middleware to power and use an electronic
device, and gave Android freely to anyone who wants to write code and build the operating
system from it. There is even a full application framework included, so third-party apps can
be built and installed, then made available for the user to run as they like.
The "proper" name for this is the Android Open Source Project, and this is what people mean
when they say things like Android is open and free. Android, in this iteration, is free for anyone
to use as they like.
History of Android
The history and versions of android are interesting to know. The code names of android
ranges from A to P currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo,
Gingerbread, Honeycomb, Ice Cream Sandwich, Jelly Bean, KitKat, Lollipop, Marhmallow,
Nougat, Oreo and Pie. Let's understand the android history in a sequence.
• Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United
States in October, 2003.
• In 17th August 2005, Google acquired android Incorporation. Since then, it is in the
subsidiary of Google Incorporation.
• The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris
White and Nick Sears.
• Originally intended for camera but shifted to smart phones later because of low
market for camera only.
• Android is the nick name of Andy Rubin given by co-workers because of his love to
robots.
• In 2007, Google announces the development of android OS.
• In 2008, HTC launched the first android mobile.
Environment Setup
In order to write an Android application, we are going to need a development environment.
Google has made a very useful tool for all Android Developers, the Android Studio. Android
Studio is the official IDE for Android development, and with a single download includes
everything you need to begin developing Android apps.
Included in the download kit, are the Software Development Kit (SDK), with all the Android
libraries we may need, and the infrastructure to download the many Android emulator
instances, so that we can initially run our application, without needing a real device. So, we
are going to download and install Android Studio.
1
Step 1 - First we have to have installed the Java Development Kit (JDK) from Oracle. If you do
not, please you should download the latest JDK from the https://www.oracle.com/. After
downloading JDK, please install it in your system.
Step 2 – After installing JDK, now it’s the time for you to setup environment variables. For this
procedure, right click This PC (My Computer) -> Properties -> Advanced System Settings ->
Environment Variables -> New. Now setup new environment variable as follows:
Here, variable value must be the path where JDK is installed. Now click OK.
Step 3 – Now download the latest android studio and install in your system. After installation
following window appears in your computer screen.
Congratulations! Android Studio has been successfully installed in your computer system.
2
Creating an Android Project
The first step is to create an Android project. An Android project contains the files that make
up an application. To create a new project, open Android Studio and choose File -> New ->
New Project to open the new application wizard.
Notice that the package name you entered uses a “reverse DNS” convention in which the
domain name of your organization is reversed and suffixed with further identifiers. This
convention keeps package names unique and distinguishes applications from each other on
a device and on Google Play.
Click Next.
3
Here we can select different devices and minimum SDK for or project. This setup configures
your application to work with different versions of Android. We are using default settings for
our project.
Android updates its tools several times a year, so your wizard may look slightly different from
what we are showing you. This is usually not a problem; the choices to make should stay
pretty much the same.
Click Next.
4
Here we can see different templates for our Application. We can use these templates as per
the requirement. Since we are developing our first application, we start by adding no activity
in our project.
Click Finish.
5
Now select Resource type layout and Click OK.
6
Now we need to write name of file. In this example I am giving name as first. For designing a
page, we can use different types of layout like Linear, Relative, Constraint etc. In this case, I
am using Linear Layout. We will discuss about different types of layout in coming chapters.
Click OK.
Note: Name of all the files under resource folder must be in lower case.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="50dp"
/>
</LinearLayout>
7
Widgets are the building blocks you use to compose a user interface. A widget can show text
or graphics, interact with the user, or arrange other widgets on the screen. Buttons, text input
controls, and check boxes are all types of widgets.
8
second.xml
9
</LinearLayout>
</LinearLayout>
The root element of this layout’s view hierarchy is a LinearLayout. As the root element, the
LinearLayout must specify the Android resource XML namespace at
http://schemas.android.com/ apk/res/android.
LinearLayout inherits from a subclass of View named ViewGroup. A ViewGroup is a widget
that contains and arranges other widgets. You use a LinearLayout when you want widgets
arranged in a single column or row. Other ViewGroup subclasses are FrameLayout,
TableLayout, and RelativeLayout.
When a widget is contained by a ViewGroup, that widget is said to be a child of the
ViewGroup. The root LinearLayout has two children: a TextView and another LinearLayout.
The child LinearLayout has two Button children of its own.
Widgets Attributes
Let’s discuss some of the attributes that you have used to configure your widgets:
10
• wrap_content view will be as big as its contents require
(You may see fill_parent in some places. This deprecated value is equivalent to
match_parent.)
android:orientation
The android:orientation attribute on the two LinearLayout widgets determines whether their
children will appear vertically or horizontally. The root LinearLayout is vertical; its child
LinearLayout is horizontal.
android:text
The TextView and Button widgets have android:text attributes. This attribute tells the widget
what text to display. Notice that the values of these attributes are not literal strings. They are
references to string resources.
A string resource is a string that lives in a separate XML file called a strings file. You can give a
widget a hard-coded string, like android:text="True", but it is usually not a good idea. Placing
strings into a separate file and then referencing them is better.
<resources>
<string name="app_name">My Application</string>
<string name="text_question">Android Studio is better than
Eclipse</string>
<string name="text_true">True</string>
<string name="text_false">False</string>
</resources>
11
Creating a New Class
Since for creating a page that can be displayed in an application we need layout resource file
for designing the page and a class file written using object oriented programming language
like Java, Kotlin, C# etc. that extends Activity class. In simple words, we can say that for
creating pages we need class file that extends Activity class. In a class file we link layout file
which we have designed and add events and other functionality to different widgets and
views that we have created in layout resource file. For creating class file we are using Java
programming language in our example.
12
Add following lines of code in newly created java file:
Second.java
package com.example.raazu.myapplication;
import android.app.Activity;
import android.os.Bundle;
This method inflates a layout and puts it on screen. When a layout is inflated, each widget in
the layout file is instantiated as defined by its attributes. You specify which layout to inflate
by passing in the layout’s resource ID.
13
Setting Up the Project
Now this is a final step to configure before running your application. Add your newly created
activity in AndroidMainfest.xml file. Following lines of code will add and configure your
activity to android manifest.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.raazu.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Second">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
14
The manifest file describes essential information about your app to the Android build tools,
the Android operating system, and Google Play.
Among many other things, the manifest file is required to declare the following:
• The app's package name, which usually matches your code's namespace. The Android
build tools use this to determine the location of code entities when building your
project. When packaging the app, the build tools replace this value with the
application ID from the Gradle build files, which is used as the unique app identifier
on the system and on Google Play.
• The components of the app, which include all activities, services, broadcast receivers,
and content providers. Each component must define basic properties such as the
name of its Kotlin or Java class. It can also declare capabilities such as which device
configurations it can handle, and intent filters that describe how the component can
be started.
• The permissions that the app needs in order to access protected parts of the system
or other apps. It also declares any permissions that other apps must have if they want
to access content from this app.
• The hardware and software features the app requires, which affects which devices can
install the app from Google Play.
Intent filters
App activities, services, and broadcast receivers are activated by intents. An intent is a
message defined by an Intent object that describes an action to perform, including the data
to be acted upon, the category of component that should perform the action, and other
instructions.
When an app issues an intent to the system, the system locates an app component that can
handle the intent based on intent filter declarations in each app's manifest file. The system
launches an instance of the matching component and passes the Intent object to that
component. If more than one app can handle the intent, then the user can select which app
to use.
An app component can have any number of intent filters (defined with the <intent-filter>
element), each one describing a different capability of that component.
If activity is defined with <intent-filter> element in manifest file than that activity will be
launched as the first activity of application.
15
1. To open the AVD Manager, do one of the following:
• Select Tools > Android > AVD Manager.
• Click AVD Manager in the toolbar.
2. Click Create Virtual Device, at the bottom of the AVD Manager dialog.
The Select Hardware page appears.
16
3. Select a hardware profile, and then click Next.
If you don't see the hardware profile you want, you can create or import a hardware
profile.
The System Image page appears.
4. Select the system image for a particular API level, and then click Next.
• The Recommended tab lists recommended system images. The other tabs
include a more complete list. The right pane describes the selected system
image. x86 images run the fastest in the emulator.
• If you see Download next to the system image, you need to click it to
download the system image. You must be connected to the internet to
download it.
17
Figure 2-16. Verifying Configuration
2. Following screen will appear. Choose your virtual device from the list and press OK
button.
18
Figure 2-18. Selecting Deployment Device
3. Now your app will start running and after some time following output will be displayed
in your emulator.
19
Figure 2-19. Displaying output in emulator
Exercise
20
Unit -3
Designing the User Interface [5 Hrs]
The View objects are usually called "widgets" and can be one of many subclasses, such as
Button or TextView. The ViewGroup objects are usually called "layouts" can be one of many
types that provide a different layout structure, such as LinearLayout or ConstraintLayout .
Following are the different types of layout used for designing the User Interface.
LinearLayout
LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally. You can specify the layout direction with the android:orientation attribute.
1
Figure 3-2. Representation of LinearLayout
All children of a LinearLayout are stacked one after the other, so a vertical list will only have
one child per row, no matter how wide they are, and a horizontal list will only be one row
high (the height of the tallest child, plus padding). A LinearLayout respects margins
between children and the gravity (right, center, or left alignment) of each child.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is label 1"
android:textSize="20sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is label 2"
android:textSize="20sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is label 3"
android:textSize="20sp"/>
</LinearLayout>
2
Figure 3-3. Output produced for LinearLayout
android:baselineAligned When set to false, prevents the layout from aligning its
children's baselines.
android:baselineAlignedChildIndex When a linear layout is part of another layout that is
baseline aligned, it can specify which of its children to
baseline align to (that is, which child TextView).
android:divider Drawable to use as a vertical divider between buttons.
android:gravity Specifies how an object should position its content, on
both the X and Y axes, within its own bounds.
android:measureWithLargestChild When set to true, all children with a weight will be
considered having the minimum size of the largest child.
android:orientation Should the layout be a column or a row? Use "horizontal"
for a row, "vertical" for a column.
android:weightSum Defines the maximum weight sum.
Layout Weight
LinearLayout also supports assigning a weight to individual children with the
android:layout_weight attribute. This attribute assigns an "importance" value to a view in
terms of how much space it should occupy on the screen. A larger weight value allows it to
expand to fill any remaining space in the parent view. Child views can specify a weight
3
value, and then any remaining space in the view group is assigned to children in the
proportion of their declared weight. Default weight is zero.
Equal distribution
To create a linear layout in which each child uses the same amount of space on the screen,
set the android:layout_height of each view to "0dp" (for a vertical layout) or the
android:layout_width of each view to "0dp" (for a horizontal layout). Then set the
android:layout_weight of each view to "1".
Unequal distribution
You can also create linear layouts where the child elements use different amounts of space
on the screen:
• If there are three text fields and two of them declare a weight of 1, while the other
is given no weight, the third text field without weight doesn't grow. Instead, this
third text field occupies only the area required by its content. The other two text
fields, on the other hand, expand equally to fill the space remaining after all three
fields are measured.
• If there are three text fields and two of them declare a weight of 1, while the third
field is then given a weight of 2 (instead of 0), then it's now declared more
important than both the others, so it gets half the total remaining space, while the
first two share the rest equally.
Following code snippet demonstrate layout_weight attribute. Here we are creating two
TextViews. First TextView have weight equal to 2 and Second TextView have weight equal
to 1. Total weight of LinearLayout is 3.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 1"
android:layout_weight="2"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label2"
android:layout_weight="1"
android:textSize="20sp" />
</LinearLayout>
4
Figure 3-4. Output demonstrating layout_weight attribute
RelativeLayout
RelativeLayout is a view group that displays child views in relative positions. The position
of each view can be specified as relative to sibling elements (such as to the left-of or below
another view) or in positions relative to the parent RelativeLayout area (such as aligned to
the bottom, left or center).
5
A RelativeLayout is a very powerful utility for designing a user interface because it can
eliminate nested view groups and keep your layout hierarchy flat, which improves
performance. If you find yourself using several nested LinearLayout groups, you may be
able to replace them with a single RelativeLayout.
6
android:layout_centerVertical If true, centers this child vertically within its
parent.
android:layout_toEndOf Positions the start edge of this view to the end
of the given anchor view ID.
android:layout_toLeftOf Positions the right edge of this view to the left
of the given anchor view ID.
android:layout_toRightOf Positions the left edge of this view to the right
of the given anchor view ID.
android:layout_toStartOf Positions the end edge of this view to the start
of the given anchor view ID.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 1"
android:textSize="20sp"
android:id="@+id/label1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 2"
android:textSize="20sp"
android:id="@+id/label2"
android:layout_toRightOf="@+id/label1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 3"
android:textSize="20sp"
android:id="@+id/label3"
android:layout_below="@+id/label1" />
</RelativeLayout>
7
Figure 3-6. Output demonstrating RelativeLayout
TableLayout
TableLayout is a layout that arranges its children into rows and columns. It consists of a
number of TableRow objects, each defining a row (actually, you can have other children,
which will be explained below). TableLayout containers do not display border lines for their
rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object.
The table has as many columns as the row with the most cells. A table can leave cells empty.
Cells can span columns, as they can in HTML.
The children of a TableLayout cannot specify the layout_width attribute. Width is always
MATCH_PARENT. However, the layout_height attribute can be defined by a child; default
value is ViewGroup.LayoutParams.WRAP_CONTENT. If the child is a TableRow, then the
height is always ViewGroup.LayoutParams.WRAP_CONTENT.
Cells must be added to a row in increasing column order, both in code and XML. Column
numbers are zero-based. If you don't specify a column number for a child cell, it will auto
increment to the next available column. If you skip a column number, it will be considered
an empty cell in that row.
Although the typical child of a TableLayout is a TableRow, you can actually use any View
subclass as a direct child of TableLayout. The View will be displayed as a single row that
spans all the table columns.
8
Figure 3-7. Representation of TableLayout
9
Following code snippet will demonstrate TableLayout.
<TableRow
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 1"
android:textSize="20sp"
android:layout_column="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 2"
android:textSize="20sp"
android:layout_column="2"/>
</TableRow>
<TableRow
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 3"
android:textSize="20sp"
android:layout_column="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 4"
android:textSize="20sp"
android:layout_column="2"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 5"
android:textSize="20sp"
android:layout_column="3"/>
</TableRow>
</TableLayout>
10
Figure 3-8. Output demonstrating TableLayout
AbsoluteLayout
An Absolute Layout lets you specify exact locations (x/y coordinates) of its children.
Absolute layouts are less flexible and harder to maintain than other types of layouts
without absolute positioning.
11
Following are the important attributes specific to AbsoluteLayout.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 1"
android:textSize="20sp"
android:layout_x="100dp"
android:layout_y="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 2"
android:textSize="20sp"
android:layout_x="150dp"
android:layout_y="100dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 3"
android:textSize="20sp"
android:layout_x="180dp"
android:layout_y="150dp" />
</AbsoluteLayout>
Since AbsoluteLayout was deprecated in API level 3. So, we can use RelativeLayout,
LinearLayout or any other layout for better performance.
12
Figure 3-10. Output Demonstrating AbsoluteLayout
ConstraintLayout
Constraint layout is an advanced version of a Relative layout. It is used to reduce the child
view hierarchies and improve the performance. It is used to define a layout by assigning
constraints for every child view/widget relative to other views present.
The aim of the ConstraintLayout is to help reduce the number of nested views, which will
improve the performance of our layout files. The layout class also makes it easier for us to
define layouts than when using a RelativeLayout as we can now anchor any side of a view
with any side of another, rather than having to place a whole view to any side of another.
For example, the attributes of a relative layout allow us to position a view using:
• layout_toRightOf
• layout_toLeftOf
• layout_toTopOf
• layout_toBottomOf
13
However, the ConstraintLayout features several more attributes:
• layout_constraintTop_toTopOf — Align the top of the desired view to the top of
another.
• layout_constraintTop_toBottomOf — Align the top of the desired view to
the bottom of another.
• layout_constraintBottom_toTopOf — Align the bottom of the desired view to
the top of another.
• layout_constraintBottom_toBottomOf — Align the bottom of the desired view to
the bottom of another.
• layout_constraintLeft_toTopOf — Align the left of the desired view to the top of
another.
• layout_constraintLeft_toBottomOf — Align the left of the desired view to
the bottom of another.
• layout_constraintLeft_toLeftOf — Align the left of the desired view to the left of
another.
• layout_constraintLeft_toRightOf — Align the left of the desired view to
the right of another.
• layout_constraintRight_toTopOf — Align the right of the desired view to
the top of another.
• layout_constraintRight_toBottomOf — Align the right of the desired view to
the bottom of another.
• layout_constraintRight_toLeftOf — Align the right of the desired view to
the left of another.
• layout_constraintRight_toRightOf — Align the right of the desired view to
the right of another.
• If desired, attributes supporting start and end are also available in place
of left and right alignment.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 1"
android:id="@+id/label1"
android:textSize="20sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 2"
android:textSize="20sp"
android:id="@+id/label2"
app:layout_constraintLeft_toRightOf="@+id/label1"
app:layout_constraintTop_toBottomOf="@+id/label1" />
14
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label 3"
android:textSize="20sp"
android:id="@+id/label3"
app:layout_constraintBottom_toTopOf="@+id/label2"
app:layout_constraintLeft_toRightOf="@+id/label2" />
</android.support.constraint.ConstraintLayout>
15
Android Widgets
Widgets are the building blocks you use to compose a user interface. A widget can show
text or graphics, interact with the user, or arrange other widgets on the screen. Buttons,
text input controls, and check boxes are all types of widgets. Some of the common widgets
used in android are discussed below:
TextView
It is a user interface element that displays text to the user. Following are the attributes
associated with TextView.
16
android:editable If set, specifies that this TextView has an input method.
android:editorExtras Reference to an <input-extras> XML resource containing
additional data to supply to an input method, which is
private to the implementation of the input method.
android:elegantTextHeight Elegant text height, especially for less compacted
complex script text.
android:ellipsize If set, causes words that are longer than the view is wide
to be ellipsized instead of broken in the middle.
android:ems Makes the TextView be exactly this many ems wide.
android:enabled Specifies whether the widget is enabled.
android:fallbackLineSpacing Whether to respect the ascent and descent of the
fallback fonts that are used in displaying the text.
android:firstBaselineToTopHeight Distance from the top of the TextView to the first text
baseline.
android:fontFamily Font family (named by string or as a font resource
reference) for the text.
android:fontFeatureSettings Font feature settings.
android:fontVariationSettings Font variation settings.
android:freezesText If set, the text view will include its current complete text
inside of its frozen icicle in addition to meta-data such as
the current cursor position.
android:gravity Specifies how to align the text by the view's x- and/or y-
axis when the text is smaller than the view.
android:height Makes the TextView be exactly this tall.
android:hint Hint text to display when the text is empty.
android:hyphenationFrequency Frequency of automatic hyphenation.
android:imeActionId Supply a value for EditorInfo.actionId used when an
input method is connected to the text view.
android:imeActionLabel Supply a value for EditorInfo.actionLabel used when an
input method is connected to the text view.
android:imeOptions Additional features you can enable in an IME associated
with an editor to improve the integration with your
application.
android:includeFontPadding Leave enough room for ascenders and descenders
instead of using the font ascent and descent strictly.
android:inputMethod If set, specifies that this TextView should use the
specified input method (specified by fully-qualified class
name).
android:inputType The type of data being placed in a text field, used to help
an input method decide how to let the user enter text.
android:justificationMode Mode for justification.
android:lastBaselineToBottomHeight Distance from the bottom of the TextView to the last
text baseline.
android:letterSpacing Text letter-spacing.
android:lineHeight Explicit height between lines of text.
17
android:lineSpacingExtra Extra spacing between lines of text.
android:lineSpacingMultiplier Extra spacing between lines of text, as a multiplier.
android:lines Makes the TextView be exactly this many lines tall.
android:linksClickable If set to false, keeps the movement method from being
set to the link movement method even if autoLink
causes links to be found.
android:marqueeRepeatLimit The number of times to repeat the marquee animation.
android:maxEms Makes the TextView be at most this many ems wide.
android:maxHeight Makes the TextView be at most this many pixels tall.
android:maxLength Set an input filter to constrain the text length to the
specified number.
android:maxLines Makes the TextView be at most this many lines tall.
android:maxWidth Makes the TextView be at most this many pixels wide.
android:minEms Makes the TextView be at least this many ems wide.
android:minHeight Makes the TextView be at least this many pixels tall.
android:minLines Makes the TextView be at least this many lines tall.
android:minWidth Makes the TextView be at least this many pixels wide.
android:numeric If set, specifies that this TextView has a numeric input
method.
android:password Whether the characters of the field are displayed as
password dots instead of themselves.
android:phoneNumber If set, specifies that this TextView has a phone number
input method.
android:privateImeOptions An addition content type description to supply to the
input method attached to the text view, which is private
to the implementation of the input method.
android:scrollHorizontally Whether the text is allowed to be wider than the view
(and therefore can be scrolled horizontally).
android:selectAllOnFocus If the text is selectable, select it all when the view takes
focus.
android:shadowColor Place a blurred shadow of text underneath the text,
drawn with the specified color.
android:shadowDx Horizontal offset of the text shadow.
android:shadowDy Vertical offset of the text shadow.
android:shadowRadius Blur radius of the text shadow.
android:singleLine Constrains the text to a single horizontally scrolling line
instead of letting it wrap onto multiple lines, and
advances focus instead of inserting a newline when you
press the enter key.
android:text Text to display.
android:textAllCaps Present the text in ALL CAPS.
android:textAppearance Base text color, typeface, size, and style.
android:textColor Text color.
android:textColorHighlight Color of the text selection highlight.
android:textColorHint Color of the hint text.
18
android:textColorLink Text color for links.
android:textCursorDrawable Reference to a drawable that will be drawn under the
insertion cursor.
android:textFontWeight Weight for the font used in the TextView.
android:textIsSelectable Indicates that the content of a non-editable text can be
selected.
android:textScaleX Sets the horizontal scaling factor for the text.
android:textSelectHandle Reference to a drawable that will be used to display a
text selection anchor for positioning the cursor within
text.
android:textSelectHandleLeft Reference to a drawable that will be used to display a
text selection anchor on the left side of a selection
region.
android:textSelectHandleRight Reference to a drawable that will be used to display a
text selection anchor on the right side of a selection
region.
android:textSize Size of the text.
android:textStyle Style (normal, bold, italic, bold|italic) for the text.
android:typeface Typeface (normal, sans, serif, monospace) for the text.
android:width Makes the TextView be exactly this wide.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is a textview"
android:id="@+id/label1"
android:textSize="25sp"
android:textStyle="bold"
android:textAllCaps="true"
android:textAlignment="center"
android:layout_centerVertical="true"
android:textColor="#FF4081" />
</RelativeLayout>
19
Figure 3-12. Output Demonstrating TextView
EditText
A user interface element for entering and modifying text. When you define an edit text
widget, you must specify the inputType attribute. For example, for plain text input set
inputType to "text".
Choosing the input type configures the keyboard type that is shown, acceptable characters,
and appearance of the edit text. For example, if you want to accept a secret number, like
a unique pin or serial number, you can set inputType to "numericPassword". An inputType
of "numericPassword" results in an edit text that accepts numbers only, shows a numeric
keyboard when focused, and masks the text that is entered for privacy.
We can use same set of attributes that we have used for TextView.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
20
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp"
android:hint="Enter Text Here"
android:inputType="text"
android:textColor="#3F51B5"
android:textColorHint="#3F51B5"
android:textSize="20sp"
android:textAlignment="center"
android:tooltipText="Enter Text" />
</RelativeLayout>
21
Button
It is a user interface element the user can tap or click to perform an action. Following are
the attributes associated with Button.
Attributes Inherited from TextView – Almost all attributes of TextView can be used for
Button.
Other Attributes:
22
android:elevation base z depth of the view.
android:fadeScrollbars Defines whether to fade out scrollbars when they
are not in use.
android:fadingEdgeLength Defines the length of the fading edges.
android:filterTouchesWhenObscured Specifies whether to filter touches when the view's
window is obscured by another visible window.
android:fitsSystemWindows Boolean internal attribute to adjust view layout
based on system windows such as the status bar.
android:focusable Controls whether a view can take focus.
android:focusableInTouchMode Boolean that controls whether a view can take focus
while in touch mode.
android:focusedByDefault Whether this view is a default-focus view.
android:forceHasOverlappingRendering Whether this view has elements that may overlap
when drawn.
android:foreground Defines the drawable to draw over the content.
android:foregroundGravity Defines the gravity to apply to the foreground
drawable.
android:foregroundTint Tint to apply to the foreground.
android:foregroundTintMode Blending mode used to apply the foreground tint.
android:hapticFeedbackEnabled Boolean that controls whether a view should have
haptic feedback enabled for events such as long
presses.
android:id Supply an identifier name for this view, to later
retrieve it
with View.findViewById() or Activity.findViewById().
android:importantForAccessibility Describes whether or not this view is important for
accessibility.
android:importantForAutofill Hints the Android System whether the view node
associated with this View should be included in a
view structure used for autofill purposes.
android:importantForContentCapture Hints the Android System whether the view node
associated with this View should be use for content
capture purposes.
android:isScrollContainer Set this if the view will serve as a scrolling container,
meaning that it can be resized to shrink its overall
window so that there will be space for an input
method.
android:keepScreenOn Controls whether the view's window should keep
the screen on while visible.
android:keyboardNavigationCluster Whether this view is a root of a keyboard navigation
cluster.
android:layerType Specifies the type of layer backing this view.
android:layoutDirection Defines the direction of layout drawing.
android:longClickable Defines whether this view reacts to long click
events.
23
android:minHeight Defines the minimum height of the view.
android:minWidth Defines the minimum width of the view.
android:nextClusterForward Defines the next keyboard navigation cluster.
android:nextFocusDown Defines the next view to give focus to when the next
focus is View.FOCUS_DOWN If the reference refers
to a view that does not exist or is part of a hierarchy
that is invisible, a RuntimeException will result
when the reference is accessed.
android:nextFocusForward Defines the next view to give focus to when the next
focus is View.FOCUS_FORWARD If the reference
refers to a view that does not exist or is part of a
hierarchy that is invisible, a RuntimeException will
result when the reference is accessed.
android:nextFocusLeft Defines the next view to give focus to when the next
focus is View.FOCUS_LEFT.
android:nextFocusRight Defines the next view to give focus to when the next
focus is View.FOCUS_RIGHT If the reference refers
to a view that does not exist or is part of a hierarchy
that is invisible, a RuntimeException will result
when the reference is accessed.
android:nextFocusUp Defines the next view to give focus to when the next
focus is View.FOCUS_UP If the reference refers to a
view that does not exist or is part of a hierarchy that
is invisible, a RuntimeException will result when the
reference is accessed.
android:onClick Name of the method in this View's context to invoke
when the view is clicked.
android:outlineAmbientShadowColor Sets the color of the ambient shadow that is drawn
when the view has a positive Z or elevation value.
android:outlineSpotShadowColor Sets the color of the spot shadow that is drawn
when the view has a positive Z or elevation value.
android:padding Sets the padding, in pixels, of all four edges.
android:paddingBottom Sets the padding, in pixels, of the bottom edge;
see R.attr.padding.
android:paddingEnd Sets the padding, in pixels, of the end edge;
see R.attr.padding.
android:paddingHorizontal Sets the padding, in pixels, of the left and right
edges; see R.attr.padding.
android:paddingLeft Sets the padding, in pixels, of the left edge;
see R.attr.padding.
android:paddingRight Sets the padding, in pixels, of the right edge;
see R.attr.padding.
android:paddingStart Sets the padding, in pixels, of the start edge;
see R.attr.padding.
24
android:paddingTop Sets the padding, in pixels, of the top edge;
see R.attr.padding.
android:paddingVertical Sets the padding, in pixels, of the top and bottom
edges; see R.attr.padding.
android:requiresFadingEdge Defines which edges should be faded on scrolling.
android:rotation rotation of the view, in degrees.
android:rotationX rotation of the view around the x axis, in degrees.
android:rotationY rotation of the view around the y axis, in degrees.
android:saveEnabled If false, no state will be saved for this view when it is
being frozen.
android:scaleX scale of the view in the x direction.
android:scaleY scale of the view in the y direction.
android:screenReaderFocusable Whether this view should be treated as a focusable
unit by screen reader accessibility tools.
android:scrollIndicators Defines which scroll indicators should be displayed
when the view can be scrolled.
android:scrollX The initial horizontal scroll offset, in pixels.
android:scrollY The initial vertical scroll offset, in pixels.
android:scrollbarAlwaysDrawHorizontalTrack Defines whether the horizontal scrollbar track
should always be drawn.
android:scrollbarAlwaysDrawVerticalTrack Defines whether the vertical scrollbar track should
always be drawn.
android:scrollbarDefaultDelayBeforeFade Defines the delay in milliseconds that a scrollbar
waits before fade out.
android:scrollbarFadeDuration Defines the delay in milliseconds that a scrollbar
takes to fade out.
android:scrollbarSize Sets the width of vertical scrollbars and height of
horizontal scrollbars.
android:scrollbarStyle Controls the scrollbar style and position.
android:scrollbarThumbHorizontal Defines the horizontal scrollbar thumb drawable.
android:scrollbarThumbVertical Defines the vertical scrollbar thumb drawable.
android:scrollbarTrackHorizontal Defines the horizontal scrollbar track drawable.
android:scrollbarTrackVertical Defines the vertical scrollbar track drawable.
android:scrollbars Defines which scrollbars should be displayed on
scrolling or not.
android:soundEffectsEnabled Boolean that controls whether a view should have
sound effects enabled for events such as clicking
and touching.
android:stateListAnimator Sets the state-based animator for the View.
android:tag Supply a tag for this view containing a String, to be
retrieved later with View.getTag() or searched for
with View.findViewWithTag().
android:textAlignment Defines the alignment of the text.
android:textDirection Defines the direction of the text.
android:theme Specifies a theme override for a view.
25
android:tooltipText Defines text displayed in a small popup window on
hover or long press.
android:transformPivotX x location of the pivot point around which the view
will rotate and scale.
android:transformPivotY y location of the pivot point around which the view
will rotate and scale.
android:transitionName Names a View such that it can be identified for
Transitions.
android:translationX translation in x of the view.
android:translationY translation in y of the view.
android:translationZ translation in z of the view.
android:visibility Controls the initial visibility of the view.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit Button"
android:textAllCaps="false"
android:textSize="20sp"
android:layout_centerInParent="true"
android:textColor="#3F51B5" />
</RelativeLayout>
26
Figure 3-14. Output Demonstrating Button
CheckBox
A checkbox is a specific type of two-states button that can be either checked or unchecked.
Following are the attributes associated with CheckBox.
Attributes Inherited from TextView – Almost all attributes of TextView can be used for
Button.
Other Attributes:
27
android:alpha alpha property of the view, as a value between 0
(completely transparent) and 1 (completely
opaque).
android:autofillHints Describes the content of a view so that a autofill
service can fill in the appropriate data.
android:autofilledHighlight Drawable to be drawn over the view to mark it as
autofilled
May be a reference to another resource, in the form
"@[+][package:]type/name" or a theme attribute in
the form "?[package:]type/name".
android:background A drawable to use as the background.
android:backgroundTint Tint to apply to the background.
android:backgroundTintMode Blending mode used to apply the background tint.
android:clickable Defines whether this view reacts to click events.
android:contentDescription Defines text that briefly describes content of the
view.
android:contextClickable Defines whether this view reacts to context click
events.
android:defaultFocusHighlightEnabled Whether this View should use a default focus
highlight when it gets focused but doesn't
have R.attr.state_focused defined in its background.
android:drawingCacheQuality Defines the quality of translucent drawing caches.
android:duplicateParentState When this attribute is set to true, the view gets its
drawable state (focused, pressed, etc.) from its
direct parent rather than from itself.
android:elevation base z depth of the view.
android:fadeScrollbars Defines whether to fade out scrollbars when they
are not in use.
android:fadingEdgeLength Defines the length of the fading edges.
android:filterTouchesWhenObscured Specifies whether to filter touches when the view's
window is obscured by another visible window.
android:fitsSystemWindows Boolean internal attribute to adjust view layout
based on system windows such as the status bar.
android:focusable Controls whether a view can take focus.
android:focusableInTouchMode Boolean that controls whether a view can take focus
while in touch mode.
android:focusedByDefault Whether this view is a default-focus view.
android:forceHasOverlappingRendering Whether this view has elements that may overlap
when drawn.
android:foreground Defines the drawable to draw over the content.
android:foregroundGravity Defines the gravity to apply to the foreground
drawable.
android:foregroundTint Tint to apply to the foreground.
android:foregroundTintMode Blending mode used to apply the foreground tint.
28
android:hapticFeedbackEnabled Boolean that controls whether a view should have
haptic feedback enabled for events such as long
presses.
android:id Supply an identifier name for this view, to later
retrieve it
with View.findViewById() or Activity.findViewById().
android:importantForAccessibility Describes whether or not this view is important for
accessibility.
android:importantForAutofill Hints the Android System whether the view node
associated with this View should be included in a
view structure used for autofill purposes.
android:importantForContentCapture Hints the Android System whether the view node
associated with this View should be use for content
capture purposes.
android:isScrollContainer Set this if the view will serve as a scrolling container,
meaning that it can be resized to shrink its overall
window so that there will be space for an input
method.
android:keepScreenOn Controls whether the view's window should keep
the screen on while visible.
android:keyboardNavigationCluster Whether this view is a root of a keyboard navigation
cluster.
android:layerType Specifies the type of layer backing this view.
android:layoutDirection Defines the direction of layout drawing.
android:longClickable Defines whether this view reacts to long click
events.
android:minHeight Defines the minimum height of the view.
android:minWidth Defines the minimum width of the view.
android:nextClusterForward Defines the next keyboard navigation cluster.
android:nextFocusDown Defines the next view to give focus to when the next
focus is View.FOCUS_DOWN If the reference refers
to a view that does not exist or is part of a hierarchy
that is invisible, a RuntimeException will result when
the reference is accessed.
android:nextFocusForward Defines the next view to give focus to when the next
focus is View.FOCUS_FORWARD If the reference
refers to a view that does not exist or is part of a
hierarchy that is invisible, a RuntimeException will
result when the reference is accessed.
android:nextFocusLeft Defines the next view to give focus to when the next
focus is View.FOCUS_LEFT.
android:nextFocusRight Defines the next view to give focus to when the next
focus is View.FOCUS_RIGHT If the reference refers to
a view that does not exist or is part of a hierarchy
29
that is invisible, a RuntimeException will result when
the reference is accessed.
android:nextFocusUp Defines the next view to give focus to when the next
focus is View.FOCUS_UP If the reference refers to a
view that does not exist or is part of a hierarchy that
is invisible, a RuntimeException will result when the
reference is accessed.
android:onClick Name of the method in this View's context to invoke
when the view is clicked.
android:outlineAmbientShadowColor Sets the color of the ambient shadow that is drawn
when the view has a positive Z or elevation value.
android:outlineSpotShadowColor Sets the color of the spot shadow that is drawn
when the view has a positive Z or elevation value.
android:padding Sets the padding, in pixels, of all four edges.
android:paddingBottom Sets the padding, in pixels, of the bottom edge;
see R.attr.padding.
android:paddingEnd Sets the padding, in pixels, of the end edge;
see R.attr.padding.
android:paddingHorizontal Sets the padding, in pixels, of the left and right
edges; see R.attr.padding.
android:paddingLeft Sets the padding, in pixels, of the left edge;
see R.attr.padding.
android:paddingRight Sets the padding, in pixels, of the right edge;
see R.attr.padding.
android:paddingStart Sets the padding, in pixels, of the start edge;
see R.attr.padding.
android:paddingTop Sets the padding, in pixels, of the top edge;
see R.attr.padding.
android:paddingVertical Sets the padding, in pixels, of the top and bottom
edges; see R.attr.padding.
android:requiresFadingEdge Defines which edges should be faded on scrolling.
android:rotation rotation of the view, in degrees.
android:rotationX rotation of the view around the x axis, in degrees.
android:rotationY rotation of the view around the y axis, in degrees.
android:saveEnabled If false, no state will be saved for this view when it is
being frozen.
android:scaleX scale of the view in the x direction.
android:scaleY scale of the view in the y direction.
android:screenReaderFocusable Whether this view should be treated as a focusable
unit by screen reader accessibility tools.
android:scrollIndicators Defines which scroll indicators should be displayed
when the view can be scrolled.
android:scrollX The initial horizontal scroll offset, in pixels.
30
android:scrollY The initial vertical scroll offset, in pixels.
android:scrollbarAlwaysDrawHorizontalT Defines whether the horizontal scrollbar track
rack should always be drawn.
android:scrollbarAlwaysDrawVerticalTra Defines whether the vertical scrollbar track should
ck always be drawn.
android:scrollbarDefaultDelayBeforeFad Defines the delay in milliseconds that a scrollbar
e waits before fade out.
android:scrollbarFadeDuration Defines the delay in milliseconds that a scrollbar
takes to fade out.
android:scrollbarSize Sets the width of vertical scrollbars and height of
horizontal scrollbars.
android:scrollbarStyle Controls the scrollbar style and position.
android:scrollbarThumbHorizontal Defines the horizontal scrollbar thumb drawable.
android:scrollbarThumbVertical Defines the vertical scrollbar thumb drawable.
android:scrollbarTrackHorizontal Defines the horizontal scrollbar track drawable.
android:scrollbarTrackVertical Defines the vertical scrollbar track drawable.
android:scrollbars Defines which scrollbars should be displayed on
scrolling or not.
android:soundEffectsEnabled Boolean that controls whether a view should have
sound effects enabled for events such as clicking and
touching.
android:stateListAnimator Sets the state-based animator for the View.
android:tag Supply a tag for this view containing a String, to be
retrieved later with View.getTag() or searched for
with View.findViewWithTag().
android:textAlignment Defines the alignment of the text.
android:textDirection Defines the direction of the text.
android:theme Specifies a theme override for a view.
android:tooltipText Defines text displayed in a small popup window on
hover or long press.
android:transformPivotX x location of the pivot point around which the view
will rotate and scale.
android:transformPivotY y location of the pivot point around which the view
will rotate and scale.
android:transitionName Names a View such that it can be identified for
Transitions.
android:translationX translation in x of the view.
android:translationY translation in y of the view.
android:translationZ translation in z of the view.
android:visibility Controls the initial visibility of the view.
31
Following code snippet will demonstrate CheckBox:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"
android:textSize="20sp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"
android:checked="true"
android:textSize="20sp" />
</LinearLayout>
32
RadioButton
A radio button is a two-states button that can be either checked or unchecked. When the
radio button is unchecked, the user can press or click it to check it. However, contrary to a
CheckBox, a radio button cannot be unchecked by the user once checked.
Radio buttons are normally used together in a RadioGroup. When several radio buttons
live inside a radio group, checking one radio button unchecks all the others.
Attributes Inherited from TextView – Almost all attributes of TextView can be used for
Button.
Other Attributes:
33
have R.attr.state_focused defined in its
background.
34
android:keepScreenOn Controls whether the view's window should keep
the screen on while visible.
android:keyboardNavigationCluster Whether this view is a root of a keyboard navigation
cluster.
android:layerType Specifies the type of layer backing this view.
android:layoutDirection Defines the direction of layout drawing.
android:longClickable Defines whether this view reacts to long click
events.
android:minHeight Defines the minimum height of the view.
android:minWidth Defines the minimum width of the view.
android:nextClusterForward Defines the next keyboard navigation cluster.
android:nextFocusDown Defines the next view to give focus to when the
next focus is View.FOCUS_DOWN If the reference
refers to a view that does not exist or is part of a
hierarchy that is invisible, a RuntimeException will
result when the reference is accessed.
android:nextFocusForward Defines the next view to give focus to when the
next focus is View.FOCUS_FORWARD If the
reference refers to a view that does not exist or is
part of a hierarchy that is invisible,
a RuntimeException will result when the reference
is accessed.
android:nextFocusLeft Defines the next view to give focus to when the
next focus is View.FOCUS_LEFT.
android:nextFocusRight Defines the next view to give focus to when the
next focus is View.FOCUS_RIGHT If the reference
refers to a view that does not exist or is part of a
hierarchy that is invisible, a RuntimeException will
result when the reference is accessed.
android:nextFocusUp Defines the next view to give focus to when the
next focus is View.FOCUS_UP If the reference refers
to a view that does not exist or is part of a hierarchy
that is invisible, a RuntimeException will result
when the reference is accessed.
android:onClick Name of the method in this View's context to
invoke when the view is clicked.
android:outlineAmbientShadowColor Sets the color of the ambient shadow that is drawn
when the view has a positive Z or elevation value.
android:outlineSpotShadowColor Sets the color of the spot shadow that is drawn
when the view has a positive Z or elevation value.
android:padding Sets the padding, in pixels, of all four edges.
android:paddingBottom Sets the padding, in pixels, of the bottom edge;
see R.attr.padding.
android:paddingEnd Sets the padding, in pixels, of the end edge;
see R.attr.padding.
35
android:paddingHorizontal Sets the padding, in pixels, of the left and right
edges; see R.attr.padding.
android:paddingLeft Sets the padding, in pixels, of the left edge;
see R.attr.padding.
android:paddingRight Sets the padding, in pixels, of the right edge;
see R.attr.padding.
android:paddingStart Sets the padding, in pixels, of the start edge;
see R.attr.padding.
android:paddingTop Sets the padding, in pixels, of the top edge;
see R.attr.padding.
android:paddingVertical Sets the padding, in pixels, of the top and bottom
edges; see R.attr.padding.
android:requiresFadingEdge Defines which edges should be faded on scrolling.
android:rotation rotation of the view, in degrees.
android:rotationX rotation of the view around the x axis, in degrees.
android:rotationY rotation of the view around the y axis, in degrees.
android:saveEnabled If false, no state will be saved for this view when it
is being frozen.
android:scaleX scale of the view in the x direction.
android:scaleY scale of the view in the y direction.
android:screenReaderFocusable Whether this view should be treated as a focusable
unit by screen reader accessibility tools.
android:scrollIndicators Defines which scroll indicators should be displayed
when the view can be scrolled.
android:scrollX The initial horizontal scroll offset, in pixels.
android:scrollY The initial vertical scroll offset, in pixels.
android:scrollbarAlwaysDrawHorizonta Defines whether the horizontal scrollbar track
lTrack should always be drawn.
android:scrollbarAlwaysDrawVerticalTr Defines whether the vertical scrollbar track should
ack always be drawn.
android:scrollbarDefaultDelayBeforeFa Defines the delay in milliseconds that a scrollbar
de waits before fade out.
android:scrollbarFadeDuration Defines the delay in milliseconds that a scrollbar
takes to fade out.
android:scrollbarSize Sets the width of vertical scrollbars and height of
horizontal scrollbars.
android:scrollbarStyle Controls the scrollbar style and position.
android:scrollbarThumbHorizontal Defines the horizontal scrollbar thumb drawable.
android:scrollbarThumbVertical Defines the vertical scrollbar thumb drawable.
android:scrollbarTrackHorizontal Defines the horizontal scrollbar track drawable.
android:scrollbarTrackVertical Defines the vertical scrollbar track drawable.
android:scrollbars Defines which scrollbars should be displayed on
scrolling or not.
36
android:soundEffectsEnabled Boolean that controls whether a view should have
sound effects enabled for events such as clicking
and touching.
android:stateListAnimator Sets the state-based animator for the View.
android:tag Supply a tag for this view containing a String, to be
retrieved later with View.getTag() or searched for
with View.findViewWithTag().
android:textAlignment Defines the alignment of the text.
android:textDirection Defines the direction of the text.
android:theme Specifies a theme override for a view.
android:tooltipText Defines text displayed in a small popup window on
hover or long press.
android:transformPivotX x location of the pivot point around which the view
will rotate and scale.
android:transformPivotY y location of the pivot point around which the view
will rotate and scale.
android:transitionName Names a View such that it can be identified for
Transitions.
android:translationX translation in x of the view.
android:translationY translation in y of the view.
android:translationZ translation in z of the view.
android:visibility Controls the initial visibility of the view.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender:"
android:textSize="20sp"/>
<RadioGroup
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:textSize="20sp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
37
android:text="Female"
android:textSize="20sp"/>
</RadioGroup>
</LinearLayout>
Spinner
It is a view that displays one child at a time and lets the user pick among them. The items
in the Spinner come from the String array or Adapter associated with this view.
Following are some important attributes associated with spinner.
38
android:gravity Gravity setting for positioning the currently selected
item.
android:popupBackground Background drawable to use for the dropdown in
spinnerMode="dropdown".
android:prompt The prompt to display when the spinner's dialog is
shown.
android:spinnerMode Display mode for spinner options.
android:entries Used for loading string array.
Following example will demonstrate Spinner. In this example for collection of items to be
loaded in Spinner we are creating string array in strings.xml file. We can also load items
collection programmatically.
strings.xml
<string-array name="spinner_items">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
<item>Item 4</item>
</string-array>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Items:"
android:textSize="20sp"/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/spinner_items"
android:spinnerMode="dropdown"/>
</LinearLayout>
39
Figure 3-17. Output Demonstrating Spinner
Spinner spinner=findViewById(R.id.spinner);
String items[]={"Item 1","Item 2","Item 3","Item 4"};
Event Handling
Events are a useful way to collect data about a user's interaction with interactive
components of Applications. Like button presses or screen touch etc. The Android
framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture
these events in your program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management −
• Event Listeners − An event listener is an interface in the View class that contains a
single callback method. These methods will be called by the Android framework
when the View to which the listener has been registered is triggered by user
interaction with the item in the UI.
40
• Event Listeners Registration − Event Registration is the process by which an Event
Handler gets registered with an Event Listener so that the handler is called when
the Event Listener fires the event.
• Event Handlers − When an event happens and we have registered an event listener
for the event, the event listener calls the Event Handlers, which is the method that
actually handles the event.
OnClickListener()
onClick() This is called when the user either clicks or touches or focuses upon
any widget like button, text, image etc. You will use onClick() event
handler to handle such event.
OnLongClickListener()
onLongClick()
This is called when the user either clicks or touches or focuses upon
any widget like button, text, image etc. for one or more seconds.
You will use onLongClick() event handler to handle such event.
OnFocusChangeListener()
onFocusChange()
This is called when the widget looses its focus ie. user goes away
from the view item. You will use onFocusChange() event handler to
handle such event.
OnFocusChangeListener()
onKey()
This is called when the user is focused on the item and presses or
releases a hardware key on the device. You will use onKey() event
handler to handle such event.
OnTouchListener()
onTouch()
This is called when the user presses the key, releases the key, or any
movement gesture on the screen. You will use onTouch() event
handler to handle such event.
OnMenuItemClickListener()
onMenuItemClick()
This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.
onCreateContextMenuItemListener()
onCreateContextMenu()
This is called when the context menu is being built(as the result of
a sustained "long click)
41
Following example will demonstrate onClick() event. For this we are creating a Button and
while clicking Button a Toast message will be displayed on screen.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_centerInParent="true"
android:id="@+id/button1"
/>
Button btn=findViewById(R.id.button1);
//adding click event and listener
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//displaying message
Toast.makeText(getApplicationContext(),"Button Clicked !",
Toast.LENGTH_SHORT).show();
}
});
42
Working with String and String Array
A string resource provides text strings for your application with optional text styling and
formatting. String is a XML resource that provides a single string while String array is a
XML resource that provides an array of strings.
Using String
43
Working with Colors
A color resource provides set of colors that you can use all over your application.
With an image saved at res/drawable/myimage.png, this layout XML applies the image to
a View:
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/myimage" />
android:icon="@drawable/myicon"
44
Exercise
1. What do you mean by layout? List and explain different types of layout used in
android with their major attributes.
2. Differentiate LinearLayout and RelativeLayout with example.
3. Differentiate RelativeLayout and ConstraintLayout with example.
4. Compare AbsoluteLayout with other types of layout.
5. Explain any five widgets with their attributes in detail.
6. What do you mean by event? Explain event handling in detail.
7. How can you use string and string array in android? Explain.
8. How can you use color in android? Explain.
9. Differentiate string and string array with example.
10. Explain the procedure for adding and displaying image in imageview. Also write
code snippet to add icon to your project.
11. Design a signup form using Relative, Linear, Absolute and Constraint Layout.
12. Design a simple UI for Book Entry in library.
13. Design a simple UI for patient registration in hospital.
14. Display the following data using TableLayout.
Student Id Name Address Gender
001 Ram Sharma Birtamode Male
002 Gita Sharma Kathmandu Female
15. Design a simple calculator UI using TableLayout.
45
Unit -4
Android Activity [4 Hrs]
The Activity Life Cycle
Every instance of Activity has a lifecycle. During this lifecycle, an activity transitions
between three possible states: running, paused, and stopped. For each transition, there is
an Activity method that notifies the activity of the change in its state.
As a user navigates through, out of, and back to your app, the Activity instances in your app
transition through different states in their lifecycle. The Activity class provides a number of
callbacks that allow the activity to know that a state has changed: that the system is
creating, stopping, or resuming an activity, or destroying the process in which the activity
resides.
Within the lifecycle callback methods, you can declare how your activity behaves when the
user leaves and re-enters the activity. For example, if you're building a streaming video
player, you might pause the video and terminate the network connection when the user
switches to another app. When the user returns, you can reconnect to the network and
allow the user to resume the video from the same spot. In other words, each callback
allows you to perform specific work that's appropriate to a given change of state. Doing
the right work at the right time and handling transitions properly make your app more
robust and performant. For example, good implementation of the lifecycle callbacks can
help ensure that your app avoids:
• Crashing if the user receives a phone call or switches to another app while using
your app.
• Consuming valuable system resources when the user is not actively using it.
• Losing the user's progress if they leave your app and return to it at a later time.
• Crashing or losing the user's progress when the screen rotates between landscape
and portrait orientation.
To navigate transitions between stages of the activity lifecycle, the Activity class provides
a core set of six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(), and
onDestroy(). The system invokes each of these callbacks as an activity enters a new state.
1
Figure 4-1. A simplified illustration of the activity lifecycle
onCreate()
You must implement this callback, which fires when the system first creates the activity.
On activity creation, the activity enters the Created state. In the onCreate() method, you
perform basic application startup logic that should happen only once for the entire life of
the activity.
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
//your stuffs
}
2
onStart()
When the activity enters the Started state, the system invokes this callback. The onStart()
call makes the activity visible to the user, as the app prepares for the activity to enter the
foreground and become interactive. For example, this method is where the app initializes
the code that maintains the UI.
The onStart() method completes very quickly and, as with the Created state, the activity
does not stay resident in the Started state. Once this callback finishes, the activity enters
the Resumed state, and the system invokes the onResume() method.
@Override
protected void onStart()
{
super.onStart();
//your stuffs
}
onResume()
When the activity enters the Resumed state, it comes to the foreground, and then the
system invokes the onResume() callback. This is the state in which the app interacts with
the user. The app stays in this state until something happens to take focus away from the
app. Such an event might be, for instance, receiving a phone call, the user’s navigating to
another activity, or the device screen’s turning off.
@Override
protected void onResume() {
super.onResume();
//your stuffs
}
onPause()
The system calls this method as the first indication that the user is leaving your activity
(though it does not always mean the activity is being destroyed); it indicates that the
activity is no longer in the foreground (though it may still be visible if the user is in multi-
window mode). Use the onPause() method to pause or adjust operations that should not
continue (or should continue in moderation) while the Activity is in the Paused state, and
that you expect to resume shortly. There are several reasons why an activity may enter this
state. For example:
• Some event interrupts app execution, as described in the onResume() section. This
is the most common case.
• In Android 7.0 (API level 24) or higher, multiple apps run in multi-window mode.
Because only one of the apps (windows) has focus at any time, the system pauses
all of the other apps.
• A new, semi-transparent activity (such as a dialog) opens. As long as the activity is
still partially visible but not in focus, it remains paused.
3
@Override
protected void onPause() {
super.onPause();
//your stuffs
}
onStop()
When your activity is no longer visible to the user, it has entered the Stopped state, and
the system invokes the onStop() callback. This may occur, for example, when a newly
launched activity covers the entire screen. The system may also call onStop() when the
activity has finished running, and is about to be terminated.
You should also use onStop() to perform relatively CPU-intensive shutdown operations. For
example, if you can't find a more opportune time to save information to a database, you
might do so during onStop().
@Override
protected void onStop() {
super.onStop();
//your stuffs
}
onDestroy()
onDestroy() is called before the activity is destroyed. The system invokes this callback
either because:
• the activity is finishing (due to the user completely dismissing the activity or due to
finish() being called on the activity), or
• the system is temporarily destroying the activity due to a configuration change
(such as device rotation or multi-window mode)
If the activity is finishing, onDestroy() is the final lifecycle callback the activity receives. If
onDestroy() is called as the result of a configuration change, the system immediately
creates a new activity instance and then calls onCreate() on that new instance in the new
configuration. The onDestroy() callback should release all resources that have not yet been
released by earlier callbacks such as onStop().
@Override
protected void onDestroy() {
super.onDestroy();
//your stuffs
}
4
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//displaying message in Log
Log.d("Lifecycle Test", "Activity Created");
}
@Override
protected void onStart()
{
super.onStart();
Log.d("Lifecycle Test", "Activity Started");
}
@Override
protected void onResume() {
super.onResume();
Log.d("Lifecycle Test", "Activity Resumed");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("Lifecycle Test", "Activity Restarted");
}
@Override
protected void onPause() {
super.onPause();
Log.d("Lifecycle Test", "Activity Paused");
}
@Override
protected void onStop() {
super.onStop();
Log.d("Lifecycle Test", "Activity Stopped");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("Lifecycle Test", "Activity Destroyed");
}
5
Now go to Logcat present inside Android Monitor: Scroll up and you will notice three
methods which were called: Activity Created, Activity started and Activity resumed.
Now press the back button on the Emulator and exit the App. Go to Logcat again and scroll
down to bottom. You will see 3 more methods were called: Activity paused, Activity
stopped and Activity is being destroyed.
FirstActivity.java
import android.app.Activity;
import android.os.Bundle;
6
SecondActivity.java
import android.app.Activity;
import android.os.Bundle;
first_activity.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is First Activity"
android:textSize="20sp"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:id="@+id/text1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:textSize="20sp"
android:layout_gravity="center"
android:id="@+id/button1"
/>
</LinearLayout>
second_activity.xml
7
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"
android:textSize="20sp"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:id="@+id/text2"
/>
</LinearLayout>
8
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".FirstActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".SecondActivity"/>
</application>
</manifest>
Intents are multi-purpose communication tools, and the Intent class provides different
constructors depending on what you are using the intent to do.
In this case, you are using an intent to tell the ActivityManager which activity to start, so
you will use this constructor:
public Intent(Context packageContext, Class<?> cls)
The Class object specifies the activity that the ActivityManager should start. The Context
object tells the ActivityManager which package the Class object can be found in.
9
Figure 4-3. The intent: telling ActivityManager what to do
Following code snippet opens SecondActivity using Intent when user clicks Button in
FirstActivity:
Button btn=findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(FirstActivity.this,SecondActivity.class);
startActivity(i);
}
});
Intent.putExtra(…) comes in many flavors, but it always has two arguments. The first
argument is always a String key, and the second argument is the value, whose type will
vary.
Let’s learn this with the help of an example. Suppose if we want to pass data like id, name
and address of student from FirstActivity to SecondActivity then we can use Intent extras
as follows:
10
FirstActivity.java
Button btn=findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(FirstActivity.this,
SecondActivity.class);
//passing data using putExtra
i.putExtra("id",001);
i.putExtra("name","Ram");
i.putExtra("address","KTM");
startActivity(i);
}
});
}
}
SecondActivity.java
//receiving data
Intent i=getIntent();
int id=i.getIntExtra("id",0);
//second argument is default value
String name=i.getStringExtra("name");
String address=i.getStringExtra("address");
txt.setText("Id="+id+"\n"+"Name="+name+"\n"+"Address="+
address);
}
}
11
Figure 4-4. Output displayed in SecondActivity
The first parameter is the same intent as before. The second parameter is the
request code. The request code is a user-defined integer that is sent to the child
activity and then received back by the parent. It is used when an activity starts more
than one type of child activity and needs to tell who is reporting back.
• Now pass data from SecondActivity to FirstActivity using following methods. There
are two methods you can call in the child activity to send data back to the parent:
public final void setResult(int resultCode)
public final void setResult(int resultCode, Intent data)
12
Following example will demonstrate this procedure. Here we are adding a Button in
SecondActivity. When user clicks this Button a message “Hello First Activity!” will be sent
to FirstActivity. This message will be displayed in TextView of FirstActivity.
FirstActivity.java
txt=findViewById(R.id.text1);
btn=findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(FirstActivity.this,
SecondActivity.class);
//starting activity with result code 2
startActivityForResult(i,2);
}
});
}
SecondActivity.java
btn=findViewById(R.id.button2);
13
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent();
i.putExtra("message","Hello First Activity!");
setResult(2,i);
finish();//finishing activity
}
});
}
}
first_activity.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is First Activity"
android:textSize="20sp"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:id="@+id/text1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second"
android:textSize="20sp"
android:layout_gravity="center"
android:id="@+id/button1"
/>
</LinearLayout>
second_activity.xml
14
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"
android:textSize="20sp"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_marginTop="100dp"
android:id="@+id/text2"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to First"
android:textSize="20sp"
android:layout_gravity="center"
android:id="@+id/button2"
/>
</LinearLayout>
15
Getting and Setting Data to/from Layout File
To demonstrate this topic, now we are going to create an activity containing some
important widgets like TextView, Button, EditText, RadioButton and Spinner. First we try
to get all data that we have inputted using these widgets. After getting all data we will
display all received data in a TextView.
first_activity.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Form"
android:textSize="20sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="@+id/txtForm" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/txtForm"
android:layout_margin="5dp"
android:hint="Enter Student Id"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/edtId"
android:layout_margin="5dp"
android:hint="Enter Student Name"
android:id="@+id/edtName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender:"
android:textSize="18sp"
android:id="@+id/txtGender"
android:layout_below="@+id/edtName"
android:layout_marginLeft="10dp"
android:layout_margin="5dp" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/edtName"
android:id="@+id/radGroup"
16
android:orientation="horizontal"
android:layout_toRightOf="@+id/txtGender">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:id="@+id/radMale" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="@+id/radFemale" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Program:"
android:textSize="18sp"
android:layout_below="@+id/radGroup"
android:layout_margin="5dp"
android:id="@+id/txtProgram" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/programs"
android:layout_below="@+id/radGroup"
android:layout_toRightOf="@+id/txtProgram"
android:layout_marginTop="5dp"
android:id="@+id/spProgram" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtProgram"
android:layout_marginTop="10dp"
android:text="Submit"
android:id="@+id/btnSubmit"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"
android:textSize="18sp"
android:id="@+id/txtResult"
android:layout_below="@+id/btnSubmit"
android:layout_margin="5dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
17
FirstActivity.java
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
radMale=findViewById(R.id.radMale);
radFemale=findViewById(R.id.radFemale);
spProgram=findViewById(R.id.spProgram);
btnSubmit=findViewById(R.id.btnSubmit);
txtResult=findViewById(R.id.txtResult);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//getting data from edit text
String id=edtId.getText().toString();
String name=edtName.getText().toString();
//getting data from radio button
String gender="";
if(radMale.isChecked())
gender="Male";
else
gender="Female";
//getting data from spinner
String program=spProgram.getSelectedItem().toString();
}
}
18
Figure 4-6. Output demonstrating getting and setting data to/from xml file
Now we are going to look another example where user input two numbers using EditText.
When user clicks a Button then our application performs addition of two numbers and
displays result in a TextView.
first_activity.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:hint="Enter First Number"
android:inputType="number"
android:id="@+id/edtFirst" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/edtFirst"
19
android:layout_margin="5dp"
android:hint="Enter Second Number"
android:inputType="number"
android:id="@+id/edtSecond" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtSecond"
android:layout_marginTop="10dp"
android:text="Calculate"
android:id="@+id/btnCalculate"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"
android:textSize="18sp"
android:id="@+id/txtResult"
android:layout_below="@+id/btnCalculate"
android:layout_margin="5dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
FirstActivity.java
edtFirst=findViewById(R.id.edtFirst);
edtSecond=findViewById(R.id.edtSecond);
btnCalculate=findViewById(R.id.btnCalculate);
txtResult=findViewById(R.id.txtResult);
btnCalculate.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
//getting data from edit text
int first,second,result;
first=Integer.parseInt(edtFirst.getText().toString());
second=Integer.parseInt(edtSecond.getText().toString());
result=first+second;
//displaying result in TextView
txtResult.setText("Result="+result);
}
});
}
}
20
Figure 4-7. Output demonstrating addition of two numbers
Exercise
1. What do you mean by android activity? Explain android activity life cycle in detail.
2. How can you declare multiple activities in manifest? Explain.
3. What do you mean by intent? Explain.
4. How can you pass data between multiple activities using intent? Explain.
5. Develop an android application which get result back from a child activity.
6. Develop an android application to calculate simple interest. Your application should
contain fields to input principal, rate, time and button for event handling. Calculate
and display result in a TextView.
7. Develop an android application to calculate area and perimeter of rectangle. Your
application should contain fields to input length and breadth and two buttons for
calculating area and perimeter. Calculate and display result in a TextView.
8. Design a signup form using any layout of your choice.
- Your design must include important widgets like TextView, EditText, Button,
RadioButton, CheckBox, Spinner etc.
- When user clicks a Button display inputted data in a TextView.
9. Develop a simple calculator application with two input fields for inputting numbers
and four Buttons for performing addition, subtraction, multiplication and division.
Display the result in a TextView.
10. Develop an android application to input your name, address, gender and other
personal information. Pass and display this information in another activity.
21
Unit -5
UI Fragments, Menus and Dialogs [6 Hrs]
Introduction to Fragments
Android Fragment is the part of activity, which is also known as sub-activity. There can be
more than one fragment in an activity. Fragments represent multiple screen inside one
activity.
A fragment must always be hosted in an activity and the fragment's lifecycle is directly
affected by the host activity's lifecycle. For example, when the activity is paused, so are all
fragments in it, and when the activity is destroyed, so are all fragments. However, while an
activity is running (it is in the resumed lifecycle state), you can manipulate each fragment
independently, such as add or remove them. When you perform such a fragment
transaction, you can also add it to a back stack that's managed by the activity—each back
stack entry in the activity is a record of the fragment transaction that occurred. The back
stack allows the user to reverse a fragment transaction (navigate backwards), by pressing
the Back button.
You should design each fragment as a modular and reusable activity component. That is,
because each fragment defines its own layout and its own behavior with its own lifecycle
callbacks, you can include one fragment in multiple activities, so you should design for
reuse and avoid directly manipulating one fragment from another fragment. This is
especially important because a modular fragment allows you to change your fragment
combinations for different screen sizes. When designing your application to support both
tablets and handsets, you can reuse your fragments in different layout configurations to
optimize the user experience based on the available screen space. For example, on a
handset, it might be necessary to separate fragments to provide a single-pane UI when
more than one cannot fit within the same activity.
1
For example, a news application can use one fragment to show a list of articles on the left
and another fragment to display an article on the right—both fragments appear in one
activity, side by side, and each fragment has its own set of lifecycle callback methods and
handle their own user input events. Thus, instead of using one activity to select an article
and another activity to read the article, the user can select an article and read it all within
the same activity, as illustrated in the tablet layout in figure 5-1.
Figure 5-1. An example of how two UI modules defined by fragments can be combined
into one activity for a tablet design, but separated for a handset design.
For example—to continue with the news application example—the application can embed
two fragments in Activity A, when running on a tablet-sized device. However, on a handset-
sized screen, there's not enough room for both fragments, so Activity A includes only the
fragment for the list of articles, and when the user selects an article, it starts Activity B,
which includes the second fragment to read the article. Thus, the application supports both
tablets and handsets by reusing fragments in different combinations, as illustrated in above
figure.
Lifecycle of Fragment
The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods
for fragment. It is shown below:
2
Figure 5-2. The lifecycle of a fragment (while its activity is running).
3
S.N. Method Description
1) onAttach(Activity) it is called only once when it is attached
with activity.
2) onCreate(Bundle) It is used to initialize the fragment.
3) onCreateView(LayoutInflater, creates and returns view hierarchy.
ViewGroup, Bundle)
4) onActivityCreated(Bundle) It is invoked after the completion of
onCreate() method.
5) onViewStateRestored(Bundle) It provides information to the fragment that
all the saved state of fragment view
hierarchy has been restored.
6) onStart() makes the fragment visible.
7) onResume() makes the fragment interactive.
8) onPause() is called when fragment is no longer
interactive.
9) onStop() is called when fragment is no longer visible.
10) onDestroyView() allows the fragment to clean up resources.
11) onDestroy() allows the fragment to do final clean-up of
fragment state.
12) onDetach() It is called immediately prior to the
fragment no longer being associated with
its activity.
Creating a UI Fragment
Fragment can be created in UI resource file as follows:
<fragment android:name="com.example.raazu.myapplication.Fragment1"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
One difference when creating a Fragment is that you must use the onCreateView() callback
to define the layout. In fact, this is the only callback you need in order to get a fragment
running. For example, here's a simple fragment that specifies its own layout:
4
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container,
false);
}
}
Example of Fragment
Following example creates two fragments named as Fragment1 and Fragment2. After
creating fragments, we will add these two fragments in activity named as FirstActivity and
display them.
Firstly, we start by creating two fragments,
fragment1.xml
fragment2.xml
5
Fragment1.java
Fragment2.java
first_activity.xml
<fragment android:name="com.example.raazu.myapplication.Fragment1"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment android:name="com.example.raazu.myapplication.Fragment2"
android:id="@+id/fragment2"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
6
FirstActivity.java
7
Wiring Widgets in Fragment
To demonstrate this topic, now I am going to create a fragment named as Fragment1 and
add this fragment to Activity named as FirstActivity. Additionally, to show wiring of widgets
inside fragment I will create UI for adding two numbers using two EditText, one Button and
one TextView for displaying result.
So, Let’s begin by creating fragment.
fragment1.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:id="@+id/edtFirst" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:id="@+id/edtSecond" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Caluclate"
android:id="@+id/btnCalculate"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result:"
android:textSize="20sp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:id="@+id/txtResult" />
</LinearLayout>
Fragment1.java
8
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment1, container,
false);
//wiring up widgets
edtFirst=view.findViewById(R.id.edtFirst);
edtSecond=view.findViewById(R.id.edtSecond);
btnCalculate=view.findViewById(R.id.btnCalculate);
txtResult=view.findViewById(R.id.txtResult);
btnCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int first,second, result;
first=Integer.parseInt(edtFirst.getText().toString());
second=Integer.parseInt(edtSecond.getText().toString());
result=first+second;
txtResult.setText("Result="+result);
}
});
return view;
}
}
first_activity.xml
<fragment android:name="com.example.raazu.myapplication.Fragment1"
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
FirstActivity.java
9
Above code will produce following output:
The FragmentManager handles two things: a list of fragments and a back stack of fragment
transactions. It is shown below:
10
Figure 5-5. The FragmentManager
Fragment transactions are used to add, remove, attach, detach, or replace fragments in
the fragment list. They are the heart of how you use fragments to compose and recompose
screens at runtime. The FragmentManager maintains a back stack of fragment transactions
that you can navigate.
The FragmentManager.beginTransaction() method creates and returns an instance of
FragmentTransaction. The FragmentTransaction class uses a fluent interface - methods
that configure FragmentTransaction return a FragmentTransaction instead of void, which
allows you to chain them together. So the highlighted code in Listing 7.12 says, “Create a
new fragment transaction, include one add operation in it, and then commit it.”
Following example will demonstrate the use of FragmentManager. Here, we are creating
two Fragments and one Activity. Activity contains two buttons for switching fragments i.e,
if first Button is clicked Fragment1 is displayed and if second Button is clicked Fragment2
is displayed on screen.
So, let’s begin by creating two fragments.
fragment1.xml
11
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am inside Fragment 1"
android:layout_gravity="center"
android:textSize="20sp"
android:layout_marginTop="20sp"
android:textStyle="bold" />
</LinearLayout>
fragment2.xml
Fragment1.java
Fragment2.java
12
Now it’s time to create Activity with two Buttons as follows.
first_activity.xml
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnFirst"
android:text="Fragment 1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnSecond"
android:text="Fragment 2" />
<fragment android:id="@+id/myfragment"
android:name="com.example.raazu.myapplication.Fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
FirstActivity.java
btnFirst=findViewById(R.id.btnFirst);
btnSecond=findViewById(R.id.btnSecond);
btnFirst.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment fragment=new Fragment1();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction =
manager.beginTransaction();
transaction.replace(R.id.myfragment, fragment);
transaction.commit();
}
});
btnSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
13
Fragment fragment=new Fragment2();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction =
manager.beginTransaction();
transaction.replace(R.id.myfragment, fragment);
transaction.commit();
}
});
}
}
14
6) Activity use a lot of memory. Fragment doesn’t use any memory
because it resides on Activity.
7) Activity is the UI of an application Fragment is the part of the Activity, it is
through which user can interact. an sub-Activity inside activity which has
its own Life Cycle which runs parallel to
the Activities Life Cycle.
8) Lifecycle of Activity: Lifecycle of Fragment:
Menus
Menus are a common user interface component in many types of applications. To provide
a familiar and consistent user experience, you can use the Menu to present user actions
and other options in your activities.
15
Figure 5-7. Example of Menu
Types of Menu
In Android there are three types of fundamental menus. They are options menu, contextual
menu and popup menu.
Options 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." Menu shown in above diagram is an example of options menu.
Context Menu
Android context menu appears when user press long clicks on the element. It is also known
as floating menu. It affects the selected content while doing action on it. It doesn't support
item shortcuts and icons.
16
Figure 5-8. Example of Context Menu
Popup Menu
A popup menu displays a list of items in a vertical list that's anchored to the view that
invoked the menu. It's good for providing an overflow of actions that relate to specific
content or to provide options for a second part of a command. Actions in a popup menu
should not directly affect the corresponding content—that's what contextual actions are
for. Rather, the popup menu is for extended actions that relate to regions of content in
your activity.
Android Popup Menu displays the menu below the anchor text if space is available
otherwise above the anchor text. It disappears if you click outside the popup menu.
17
Implementing menu in an Application
For all menu types, Android provides a standard XML format to define menu items. Instead
of building a menu in your activity's code, you should define a menu and all its items in an
XML menu resource. You can then inflate the menu resource (load it as a Menu object) in
your activity or fragment.
To define the menu, create an XML file inside your project's res/menu/ directory and build
the menu with the following elements:
<menu>
• Defines a Menu, which is a container for menu items. A <menu> element must be
the root node for the file and can hold one or more <item> and <group> elements.
<item>
• Creates a Menu Item, which represents a single item in a menu. This element may
contain a nested <menu> element in order to create a submenu.
<group>
• An optional, invisible container for <item> elements. It allows you to categorize
menu items so they share properties such as active state and visibility.
mymenu.xml
<item android:id="@+id/item1"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:title="Item 2"/>
<item android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="withText"/>
</menu>
The <item> element supports several attributes you can use to define an item's appearance
and behavior. The items in the above menu include the following attributes:
18
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
• A reference to a drawable to use as the item's icon.
android:title
• A reference to a string to use as the item's title.
android:showAsAction
• Specifies when and how this item should appear as an action item in the app bar.
FirstActivity.java
//handling clicks
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
//your stuffs
return true;
case R.id.item2:
//your stuffs
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
19
first_activity.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World !"
android:textSize="20sp"
android:layout_centerInParent="true" />
</RelativeLayout>
20
Creating Context Menu
To provide a floating context menu:
1. Register the View to which the context menu should be associated by calling
registerForContextMenu() and pass it the View.
2. Implement the onCreateContextMenu() method in your Activity or Fragment.
3. For event handling on click implement onContextItemSelected().
FirstActivity.java
btnClick=findViewById(R.id.btnClick);
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
//your stuffs
return true;
case R.id.item2:
//your stuffs
return true;
default:
return super.onContextItemSelected(item);
}
}
}
first_activity.xml
21
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show context menu"
android:layout_centerHorizontal="true"
android:layout_marginTop="20sp"
android:id="@+id/btnClick"
android:textSize="20sp" />
</RelativeLayout>
22
To perform an action when the user selects a menu item, you must implement the
PopupMenu.OnMenuItemClickListener interface and register it with your PopupMenu by
calling setOnMenuItemclickListener(). When the user selects an item, the system calls the
onMenuItemClick() callback in your interface.
FirstActivity.java
first_activity.xml
</RelativeLayout>
23
Above code produces following output.
Dialogs
A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog does not fill the screen and is normally used for modal events that
require users to take an action before they can proceed.
AlertDialog
• A dialog that can show a title, up to three buttons, a list of selectable items, or a
custom layout.
24
DatePickerDialog or TimePickerDialog
• A dialog with a pre-defined UI that allows the user to select a date or time.
Custom Dialog
• A custom dialog built by programmer as per the requirement.
25
Building an Alert Dialog
There are three regions of an alert dialog:
Title
This is optional and should be used only when the content area is occupied by a detailed
message, a list, or custom layout. If you need to state a simple message or question (such
as the dialog in figure 1), you don't need a title.
Content area
This can display a message, a list, or other custom layout.
Action buttons
There should be no more than three action buttons in a dialog.
FirstActivity.java
btnClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
builder.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//your stuffs
}
});
builder.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
26
first_activity.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Dialog"
android:layout_centerHorizontal="true"
android:layout_marginTop="20sp"
android:id="@+id/btnClick"
android:textSize="20sp" />
</RelativeLayout>
27
Building Custom Dialog and Setting Dialog Content
To demonstrate this topic, I am going to create a custom layout file for a dialog. This file
contains two EditText for inputting two numbers and a Button. After clicking Button sum
of these numbers will be displayed in a TextView.
So, let’s begin by creating custom layout for dialog.
custom_dialog.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="number"
android:id="@+id/edtFirst" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="number"
android:id="@+id/edtSecond" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Caluclate"
android:id="@+id/btnCalculate"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result:"
android:textSize="20sp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:id="@+id/txtResult" />
</LinearLayout>
first_activity.xml
<Button
android:layout_width="wrap_content"
28
android:layout_height="wrap_content"
android:text="Show Dialog"
android:layout_centerHorizontal="true"
android:layout_marginTop="20sp"
android:id="@+id/btnClick"
android:textSize="20sp" />
</RelativeLayout>
FirstActivity.java
btnClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
//wiring up widgets
edtFirst=view.findViewById(R.id.edtFirst);
edtSecond=view.findViewById(R.id.edtSecond);
btnCalculate=view.findViewById(R.id.btnCalculate);
txtResult=view.findViewById(R.id.txtResult);
btnCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int first,second, result;
first=Integer.parseInt(edtFirst.getText().toString());
second=Integer.parseInt(edtSecond.getText().toString());
result=first+second;
txtResult.setText("Result="+result);
}
});
29
AlertDialog alert = builder.create();
alert.show();
}
}
Exercise
30
9. Develop an android application to calculate area and perimeter of rectangle. Your
application must calculate and display area in one fragment and perimeter in
another fragment.
10. Differentiate activity and fragment with example.
11. What do you mean by menu? Explain its types.
12. Develop an android application to demonstrate options menu.
13. Develop an android application to demonstrate context menu.
14. Develop an android application to demonstrate popup menu.
15. What do you mean by dialog box? Explain its types.
16. How can you create a dialog fragment? Explain with example.
17. Develop an android application to demonstrate alert dialog.
18. How can you open custom dialog on button click? Explain with example.
19. Develop an android application to calculate simple interest in a dialog.
20. Develop an android application to calculate area and perimeter of a rectangle in a
dialog.
31
Unit – 6
ListView, GridView and RecyclerView [6 Hrs]
ListView
Android ListView is a view which groups several items and display them in vertical
scrollable list. The list items are automatically inserted to the list using an Adapter that
pulls content from a source such as an array or database.
An adapter actually bridges between UI components and the data source that fill data into
UI Component. Adapter holds the data and send the data to adapter view, the view can
take the data from adapter view and shows the data on different views like as spinner, list
view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by
binding them to an Adapter, which retrieves data from an external source and creates a
View that represents each data entry.
To display a list, you can include a list view in your layout XML file:
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
1
Following are the attributes associated with ListView:
• First argument this is the application context. Most of the case, keep it this.
• Second argument will be layout defined in XML file.
• Third argument is a TextView used for each string in the array.
• Final argument is an array of strings which will be populated in the TextView.
Once you have array adapter created, then simply call setAdapter() on
your ListView object as follows –
Features of ListView:
1. It displays a vertically-scrollable collection of views, where each view is positioned
immediately below the previous view in the list.
2. ListView uses Adapter classes which add the content from data source (such as
string array, array, database etc.)
3. ListView is a default scrollable which does not use other scroll view.
4. ListView is implemented by importing android.widget.ListView class.
Following example will demonstrate ListView. Here we are creating two layout file. One for
the ListView and another for list items to be displayed in a ListView. After creating layout
files, we use ArrayAdapter class to display String array in a ListView.
listview_example.xml
2
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:id="@+id/mylist"
android:layout_height="match_parent" />
</RelativeLayout>
listview_items.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/text"
android:textStyle="bold"
android:layout_margin="10dp" />
</RelativeLayout>
Now we are creating a java file to for displaying String array in a ListView.
ListViewExample.java
listView=findViewById(R.id.mylist);
//creating string array
String names[]=
{"Ram","Shyam","Hari","Sita","Gita","Rita"};
}
}
3
Figure 6-2. Output Demonstrating ListView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long l) {
//retrieving value
String value=adapter.getItem(position);
//displaying in Toast
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).
show();
}
});
4
custom_list.xml
<ListView
android:layout_width="match_parent"
android:id="@+id/mylist"
android:layout_height="match_parent" />
</RelativeLayout>
customlist_items.xml
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:id="@+id/image" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/title"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:layout_toRightOf="@+id/image"
android:text="Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:id="@+id/description"
android:layout_below="@+id/title"
android:text="This is description"
android:layout_toRightOf="@+id/image” />
</RelativeLayout>
5
MyListAdapter.java
//wiring widgets
TextView txtTitle = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById
(R.id.image);
TextView txtDescription = (TextView) rowView.findViewById
(R.id.description);
txtTitle.setText(title[position]);
imageView.setImageResource(image[position]);
txtDescription.setText(description[position]);
return rowView;
};
}
CustomListExample.java
// creating arrays
String[] title={
"Title 1", "Title 2",
"Title 3", "Title 4"};
String[] description={
"This is description 1",
"This is description 2",
"This is description 3",
"This is description 4"
};
6
int[] image={
//Replace with different images
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
}
}
7
Handling clicks in Custom ListView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long l) {
//retrieving title and description
String title=adapter.title[position];
String descrption=adapter.description[position];
}
});
GridView
Android GridView shows items in two-dimensional scrolling grid (rows & columns). The
items in the grid come from the ListAdapter associated with this view.
8
Following are the attributes associated with GridView:
Features of GridView
1. GridView displays items in two-dimensional scrolling grid.
2. GridView uses Adapter classes which add the content from data source (such as
string array, array, database etc.)
3. GridView is a default scrollable which does not use other scroll view.
4. GridView is implemented by importing android.widget.GridView class.
Following example will demonstrate GridView. Here we are creating two layout file. One
for the GridView and another for grid items to be displayed in a GridView. After creating
layout files, we use ArrayAdapter class to display String array in a GridView.
gridview_example.xml
<GridView
android:layout_width="match_parent"
android:id="@+id/mygrid"
android:numColumns="3"
android:layout_height="match_parent" />
</RelativeLayout>
gridview_items.xml
9
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/text"
android:textStyle="bold"
android:layout_margin="10dp" />
</RelativeLayout>
Now we are creating a java file to for displaying String array in a GridView.
GridViewExample.java
gridView =findViewById(R.id.mygrid);
//creating string array
String names[]=
{"Ram","Shyam","Hari","Sita","Gita"};
}
}
10
Figure 6-5. Output Demonstrating GridView
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long l) {
//retrieving value
String value=adapter.getItem(position);
//displaying in Toast
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).
show();
}
});
11
custom_grid.xml
<GridView
android:layout_width="match_parent"
android:id="@+id/mygrid"
android:numColumns="2"
android:layout_height="match_parent" />
</RelativeLayout>
customgrid_items.xml
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:layout_centerHorizontal="true"
android:id="@+id/image" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/title"
android:textStyle="bold"
android:layout_centerHorizontal="true"
android:layout_below="@+id/image"
android:text="Title" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:id="@+id/description"
android:text="This is description"
android:layout_centerHorizontal="true"
android:layout_below="@+id/title" />
</RelativeLayout>
12
MyGridAdapter.java
//wiring widgets
TextView txtTitle = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById
(R.id.image);
TextView txtDescription = (TextView) rowView.findViewById
(R.id.description);
txtTitle.setText(title[position]);
imageView.setImageResource(image[position]);
txtDescription.setText(description[position]);
return rowView;
};
}
CustomGridExample.java
// creating arrays
String[] title={
"Title 1", "Title 2",
"Title 3", "Title 4"};
String[] description={
"This is description 1",
"This is description 2",
"This is description 3",
"This is description 4"
};
13
int[] image={
//Replace with different images
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
}
}
14
Handling clicks in Custom GridView
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long l) {
//retrieving title and description
String title=adapter.title[position];
String descrption=adapter.description[position];
}
});
RecyclerView
The RecyclerView widget is a more advanced and flexible version of ListView. If your app
needs to display a scrolling list of elements based on large data sets (or data that frequently
changes), you should use RecyclerView. RecyclerView is mostly used to design the user
interface with the fine-grain control over the lists and grids of android application. It was
introduced in Marshmallow.
In the RecyclerView model, several different components work together to display your
data. The overall container for your user interface is a RecyclerView object that you add to
your layout. The RecyclerView fills itself with views provided by a layout manager that you
15
provide. You can use one of our standard layout managers (such as LinearLayoutManager
or GridLayoutManager), or implement your own.
The views in the list are represented by view holder objects. These objects are instances of
a class you define by extending RecyclerView.ViewHolder. Each view holder is in charge of
displaying a single item with a view. For example, if your list shows music collection, each
view holder might represent a single album. The RecyclerView creates only as many view
holders as are needed to display the on-screen portion of the dynamic content, plus a few
extra. As the user scrolls through the list, the RecyclerView takes the off-screen views and
rebinds them to the data which is scrolling onto the screen.
The view holder objects are managed by an adapter, which you create by extending
RecyclerView.Adapter. The adapter creates view holders as needed. The adapter also
binds the view holders to their data. It does this by assigning the view holder to a position,
and calling the adapter's onBindViewHolder() method. That method uses the view holder's
position to determine what the contents should be, based on its list position.
This RecyclerView model does a lot of optimization work so you don't have to:
• When the list is first populated, it creates and binds some view holders on either
side of the list. For example, if the view is displaying list positions 0 through 9, the
RecyclerView creates and binds those view holders, and might also create and bind
the view holder for position 10. That way, if the user scrolls the list, the next
element is ready to display.
• As the user scrolls the list, the RecyclerView creates new view holders as necessary.
It also saves the view holders which have scrolled off-screen, so they can be reused.
If the user switches the direction they were scrolling, the view holders which were
scrolled off the screen can be brought right back. On the other hand, if the user
keeps scrolling in the same direction, the view holders which have been off-screen
the longest can be re-bound to new data. The view holder does not need to be
created or have its view inflated; instead, the app just updates the view's contents
to match the new item it was bound to.
• When the displayed items change, you can notify the adapter by calling an
appropriate RecyclerView.Adapter.notify…() method. The adapter's built-in code
then rebinds just the affected items.
Features of RecyclerView
1. RecyclerView widget is a more advanced and flexible version of ListView. So, we
can use RecyclerView to display large dataset.
2. RecyclerView contains integrated animations for adding, updating and removing
items.
3. RecyclerView enforces the recycling of views by using the ViewHolder pattern.
4. RecyclerView supports both grids and lists.
5. RecyclerView supports vertical and horizontal scrolling.
16
Implementing RecyclerView in Application
To access the RecyclerView widget, you need to add following dependency to your project
as follows:
1. Open the build.gradle file for your app module.
2. Add the support library to the dependencies section
dependencies {
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
Now you can add the RecyclerView to your layout file as follows:
<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Once you have added a RecyclerView widget to your layout, obtain a handle to the object,
connect it to a layout manager, and attach an adapter for the data to be displayed:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
recyclerView = (RecyclerView) findViewById
(R.id.my_recycler_view);
17
To feed all your data to the list, you must extend the RecyclerView.Adapter class as
follows:
public class MyAdapter extends
RecyclerView.Adapter<MyAdapter.MyViewHolder> {
//add stuffs for displaying dataset in recyclerview
}
Following example demonstrates RecyclerView. Here, we are creating three arrays for
name, address and image. We are going to display these arrays in RecyclerView.
recyclerview_example.xml
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
recyclerview_items.xml
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:id="@+id/image" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtName"
android:textStyle="bold"
android:layout_toRightOf="@+id/image"
android:layout_marginTop="10dp"
android:text="Name" />
<TextView
18
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:id="@+id/txtAddress"
android:text="Address"
android:layout_toRightOf="@+id/image"
android:layout_below="@+id/txtName" />
</RelativeLayout>
Now it’s time to create java files. Here we need to java classes one will be the Activity and
another is needed for creating Adapter for RecycerView.
RecyclerViewExample.java
//creating array
String[] name={
"Ram","Shyam","Hari",
"Gita","Sita"
};
String[] address={
"Birtamode","Kathmandu","Pokhara",
"Birtamode","Kathmandu"
};
int[] image={
R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher
};
}
}
19
RecyclerViewAdapter.java
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
LayoutInflater layoutInflater = LayoutInflater.from
(context);
View listItem= layoutInflater.inflate
(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position){
holder.txtName.setText(name[position]);
holder.txtAddress.setText(address[position]);
holder.imageView.setImageResource(image[position]);
}
@Override
public int getItemCount() {
return name.length;
}
20
Above code produces following output:
Following code snipped can be used if you want to display items in grid layout.
MyData.java
21
}
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public int getImage(){
return image;
}
}
RecyclerViewExample.java
}
}
RecyclerViewAdapter.java
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View listItem= layoutInflater.inflate
22
(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
MyData current=data.get(position);
holder.txtName.setText(current.getName());
holder.txtAddress.setText(current.getAddress());
holder.imageView.setImageResource(current.getImage());
}
@Override
public int getItemCount() {
return data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView txtName,txtAddress;
ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.txtName);
txtAddress = itemView.findViewById(R.id.txtAddress);
imageView = itemView.findViewById(R.id.image);
}
}
}
23
Handling clicks in RecyclerView
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MyData current=data.get(position);
holder.txtName.setText(current.getName());
holder.txtAddress.setText(current.getAddress());
holder.imageView.setImageResource(current.getImage());
//handling clicks
holder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//retieving data
String name=current.getName();
String address=current.getAddress();
Toast.makeText(context,name,Toast.LENGTH_SHORT).show();
}
});
Exercise
24
Unit – 7
Advanced Android Concepts [10 Hrs]
The version of SQLite depends on the version of Android. See the following table:
Features of SQLite:
Following is a list of features which makes SQLite popular among other lightweight
databases:
o SQLite is totally free: SQLite is open-source. So, no license is required to work with
it.
o SQLite is server less: SQLite doesn't require a different server process or system to
operate.
o SQLite is very flexible: It facilitates you to work on multiple databases on the same
session on the same time.
o Configuration Not Required: SQLite doesn't require configuration. No setup or
administration required.
o SQLite is a cross-platform DBMS: You don't need a large range of different
platforms like Windows, Mac OS, Linux, and Unix. It can also be used on a lot of
embedded operating systems like Symbian, and Windows CE.
o Storing data is easy: SQLite provides an efficient way to store data.
o Variable length of columns: The length of the columns is variable and is not fixed.
It facilitates you to allocate only the space a field needs. For example, if you have a
varchar (200) column, and you put a 10 characters' length value on it, then SQLite
will allocate only 20 characters' space for that value not the whole 200 space.
o Provide large number of API's: SQLite provides API for a large range of
programming languages. For example: .Net languages (Visual Basic, C#), PHP, Java,
Objective C, Python and a lot of other programming language.
1
o SQLite is written in ANSI-C and provides simple and easy-to-use API.
o SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32,
WinCE, WinRT).
SQL vs SQLite
2
3. No Installation Needed
SQLite is very easy to learn. You don’t need to install and configure it. Just download
SQLite libraries in your computer and it is ready for creating the database.
4. Reliable
It updates your content continuously so, little or no work is lost in a case of power
failure or crash. SQLite is less bugs prone rather than custom written file I/O codes.
SQLite queries are smaller than equivalent procedural codes so, chances of bugs
are minimal.
5. Portable
SQLite is portable across all 32-bit and 64-bit operating systems and big- and little-
endian architectures. Multiple processes can be attached with same application file
and can read and write without interfering each other. It can be used with all
programming languages without any compatibility issue.
6. Accessible
SQLite database is accessible through a wide variety of third-party tools. SQLite
database's content is more likely to be recoverable if it has been lost. Data lives
longer than code.
7. Reduce Cost and Complexity
It reduces application cost because content can be accessed and updated using
concise SQL queries instead of lengthy and error-prone procedural queries. SQLite
can be easily extended in in future releases just by adding new tables and/or
columns. It also preserves the backwards compatibility.
Establishing Connection
To use SQLite database in android two classes are used for creating database and
manipulating data. They are SQLiteOpenHelper and SQLiteDatabase class.
The SQLiteOpenHelper class is used for database creation and version management. For
performing any database operation, you have to provide the implementation
of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
Method Description
public abstract void onCreate(SQLiteDatabase called only once when database is created for
db) the first time.
public abstract void onUpgrade(SQLiteDatabase called when database needs to be upgraded.
db, int oldVersion, int newVersion)
public synchronized void close () closes the database object.
public void onDowngrade(SQLiteDatabase db, called when database needs to be
int oldVersion, int newVersion) downgraded.
3
SQLiteDatabase class contains methods to be performed on SQLite database such as
create, update, delete, select etc. There are many methods in SQLiteDatabase class. Some
of them are as follows:
Method Description
void execSQL(String sql) executes the sql query not select query. Basically used for
creating database and tables.
long insert(String table, String inserts a record on the database. The table specifies the
nullColumnHack, ContentValues table name, nullColumnHack doesn't allow completely
values) null values. If second argument is null, android will store
null values if values are empty. The third argument
specifies the values to be stored.
int update(String table, updates a row.
ContentValues values, String
whereClause, String[] whereArgs)
Cursor rawQuery(String query, returns a cursor over the result set.
String[] selectionArgs)
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// create notes table
String createQuery="CREATE TABLE mytable(id INTEGER PRIMARY
KEY,name TEXT,address TEXT)";
db.execSQL(createQuery);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
// Create tables again
onCreate(db);
}
}
4
Data Manipulation
Following code snippet can be used to perform various manipulation operation like insert,
update, select and delete.
Following example will demonstrate the use of SQLite in Android. In this example, we are
creating three columns id, name and address in database table. Also we are creating
effective UI for showing different data manipulation operations.
sqlite_example.xml
5
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Id"
android:inputType="number"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:layout_below="@+id/edtId"
android:id="@+id/edtName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_below="@+id/edtName"
android:id="@+id/edtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:id="@+id/btnInsert"
android:text="Insert" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnInsert"
android:id="@+id/btnSelect"
android:layout_marginLeft="10dp"
android:text="Select" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnSelect"
android:id="@+id/btnUpdate"
android:layout_marginLeft="10dp"
android:text="Update" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnUpdate"
android:id="@+id/btnDelete"
android:layout_marginLeft="10dp"
android:text="Delete" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Selected Data:"
android:layout_below="@+id/btnSelect"
6
android:layout_marginTop="10dp"
android:id="@+id/txtData"
android:textSize="18sp" />
</RelativeLayout>
Now we are creating Helper class for SQLite operations by extending SQLiteOpenHelpter
as follows:
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// create notes table
String createQuery="CREATE TABLE mytable(id INTEGER PRIMARY
KEY,name TEXT, address TEXT)";
db.execSQL(createQuery);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
// Create tables again
onCreate(db);
}
7
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("name",name);
contentValues.put("address",address);
//updating row
db.update("mytable",contentValues,"id=?",new String[]{id});
db.close();
}
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
edtAddress=findViewById(R.id.edtAddress);
btnInsert=findViewById(R.id.btnInsert);
btnUpdate=findViewById(R.id.btnUpdate);
btnSelect=findViewById(R.id.btnSelect);
btnDelete=findViewById(R.id.btnDelete);
txtData=findViewById(R.id.txtData);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int id=Integer.parseInt(edtId.getText().toString());
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.insertData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Inserted
Successfully !", Toast.LENGTH_SHORT).show();
}
});
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//retrieving data
int id=0;
8
String name="",address="";
//calling select function
Cursor cursor=myDbHelper.selectData();
while (cursor.moveToNext()){
id=cursor.getInt(0);
name=cursor.getString(1);
address=cursor.getString(2);
}
//displaying data in TextView
txtData.setText("Id="+id+"\t Name="+name+"\tAddress="
+address);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.updateData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Updated
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
//calling delete function
myDbHelper.deleteData(id);
Toast.makeText(getApplicationContext(),"Data Deleted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
}
}
9
Figure 7-1. Output demonstrating various operation using SQLite
list_items.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_margin="10dp"
android:text="Id"
android:textStyle="bold"
10
android:id="@+id/txtId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtName"
android:textStyle="bold"
android:layout_toRightOf="@+id/txtId"
android:layout_marginTop="10dp"
android:text="Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtAddress"
android:text="Address"
android:layout_marginLeft="10dp"
android:layout_below="@+id/txtName" />
</RelativeLayout>
sqlite_example.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Id"
android:inputType="number"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:layout_below="@+id/edtId"
android:id="@+id/edtName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_below="@+id/edtName"
android:id="@+id/edtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:id="@+id/btnInsert"
android:text="Insert" />
11
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnInsert"
android:id="@+id/btnSelect"
android:layout_marginLeft="10dp"
android:text="Select" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnSelect"
android:id="@+id/btnUpdate"
android:layout_marginLeft="10dp"
android:text="Update" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnUpdate"
android:id="@+id/btnDelete"
android:layout_marginLeft="10dp"
android:text="Delete" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Selected Data:"
android:layout_below="@+id/btnSelect"
android:layout_marginTop="10dp"
android:id="@+id/txtData"
android:textSize="18sp" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mylist"
android:layout_below="@+id/txtData" />
</RelativeLayout>
ListAdapter.java
12
this.address=address;
}
txtId.setText(id.get(position).toString());
txtName.setText(name.get(position).toString());
txtAddress.setText(address.get(position).toString());
return rowView;
};
}
SqliteExample.java
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
edtAddress=findViewById(R.id.edtAddress);
btnInsert=findViewById(R.id.btnInsert);
btnUpdate=findViewById(R.id.btnUpdate);
btnSelect=findViewById(R.id.btnSelect);
btnDelete=findViewById(R.id.btnDelete);
listView=findViewById(R.id.mylist);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int id=Integer.parseInt(edtId.getText().toString());
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.insertData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Inserted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
13
public void onClick(View view) {
//creating dynamic array using Arraylist
//array is not suitable for this example
ArrayList<Integer> id=new ArrayList<>();
ArrayList<String> name=new ArrayList<>();
ArrayList<String> address=new ArrayList<>();
//calling select function
Cursor cursor=myDbHelper.selectData();
while (cursor.moveToNext()){
id.add(cursor.getInt(0));
name.add(cursor.getString(1));
address.add(cursor.getString(2));
}
ListAdapter adapter=new ListAdapter
(SqliteExample.this,id,name,address);
listView.setAdapter(adapter);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.updateData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Updated
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
//calling delete function
myDbHelper.deleteData(id);
Toast.makeText(getApplicationContext(),"Data Deleted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
}
}
14
Figure 7-2. Output demonstrating displaying retrieved data in ListView
sqlite_example.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Id"
android:inputType="number"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
15
android:layout_below="@+id/edtId"
android:id="@+id/edtName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_below="@+id/edtName"
android:id="@+id/edtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:id="@+id/btnInsert"
android:text="Insert" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnInsert"
android:id="@+id/btnSelect"
android:layout_marginLeft="10dp"
android:text="Select" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnSelect"
android:id="@+id/btnUpdate"
android:layout_marginLeft="10dp"
android:text="Update" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnUpdate"
android:id="@+id/btnDelete"
android:layout_marginLeft="10dp"
android:text="Delete" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Selected Data:"
android:layout_below="@+id/btnSelect"
android:layout_marginTop="10dp"
android:id="@+id/txtData"
android:textSize="18sp" />
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/recyclerview"
android:layout_below="@+id/txtData" />
</RelativeLayout>
16
DataModel.java
RecyclerViewAdapter.java
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(context);
View listItem= layoutInflater.inflate(R.layout.list_items,
parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final DataModel current=data.get(position);
holder.txtId.setText(current.getId()+"");
holder.txtName.setText(current.getName());
holder.txtAddress.setText(current.getAddress());
}
17
@Override
public int getItemCount() {
return data.size();
}
SqliteExample.java
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
edtAddress=findViewById(R.id.edtAddress);
btnInsert=findViewById(R.id.btnInsert);
btnUpdate=findViewById(R.id.btnUpdate);
btnSelect=findViewById(R.id.btnSelect);
btnDelete=findViewById(R.id.btnDelete);
recyclerView=findViewById(R.id.recyclerview);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int id=Integer.parseInt(edtId.getText().toString());
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.insertData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Inserted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
18
ArrayList<DataModel> data=new ArrayList<>();
//calling select function
Cursor cursor=myDbHelper.selectData();
while (cursor.moveToNext()){
int id=cursor.getInt(0);
String name=cursor.getString(1);
String address=cursor.getString(2);
DataModel dataModel=new DataModel(id,name,address);
data.add(dataModel);
}
//plotting in recyclerview
layoutManager=new LinearLayoutManager
(SqliteExample.this);
recyclerView.setLayoutManager(layoutManager);
recyclerViewAdapter=new RecyclerViewAdapter
(SqliteExample.this,data);
recyclerView.setAdapter(recyclerViewAdapter);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.updateData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Updated
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
//calling delete function
myDbHelper.deleteData(id);
Toast.makeText(getApplicationContext(),"Data Deleted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
}
}
19
Figure 7-3. Output demonstrating displaying retrieved data in RecyclerView
Introduction to API
API is an abbreviation for Application Programming Interface which is a collection of
communication protocols and subroutines used by various programs to communicate
between them. A programmer can make use of various API tools to make its program easier
and simpler. Also, an API facilitates the programmers with an efficient way to develop their
software programs.
Thus in simpler terms, an API helps two programs or applications to communicate with
each other by providing them with necessary tools and functions. It takes the request from
the user and sends it to the service provider and then again sends the result generated
from the service provider to the desired user.
A developer extensively uses API’s in his software to implement various features by using
an API call without writing the complex codes for the same. We can create an API for an
operating system, database systems, hardware system, for a JavaScript file or similar object
oriented files. Also, an API is similar to a GUI (Graphical User Interface) with one major
difference. Unlike GUI’s, an API helps the software developers to access the web tools while
a GUI helps to make a program easier to understand by the users.
20
Real life example of an API:
Suppose, we are searching for a hotel room on an online website. In this case, you have a
vast number of options to choose from and this may include the hotel location, the check-
in and check-out dates, price, accommodation details and many more factors. So in order
to book the room online, you need to interact with the hotel booking’s website which in
further will let you know if there is a room available on that particular date or not and at
what price.
Now in the above example, the API is the interface that actually communicates in between.
It takes the request of the user to the hotel booking’s website and in turn returns back the
most relevant data from the website to the intended user. Thus, we can see from this
example how an API works and it has numerous applications in real life from switching on
mobile phones to maintaining a large amount of databases from any corner of the world.
Types of API
There are various kinds of API’s available according to their uses and applications like the
Browser API which is created for the web browsers to abstract and to return the data from
surroundings or the Third party API’s, for which we have to get the codes from other sites
on the web (e.g. Facebook, Twitter).
2. Local APIs:
In this types of API, the programmers get the local middleware services. TAPI
(Telephony Application Programming Interface), .NET are common examples of
Local API’s.
3. Program APIs:
It makes a remote program appears to be local by making use of RPC’s (Remote
Procedural Calls). SOAP is a well-known example of this type of API.
21
Few other types of APIs:
• SOAP (SIMPLE OBJECT ACCESS PROTOCOL): It defines messages in XML format
used by web applications to communicate with each other.
• REST (Representational State Transfer): It makes use of HTTP to GET, POST, PUT,
or DELETE data. It is basically used to take advantage of the existing data.
• JSON-RPC: It use JSON for data transfer and is a light-weight remote procedural call
defining few data structure types.
• XML-RPC: It is based on XML and uses HTTP for data transfer. This API is widely used
to exchange information between two or more networks.
Introduction to JSON
JSON — short for JavaScript Object Notation — is a format for sharing data. As its name
suggests, JSON is derived from the JavaScript programming language, but it’s available for
use by many languages including Python, Ruby, PHP, and Java.
JSON uses the .json extension when it stands alone. When it’s defined in another file
format (as in .html), it can appear inside of quotes as a JSON string, or it can be an object
assigned to a variable. This format is easy to transmit between web server and client or
browser.
Very readable and lightweight, JSON offers a good alternative to XML and requires much
less formatting. This informational guide will get you up to speed with the data you can use
in JSON files, and the general structure and syntax of this format.
22
A JSON object looks something like this:
{
"sid" : "111",
"name" : "Raazu Poudel",
"address" : "Birtamode"
}
Although this is a very short example, and JSON could be many lines long, this shows that
the format is generally set up with two curly braces (or curly brackets) that look like this
{ } on either end of it, and with key-value pairs populating the space between. Most data
used in JSON ends up being encapsulated in a JSON object.
Key-value pairs have a colon between them as in "key" : "value". Each key-value pair is
separated by a comma, so the middle of a JSON looks like this: "key" : "value", "key" :
"value", "key": "value". In our example above, the first key-value pair is "sid" : "111".
getdata.php
<?php
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
23
//retrieving data
$sql = "SELECT * FROM student";
$result = $conn->query($sql);
echo json_encode($json);
$conn->close();
?>
Testing in browser:
DecodingJSON.java
24
" ]\n" +
"}";
//decoding JSON
JSONObject result=new JSONObject(json_data);
JSONArray data=result.getJSONArray("data");
for(int i=0;i<data.length();i++){
//fetching each row
JSONObject student=data.getJSONObject(i);
int sid=student.getInt("sid");
String name=student.getString("name");
String address=student.getString("address");
//displaying data
Log.d("Row "+i,sid+" "+name+" "+address);
}
}catch (Exception ex){
Log.d("exception",ex.toString());
}
}
}
25
To use volley in your application, we need to add following dependency in our project:
dependencies {
...
implementation 'com.android.volley:volley:1.1.1'
}
Also, to use Volley, you must add the android.permission.INTERNET permission to your
app's manifest. Without this, your app won't be able to connect to the network.
<uses-permission android:name="android.permission.INTERNET"/>
26
Displaying Retrieved data in RecyclerView
json_example.xml
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/recyclerview" />
</RelativeLayout>
list_items.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_margin="10dp"
android:text="Id"
android:textStyle="bold"
android:id="@+id/txtId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtName"
android:textStyle="bold"
android:layout_toRightOf="@+id/txtId"
android:layout_marginTop="10dp"
android:text="Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtAddress"
android:text="Address"
android:layout_marginLeft="10dp"
android:layout_below="@+id/txtName" />
</RelativeLayout>
27
DataModel.java
RecyclerViewAdapter.java
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(context);
View listItem= layoutInflater.inflate(R.layout.list_items,
parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final DataModel current=data.get(position);
holder.txtId.setText(current.getId()+"");
holder.txtName.setText(current.getName());
holder.txtAddress.setText(current.getAddress());
}
28
@Override
public int getItemCount() {
return data.size();
}
JsonExample.java
29
public void decodeJson(String response){
try{
ArrayList<DataModel> data=new ArrayList<>();
JSONObject result=new JSONObject(response);
JSONArray array=result.getJSONArray("data");
for(int i=0;i<array.length();i++){
//fetching each row
JSONObject student=array.getJSONObject(i);
int sid=student.getInt("sid");
String name=student.getString("name");
String address=student.getString("address");
DataModel dataModel=new DataModel(sid,name,address);
data.add(dataModel);
}
30
Sending Contents to Remote Server
send_data.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Id"
android:inputType="number"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:layout_below="@+id/edtId"
android:id="@+id/edtName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_below="@+id/edtName"
android:id="@+id/edtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:id="@+id/btnSubmit"
android:layout_centerHorizontal="true"
android:text="Submit" />
</RelativeLayout>
SendData.java
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
edtAddress=findViewById(R.id.edtAddress);
btnSubmit=findViewById(R.id.btnSubmit);
31
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
volleyRequest();
}
});
};;
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
}
setdata.php
<?php
32
//server credentials
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//inserting data
$sql = "INSERT INTO student(sid,name,address)
VALUES('".$sid."','".$name."','".$address."')";
$result = $conn->query($sql);
if($result)
echo"Data Inserted Successfully !";
else
echo"Failed to Insert Data !";
$conn->close();
?>
33
Implementing Google Maps in Android Application
Android allows us to integrate Google Maps in our application. For this Google provides us
a library via Google Play Services for using maps. In order to use the Google Maps API, you
must register your application on the Google Developer Console and enable the API.
An API key is needed to access the Google Maps servers. This key is free and you can use
it with any of your applications. If you haven’t created project, you can follow the below
steps to get started:
Step 1: Open Google developer console and sign in with your Gmail
account: https://console.developers.google.com/project
Step 2: Now create new project. You can create new project by clicking on the Create
Project button and give name to your project.
Step 3: Now click on APIs & Services and open Dashboard from it.
34
Step 5: Now search for Google Map Android API and enable it.
Step 7: Now click on Create credentials and choose API key. It will create API key to
integrate maps in your application.
35
Step 8: Now API your API key will be generated. Copy it and save it somewhere as we will
need it when implementing Google Map in our Android project.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Step 2: Add your generated API Key in your manifest file inside application tag as follows.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCWIdlyqlFhC7lOthG164H42heV1F7N3v0" />
dependencies {
. . .
. . .
implementation 'com.google.android.gms:play-services-maps:15.0.1'
}
map_activity.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
tools:context=".MapsActivity"
android:layout_width="match_parent"
36
android:layout_height="match_parent" />
</RelativeLayout>
MapsActivity.java
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Adding latitude and longitude
LatLng location = new LatLng(26.644096, 87.989391);
//Adding red marker to point location
mMap.addMarker(new MarkerOptions().position(location).
title("Marker in Birtamode"));
//Moving camera to desired location
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
//Adding zoom effect
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f) );
}
}
37
Figure 7-7. Output Demonstrating Google Map.
Note: Don’t use com.example…. as a package name because example is not supported by
play store. Instead you can rename your package name.
38
Step 2: Now click Create new keystore file. This keystore file is necessary to upload new
app and for updating existing app. If you have already created keystore file, then you can
click Choose existing keystore file.
Step 3: Now fill up information for creating new keystore file and click ok. Example is shown
below.
Note: Please remember keystore file, username and password because if it is lost, then
you will be unable to update your application.
39
Step 4: Now select V1 (Jar Signature) and click Finish. This will create signed APK for
release.
40
Step 5: Now click Event Log and locate to the folder where signed APK has been placed.
You can get your signed APK file inside release folder.
Here you need to create your developer account for lifetime by paying $25 using your
credit card. There is no limitation for number of apps. You can upload multiple apps using
a single account.
Step 2: Once you’ve created developer account following page will be displayed on screen.
Click Create Application.
41
Step 3: Next, give your application a title and the default language. You will now be moved
to the Store listing screen.
In store listing page you must add everything related to how your app will look in the store.
Following information must be added in this page:
• A short description of your application
• A full description
• Screenshots (at least 2)
• A Hi Resolution Icon
• A Feature Graphic
• The application’s type and its category
• Your email
• Your privacy policy (if you don’t have one, check the Not submitting a privacy policy
checkbox)
Step 4: Now go to the App Releases page and click Create Release button. Following page
will be displayed on screen.
42
Here you can upload your signed APK. Here you can also give the release a name and
specify what is new in this release. Pay special attention to whatever you type in what is
new in this release because it will appear in the Play store under the What’s New section.
Once you are done, you can press the Review button on the lower right corner of the page.
After pressing the Continue button, you will be asked several questions regarding the
content of your application. Just follow them in order, filling one by one.
43
Step 6: Last but not least, go to Pricing & distribution page. Be aware to fill in all the
required fields. In this last page, you can decide on:
• If your application will be free or not
• Which countries your application will be available to
• If it contains ads
• User programs
Step 7: After filling up all the information regarding Store Listings, Content Rating, Pricing
& Distribution etc. Now you can go to App Release page to publish your application. To
publish app in play store, click Rollout Button.
Exercise
44
12. Explain the advantages of JSON over XML.
13. How do your communication your application with remote server? Explain with the
help of suitable example.
14. Develop an android application that demonstrates retrieval of contents from
remote server.
15. Develop an android application that demonstrates sending of contents to remote
server.
16. Develop a phone directory application (Phone records must be stored in remote
server).
17. Explain the procedure for generating API key for displaying google map in your
application.
18. Develop an android application that displays google map.
19. Explain the procedure for generating signed APK.
20. Explain the procedure for publishing signed APK in play store.
45
Unit -8
Introduction to iOS Programming [8 Hrs]
Originally unveiled in 2007 for the iPhone, iOS has been extended to support other Apple
devices such as the iPod Touch (September 2007) and the iPad (January 2010). As of March
2018, Apple's App Store contains more than 2.1 million iOS applications, 1 million of which
are native for iPads. These mobile apps have collectively been downloaded more than 130
billion times.
The iOS user interface is based upon direct manipulation, using multi-touch gestures.
Interface control elements consist of sliders, switches, and buttons. Interaction with the
OS includes gestures such as swipe, tap, pinch, and reverse pinch, all of which have specific
definitions within the context of the iOS operating system and its multi-touch interface.
Internal accelerometers are used by some applications to respond to shaking the device
(one common result is the undo command) or rotating it in three dimensions (one common
result is switching between portrait and landscape mode). Apple has been significantly
praised for incorporating thorough accessibility functions into iOS, enabling users with
vision and hearing disabilities to properly use its products.
Major versions of iOS are released annually. On all recent iOS devices, iOS regularly checks
on the availability of an update, and if one is available, will prompt the user to permit its
automatic installation. The current version, iOS 13 was released to the public on 19
September 2019, introducing user interface tweaks and a dark mode, along with features
such as a redesigned Reminders app, a swipe keyboard, and an enhanced Photos app. iOS
13 does not support devices with less than 2 GB of RAM, including the iPhone 5s, iPod
Touch (6th generation), and the iPhone 6 and iPhone 6 Plus, which still make up over 10%
of all iOS devices. iOS 13 is exclusively for the iPhone and iPod touch as the iPad variant is
now called iPadOS.
iOS programming is a set of processes and procedures involved in writing software for
iPhone developed by Apple Inc.
iOS Platform
The iOS SDK (Software Development Kit) allows for the development of mobile apps on
iOS. While originally developing iPhone prior to its unveiling in 2007, Apple's then-CEO
Steve Jobs did not intend to let third-party developers build native apps for iOS, instead
directing them to make web applications for the Safari web browser. However, backlash
from developers prompted the company to reconsider with Jobs announcing in October
1
2007 that Apple would have a software development kit available for developers by
February 2008. The SDK was released on March 6, 2008.
The SDK is a free download for users of Mac personal computers. It is not available for
Microsoft Windows PCs. The SDK contains sets giving developers access to various
functions and services of iOS devices, such as hardware and software attributes. It also
contains an iPhone simulator to mimic the look and feel of the device on the computer
while developing. New versions of the SDK accompany new versions of iOS. In order to test
applications, get technical support, and distribute apps through App Store, developers are
required to subscribe to the Apple Developer Program.
Combined with Xcode, the iOS SDK helps developers write iOS apps using officially
supported programming languages, including Swift and Objective-C. Other companies have
also created tools that allow for the development of native iOS apps using their respective
programming languages.
Environment Setup
For development of iOS applications, we need to install Xcode editor, its apple integrated
development environment (IDE). The Xcode editor is the primary development tool for any
type of apple platforms like OSX Software’s, iPhones App, Mac, etc.
The requirement of the Xcode editor is that we should have minimum Apple Laptop or Mac
Computer for development of iOS application. We can download Xcode editor from Apple
website or Apple app store and this editor is completely free we don’t need to pay
anything for Apple.
2
Creating an Xcode Project
With Xcode installed, it is time to launch it for the first time. If all went well, you should see
the Welcome to Xcode window, which contains a few useful links and helps you create a
new application. To create your first iOS application, select Create a new Xcode
project from the list of options.
Xcode makes it easy to create a new Xcode project by offering a handful of useful project
templates. The Single View Application template is a good choice for your first application.
Select it from the list of iOS > Application templates and click Next.
3
Figure 8-2: Creating a Project
The next window lets you configure your Xcode project. Fill in the fields as shown in the
screenshot below and click Next.
4
Figure 8-3: Configuring a new Project
Once we click on Next button new dialog will open in that we need to select the location
to save our project. Once you select the location to save project then click on Create button
like as shown below.
5
Figure 8-4: Selecting project location
After click on Create button the Xcode will create and open a new project. By default, our
project structure will be like as shown below.
6
Building the Interface
In our project Main.storyboard and ViewController.swift are the main files which we used
to design app user interface and to maintain source code.
• Main.storyboard - Its visual interface editor and we will use this file to design our
app user interface
• ViewController.swift - It contains source code of our application and we use this
file to write any code related to our app.
Now in project select Main.storyboard file the Xcode will open visual interface editor like
as shown below.
Now select ViewController.swift file in your project that view will be like as shown below.
7
Figure 8-7: First look of ViewController.swift
Now we will add controls to our application for that open Object Library. The Object Library
will appear at the bottom of Xcode in right side. In case if you don't find Object library, click
on the button which is at the third position from the left in the library selector bar like as
shown below. (Alternatively you can choose View -> Utilities -> Show Object Library).
8
Figure 8-9: Adding label to the project
Now we will change the text of label for that click on label in right side the label properties
will open in Text property textbox write the “Hello World”. Once we change the label text
now we will change the position of label control for that select label control -> Click
on label control and just drag the label control like as shown below.
9
Once we click and drag the label control we can able to see multiple properties like
“Center Horizontally in Container”, “Center Vertically in Container”, etc.
We will set “Center Horizontally in Container”, “Center Vertically in Container” properties
for label control to make our label appeared in centered position. Once we set these two
properties we can able to see two lines which appear like cross on our hello world label like
as shown below.
10
Once we select the required simulator then we will run our application by
using Run button, located in the top-left corner of the Xcode toolbar like as shown below.
Once we run the iOS hello world application we will get output like as shown below.
Making Connections
A connection lets one object know where another object is in memory so that the two
objects can communicate. There are two kinds of connections that you can make in
Interface Builder: outlets and actions. An outlet is a reference to an object. An action is a
method that gets triggered by a button or some other view that the user can interact with,
like a slider or a picker.
For making connections you have to use iOS Outlets and Actions. In iOS Outlets and Actions
are basically the property symbol of IBoutlets and IBActions where IB called Interface
Builder. Outlet is basically the reference object and action is the method which is used to
perform some type of actions.
Following is the syntax of using iOS Actions and Outlets in applications.
If you observe above syntax we used “@IBOutlet” to add reference of label control and
we used “@IBAction” to add button click action to change label control text.
11
To demonstrate connection, let’s take an example of an iOS application containing two
view controls (one label control and another button control). While clicking on the button
control we must be able to change text of label.
So, let’s begin by adding label and button controls in our storyboard.
Now we will map our controls to ViewController.swift file for that we need to
use Assistant editor in Xcode. Open the Xcode editor in assistant mode for that click on
the overlap circle button in Xcode toolbar at top right side like as shown below.
Now press Ctrl button in keyboard and drag the controls from your canvas to the code
display in ViewController.swift file like as shown below.
12
Figure 8-17: Connecting UI controls to application code
Once you drag the controls from viewcontroller to code in ViewController.swift file now
write code in @IBAction to change the label text when click on button. Once we make
required changes our ViewController.swift file should be like as shown below.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labeltxt: UILabel!
@IBAction func buttonaction(sender: AnyObject) {
labeltxt.text = "We love BCA "
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Once we run application click on button it will change the label text. The button performs
the action for label to change its outlet text.
13
Figure 8-18: Output demonstrating connection
Swift maintains the expressiveness of Objective-C while introducing a syntax that is safer,
succinct, and readable. It emphasizes type safety and adds advanced features such as
optionals, generics, and sophisticated structures and enumerations. Most importantly,
Swift allows the use of these new features while relying on the same tested, elegant iOS
frameworks that developers have built upon for years.
Types in Swift
Swift types can be arranged into three basic groups: structures, classes, and enumerations.
All three can have:
• properties – values associated with a type
• initializers – code that initializes an instance of a type
• instance methods – functions specific to a type that can be called on an instance of
that type
• class or static methods – functions specific to a type that can be called on the type
itself
14
c
Variables
You must declare them using var keyword as follows –
var variableName = <initial value>
You can provide a type annotation when you declare a variable, to be clear about the kind
of values the variable can store. Here is the syntax –
var variableName:<data type> = <optional initial value>
var varA = 42
print(varA)
var varB:Float
varB = 3.14159
print(varB)
When we run the above program using playground, we get the following result −
42
3.1415901184082
Optionals
Swift also introduces Optionals type, which handles the absence of a value. Optionals say
either "there is a value, and it equals x" or "there isn't a value at all".
15
Here’s an optional Integer declaration –
var perhapsInt: Int?
The above declaration is equivalent to explicitly initializing it to nil which means no value –
var perhapsStr: String? = nil
if myString != nil {
print(myString)
} else {
print("myString has nil value")
}
When we run the above program using playground, we get the following result –
myString has nil value
Constants
Constants refer to fixed values that a program may not alter during its execution. Constants
can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except the fact that their values cannot be
modified after their definition.
Before you use constants, you must declare them using let keyword as follows –
let constantName = <initial value>
When we run the above program using playground, we get the following result –
42
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. Swift is rich in built-in operators and provides the following types of
operators −
• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Range Operators
16
• Misc Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by Swift language.
Assume variable A holds 10 and variable B holds 20, then −
Comparison Operators
The following table shows all the relational operators supported by Swift language. Assume
variable A holds 10 and variable B holds 20, then –
Logical Operators
The following table shows all the logical operators supported by Swift language. Assume
variable A holds 1 and variable B holds 0, then –
17
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is true.
state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Bitwise Operators
Bitwise operators work on bits and perform bit by bit operation. The truth tables for &, |,
and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
Bitwise operators supported by Swift language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then 7−
18
>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15, which
moved right by the number of bits specified by the is 0000 1111
right operand.
Assignment Operators
Swift supports the following assignment operators –
Range Operators
Swift includes two range operators, which are shortcuts for expressing a range of values.
The following table explains these two operators.
19
…2 gives beginning… to
1,2
Misc Operators
Swift supports a few other important operators including range and ? : which are explained
in the following table.
Decision Making
Swift provides the following types of decision making statements.
print("Value of
variable varA is
\(varA)");
Output:
varA is less than 20
Value of variable varA
is 10
20
/* If condition is
true then print the
following */
print("varA is less
than 20");
} else {
/* If condition is
false then print the
following */
print("varA is not
less than 20");
}
print("Value of
variable varA is
\(varA)");
Output:
varA is not less than
20
Value of variable varA
is 100
} else if varA == 50 {
/* If condition is
true then print the
following */
print("varA is equal
to than 50");
} else {
/* If condition is
false then print the
following */
print("None of the
values is matching");
}
21
print("Value of
variable varA is
\(varA)");
Output:
None of the values is
matching
Value of variable varA
is 100
if varB == 200 {
/* If condition
is true then print the
following */
print("Second
condition is also
satisfied");
}
}
print("Value of
variable varA is
\(varA)");
print("Value of
variable varB is
\(varB)");
Output:
First condition is
satisfied
Second condition is
also satisfied
Value of variable varA
is 100
Value of variable varB
is 200
22
5 switch statement A switch statement var index = 10
allows a variable to be switch index {
tested for equality case 100 :
against a list of values. print( "Value of
index is 100")
case 10,15 :
print( "Value of
index is either 10 or
15")
case 5 :
print( "Value of
index is 5")
default :
print( "default
case")
}
Output:
Value of index is
either 10 or 15
Loops
Swift programming language provides the following kinds of loop to handle looping
requirements.
Output:
Value of index is 10
Value of index is 20
Value of index is 30
Output:
Value of index is 10
Value of index is 11
23
Value of index is 12
Value of index is 13
Value of index is 14
Output:
Value of index is 10
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Arrays
You can create an empty array of a certain type using the following initializer syntax –
var someArray = [SomeType]()
You can use the following statement to create an empty array of Int type having 3 elements
and the initial value as zero –
var someInts = [Int](count: 3, repeatedValue: 0)
Following is one more example to create an array of three elements and assign three values
to that array –
var someInts:[Int] = [10, 20, 30]
You can retrieve a value from an array by using subscript syntax, passing the index of the
value you want to retrieve within square brackets immediately after the name of the array
as follows –
var someVar = someArray[index]
The following example shows how to create, initialize, and access arrays –
var someInts = [Int](count: 3, repeatedValue: 10)
Output:
Value of first element is 10
Value of second element is 10
Value of third element is 10
24
Strings
You can create a String either by using a string literal or creating an instance of a String
class as follows –
// String creation using String literal
var stringA = "Hello, Swift!"
print( stringA )
Empty String
You can create an empty String either by using an empty string literal or creating an
instance of String class as shown below. You can also check whether a string is empty or
not using the Boolean property isEmpty.
if stringA.isEmpty {
print( "stringA is empty" )
} else {
print( "stringA is not empty" )
}
if stringB.isEmpty {
print( "stringB is empty" )
} else {
print( "stringB is not empty" )
}
Output:
stringA is empty
stringB is empty
String Concatenation
You can use the + operator to concatenate two strings or a string and a character, or two
characters. Here is a simple example –
let constA = "Hello,"
let constB = "World!"
Output:
Hello,World!
25
String Length
Swift strings do not have a length property, but you can use the global count() function to
count the number of characters in a string. Here is a simple example –
Output:
Hello, Swift 4!, length is 15
String Comparison
You can use the == operator to compare two strings variables or constants. Here is a simple
example –
var varA = "Hello, Swift!"
var varB = "Hello, World!"
if varA == varB {
print( "\(varA) and \(varB) are equal" )
} else {
print( "\(varA) and \(varB) are not equal" )
}
Output:
Hello, Swift! and Hello, World! are not equal
Function
A function's arguments must always be provided in the same order as the function's
parameter list and the return values are followed by →.
Take a look at the following code. The student’s name is declared as string datatype
declared inside the function 'student' and when the function is called, it will return
student’s name.
26
When we run the above program using playground, we get the following result –
First Program
About Functions
When we run above program using playground, we get the following result –
40
45
120
When we run the above program using playground, we get the following result −
Alice
The view hierarchy is a major part of the responder chain, and it is something that the
application frameworks use to determine the layering order of views when they render the
content of a window in a drawing pass. The view hierarchy is also the governing concept
behind view composition: You construct compound views by adding sub views to a super
view. Finally, the view hierarchy is a critical factor in the multiple coordinate systems found
in a window.
27
Figure 8-20. View Hierarchy in iOS
A view is related to other views through two properties, and these relationships determine
the form of the hierarchy:
• super view — The view above a given view in the hierarchy; this is the view that
encloses it. All views except the topmost view must have a super view.
• sub views — The views below a given view in the hierarchy; these are the views
that it encloses. A view may have any number of sub views, or it may have none.
28
Figure 8-21. Example of View Hierarchy in iOS
29
To demonstrate storyboard now I am going to create a storyboard containing a Tab and
multiple view controllers linking with the Tab.
So, let’s begin by creating a project with following information:
§ Product Name: MyExample.
§ Organization Name: Fill this in however you like.
§ Organization Identifier: The identifier you use for your apps.
§ Language: Swift.
§ User Interface: Storyboard.
§ Make sure you’ve unchecked the Use Core Data, Include Unit Tests and UI
Tests options.
Open Main.storyboard in the Project navigator to view it in the Interface Builder editor:
Here, you see a single view controller containing an empty view. The arrow pointing to the
view controller from the left indicates it’s the initial view controller for this
storyboard. Xcode enables Auto Layout and Size Classes by default for storyboards. They
allow you to make flexible user interfaces that can resize easily, which is useful for
supporting various sizes of iPhones and iPads.
30
Figure 8-24. Adding Tab Controller to Main. Storyboard
The arrows between the tab bar controller and the view controllers it contains represent
the container relationship. The icon shown below, in the middle of the arrow body,
signifies that they have an embed relationship.
31
Build and run and you’ll see something like this in the console:
This error simply indicates that the app didn’t find the initial view controller to show.
To fix this error, Open Main.storyboard and select the Tab Bar Controller Scene. On the
right, select the Attribute inspector.
Checking this box will identify the selected view controller as the initial entry point for the
storyboard you’re on. Also, an arrow will appear on the left of the view controller.
Now, build and run and you’ll see an empty view controller with a tab bar that has two
items at the bottom.
32
Figure 8-26. Output demonstrating Tab View Controller
33
We can apply custom styles to the content in iOS label
control like changing the font style, font size, adding
background colors, etc. based on our requirements.
3 iOS UI Text Fields In iOS Text fields are used to allow users to enter single
line of text as an input to an app. The text fields
automatically bring up a keyboard to enter a text
whenever the user touch or taped it and these text fields
are helpful to gather small amounts of text from the user
like name, email, etc. By using text fields, we can perform
some actions like search operation, based on that text.
We can use Text Fields in our iOS application by
adding UITextField class reference in our applications.
4 iOS UI Image View In iOS, image view is used to show the images in iOS
application and it will resize the images automatically to
make fit with the current size of view.
By using iOS image view, we can show single image or
animated sequence of images with transparent or opaque
background based on our requirement.
5 iOS Progress Bar In iOS progress indicators or progress bars are used to
(Progress View) show the progress of task in application instead of making
people staring at a static screen while performing lengthy
data operations.
By using iOS progress indicators or bars we can make the
people to understand that how long the process will take
to finish the task like as shown below:
34
By using iOS switches we can implement features like
allowing users to turn the settings on or off based on
their requirements.
The visual representation of iOS switches with on and off
options will be like as shown below:
11 iOS UI Scroll View In iOS, scroll view is used to show the content which is
larger than the scroll view boundaries like viewing larger
content in documents, showing multiple images in app. In
our iOS application whenever we see the scroll view it is
indication that there is extra content other than visible
area.
We can use Scroll View in our iOS applications by
adding UIScrollView class reference.
35
Creating a Simple iOS Application
Here we going to create a simple application to show the addition of two numbers. Our
application contains two Text Fields for inputting two numbers and a Button to trigger click
event. Also I will create a Label for displaying the result.
import UIKit
class ViewController: UIViewController {
36
}
Exercise
37
Model Question – Set 1
Mobile Programming
BCA Sixth Semester
6. During an Activity life-cycle, what is the first callback method invoked by the
system?
A. onStop() B. onStart()
C. onCreate() D. onRestore()
Answer: C
7. What Activity method you use to retrieve a reference to an Android view by using
the id attribute of a resource XML?
A. findViewByReference(int id); B. findViewById(int id)
C. retrieveResourceById(int id) D. findViewById(String id)
Answer: B
8. What does the src folder contain?
A. Image and icon files B. XML resource files
C. The application manifest file D. Java source code files
Answer: D
Mobile Programming
BCA Sixth Semester
3. What is the name of the program that converts Java byte code into Dalvik byte
code?
A. Android Interpretive Compiler (AIC) B. Dalvik Converter
C. Dex compiler D. Mobile Interpretive Compiler (MIC)
Answer: C
5. When developing for the Android OS, Java bytecode is compiled into what?
A. Java source code B. Dalvik application code
C. Dalvik byte code D. C source code
Answer: C
Mobile Programming
BCA Sixth Semester
6. The XML file that contains all the text that your application uses.
A. stack.xml B. text.xml
C. strings.xml D. string.java
Answer: C
Dashboard
activity_main.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dashboard"
android:textSize="20sp"
android:id="@+id/dashboard"
android:layout_margin="10dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="2"
android:id="@+id/linear1"
android:layout_margin="10dp"
android:layout_below="@+id/dashboard"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#FF69B4"
android:orientation="vertical"
android:padding="10dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="18sp"
android:textStyle="bold"
android:text="Today's Income" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtIncome"
android:layout_gravity="center"
android:textSize="18sp"
android:text="0" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:background="#FA8072"
android:layout_marginLeft="10dp"
android:padding="10dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="18sp"
android:textStyle="bold"
android:text="Today's Expenses" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtExpenses"
android:layout_gravity="center"
android:textSize="18sp"
android:text="0" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="2"
android:id="@+id/linear2"
android:layout_margin="10dp"
android:layout_below="@+id/linear1"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#F4A460"
android:orientation="vertical"
android:padding="10dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="18sp"
android:textStyle="bold"
android:text="Today's Balance" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtBalance"
android:layout_gravity="center"
android:textSize="18sp"
android:text="0" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:background="#DA70D6"
android:layout_marginLeft="10dp"
android:padding="10dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="18sp"
android:textStyle="bold"
android:gravity="center"
android:id="@+id/txtDetails"
android:padding="1dp"
android:lines="2"
android:text="View Today's Details" />
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Income/Expenses"
android:textAllCaps="false"
android:textSize="18sp"
android:layout_below="@+id/linear2"
android:layout_margin="10dp"
android:id="@+id/btnEntry"
android:background="#9370DB"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date Wise Report"
android:textAllCaps="false"
android:textSize="18sp"
android:layout_below="@+id/btnEntry"
android:layout_margin="10dp"
android:id="@+id/btnReport"
android:background="#4682B4"/>
</RelativeLayout>
MainActivity.java
txtIncome=findViewById(R.id.txtIncome);
txtExpenses=findViewById(R.id.txtExpenses);
txtBalance=findViewById(R.id.txtBalance);
txtDetails=findViewById(R.id.txtDetails);
btnEntry=findViewById(R.id.btnEntry);
btnReport=findViewById(R.id.btnReport);
myDatabase=new MyDatabase(this);
btnEntry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,
DataEntry.class);
startActivity(intent);
}
});
txtDetails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,
TodayDetails.class);
startActivity(intent);
}
});
btnReport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,
DateWiseReport.class);
startActivity(intent);
}
});
@Override
protected void onResume(){
super.onResume();
//displaying data of current date
loadData();
}
Data Entry
data_entry.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Date"
android:id="@+id/edtDate"
android:inputType="date"
android:layout_margin="10dp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:entries="@array/title"
android:id="@+id/spTitle" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Amount"
android:id="@+id/edtAmount"
android:inputType="number"
android:layout_margin="10dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Submit"
android:id="@+id/btnSubmit"/>
</LinearLayout>
DataEntry.java
edtDate=findViewById(R.id.edtDate);
edtAmount=findViewById(R.id.edtAmount);
spTitle=findViewById(R.id.spTitle);
btnSubmit=findViewById(R.id.btnSubmit);
myDatabase=new MyDatabase(this);
edtDate.setText(MainActivity.getCurrentDate());
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//getting data
String date=edtDate.getText().toString();
String title=spTitle.getSelectedItem().toString();
String amount=edtAmount.getText().toString();
//validating data
if(date.equals("")){
Toast.makeText(DataEntry.this,"Please Enter Date !",
Toast.LENGTH_LONG).show();
} else if(amount.equals("")) {
Toast.makeText(DataEntry.this, "Please Enter Amount
!",Toast.LENGTH_LONG).show();
} else if(title.equals("Select Title")){
Toast.makeText(DataEntry.this,"Please Select Title
!",Toast.LENGTH_LONG).show();
}else{
//checking income or expenses
if(title.equals("Income"))
myDatabase.insertData(date,amount,"0");
else
myDatabase.insertData(date,"0",amount);
Toast.makeText(DataEntry.this,"Data Inserted
Successfully !",Toast.LENGTH_LONG).show();
edtAmount.setText("");
spTitle.setSelection(0);
}
}
});
}
}
Database
MyDatabase.java
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// create notes table
String createQuery="CREATE TABLE mytable(id INTEGER PRIMARY KEY
AUTOINCREMENT,date TEXT,income TEXT,expenses TEXT)";
db.execSQL(createQuery);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
// Create tables again
onCreate(db);
}
today_details.xml
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
list_items.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date: 2020-04-03"
android:layout_margin="10dp"
android:id="@+id/txtDate"
android:textStyle="bold"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Income: 20000"
android:layout_margin="10dp"
android:id="@+id/txtIncome"
android:textStyle="bold"
android:layout_toRightOf="@+id/txtDate"
android:textColor="#3F51B5"
android:visibility="gone"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expenses: 10000"
android:layout_margin="10dp"
android:id="@+id/txtExpenses"
android:textStyle="bold"
android:layout_toRightOf="@+id/txtDate"
android:textColor="#FF4081"
android:visibility="gone"
android:textSize="18sp" />
</RelativeLayout>
DataModel.java
}
RecyclerViewAdapter.java
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(context);
View listItem= layoutInflater.inflate(R.layout.list_items,
parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final DataModel current=data.get(position);
holder.txtDate.setText("Date: "+current.getDate());
if(current.getExpenses()==0){
holder.txtExpenses.setVisibility(View.GONE);
holder.txtIncome.setVisibility(View.VISIBLE);
holder.txtIncome.setText("Income: "+current.getIncome());
}else{
holder.txtExpenses.setVisibility(View.VISIBLE);
holder.txtIncome.setVisibility(View.GONE);
holder.txtExpenses.setText("Expenses: "+
current.getExpenses());
}
holder.relativeLayout.setOnClickListener(new View.
OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(context,ModifyDetails.class);
intent.putExtra("id",current.getId());
intent.putExtra("date",current.getDate());
if(current.getExpenses()==0)
intent.putExtra("amount",current.getIncome());
else
intent.putExtra("amount",current.getExpenses());
context.startActivity(intent);
}
});
@Override
public int getItemCount() {
return data.size();
}
TodayDetails.java
@Override
protected void onResume(){
super.onResume();
loadData();
}
layoutManager=new LinearLayoutManager(this);
recyclerAdapter=new RecyclerViewAdapter(this,data);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerAdapter);
}
}
Date wise Report
datewise_report.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Between:"
android:layout_margin="10dp"
android:textSize="18sp"
android:textStyle="bold"
android:id="@+id/between" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Date"
android:textSize="18sp"
android:inputType="date"
android:layout_toRightOf="@+id/between"
android:id="@+id/edtDate1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="and"
android:layout_margin="10dp"
android:layout_toRightOf="@+id/edtDate1"
android:textSize="18sp"
android:textStyle="bold"
android:id="@+id/and" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Date"
android:textSize="18sp"
android:inputType="date"
android:layout_toRightOf="@+id/and"
android:id="@+id/edtDate2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:id="@+id/btnSubmit"
android:layout_below="@+id/between"
android:layout_centerHorizontal="true" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_marginTop="10dp"
android:scrollbars="vertical"
android:layout_below="@+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
DateWiseReport.java
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loadData();
}
});
modify_details.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Date"
android:id="@+id/edtDate"
android:inputType="date"
android:layout_margin="10dp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:entries="@array/title"
android:id="@+id/spTitle" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Amount"
android:id="@+id/edtAmount"
android:inputType="number"
android:layout_margin="10dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Update"
android:id="@+id/btnUpdate"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Delete"
android:id="@+id/btnDelete"/>
</LinearLayout>
ModifyDetails.java
edtDate=findViewById(R.id.edtDate);
edtAmount=findViewById(R.id.edtAmount);
spTitle=findViewById(R.id.spTitle);
btnUpdate=findViewById(R.id.btnUpdate);
btnDelete=findViewById(R.id.btnDelete);
myDatabase=new MyDatabase(this);
Intent intent=getIntent();
id=intent.getIntExtra("id",0);
date=intent.getStringExtra("date");
amount=intent.getIntExtra("amount",0);
edtDate.setText(date);
edtAmount.setText(amount+"");
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myDatabase.deleteData(String.valueOf(id));
Toast.makeText(ModifyDetails.this,"Data Deleted
Successfully !",Toast.LENGTH_LONG).show();
finish();
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//getting data
String date=edtDate.getText().toString();
String title=spTitle.getSelectedItem().toString();
String amount=edtAmount.getText().toString();
//validating data
if(date.equals("")){
Toast.makeText(ModifyDetails.this,"Please Enter Date
!",Toast.LENGTH_LONG).show();
} else if(amount.equals("")) {
Toast.makeText(ModifyDetails.this, "Please Enter
Amount !", Toast.LENGTH_LONG).show();
} else if(title.equals("Select Title")){
Toast.makeText(ModifyDetails.this,"Please Select
Title !",Toast.LENGTH_LONG).show();
}else{
//checking income or expenses
if(title.equals("Income"))
myDatabase.updateData(String.valueOf(id),
date,amount,"0");
else
myDatabase.updateData(String.valueOf(id),
date,"0",amount);
Toast.makeText(ModifyDetails.this,"Data Updated
Successfully !",Toast.LENGTH_LONG).show();
finish();
}
}
});
}
}
Manifest File
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.raazu.incomeexprensestracker">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
</manifest>
build.gradle
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
}
Sample Project -2 Jokes/Stories Application
Project Features-
• Jokes and stories can be added by admin.
• Admin can update/delete jokes/stories.
• All data are saved permanently on remote server.
• Users can read jokes/stories anytime/anywhere.
• Data once loaded are saved locally using SQLite.
• So, users are able to read jokes/stories even if there is no internet connection.
Project Files-
Project Prototype:
Database Tables
Necessary API’s
login.php
<?php
$user=$_POST["username"];
$pass=$_POST["password"];
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//retrieving data
$sql = "SELECT * FROM tbllogin WHERE username='$user' AND
password='$pass'";
$result = $conn->query($sql);
if($result->num_rows>0)
echo "Success";
else
echo "Failed";
$conn->close();
?>
storedata.php
<?php
//server credentials
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//inserting data
$sql = "INSERT INTO tbldata(title,category,description)
VALUES('".$title."','".$category."','".$description."')";
$result = $conn->query($sql);
if($result)
echo"Data Inserted Successfully !";
else
echo"Failed to Insert Data !";
$conn->close();
?>
getdetails.php
<?php
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server,$username,$password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//retrieving data
$sql="SELECT * FROM tbldata ORDER BY id DESC";
$result = $conn->query($sql);
echo json_encode($json);
$conn->close();
?>
updatedata.php
<?php
//server credentials
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//updating data
$sql = "UPDATE tbldata SET title='$title', category='$category',
description='$description' WHERE id='$id'";
$result = $conn->query($sql);
if($result)
echo"Data Updated Successfully !";
else
echo"Failed to Update Data !";
$conn->close();
?>
deletedata.php
<?php
//server credentials
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//updating data
$sql = "DELETE FROM tbldata WHERE id='$id'";
$result = $conn->query($sql);
if($result)
echo"Data Deleted Successfully !";
else
echo"Failed to Delete Data !";
$conn->close();
?>
ConnectionDetector.java
}
return false;
}
}
MyDatabase.java
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// create notes table
String createQuery="CREATE TABLE mytable(id INTEGER PRIMARY KEY,
title TEXT,category TEXT,description TEXT)";
db.execSQL(createQuery);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
// Create tables again
onCreate(db);
}
Dashboard
activity_main.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dashboard"
android:textSize="20sp"
android:layout_margin="10dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:background="#F4A460"
android:orientation="vertical"
android:padding="15dp"
android:layout_margin="15dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20sp"
android:textStyle="bold"
android:text="Total Jokes" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtJokes"
android:gravity="center"
android:textSize="18sp"
android:text="0" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:background="#FA8072"
android:orientation="vertical"
android:padding="15dp"
android:layout_margin="15dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20sp"
android:textStyle="bold"
android:text="Total Stories" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtStories"
android:gravity="center"
android:textSize="18sp"
android:text="0" />
</LinearLayout>
</LinearLayout>
MainActivity.java
txtJokes=findViewById(R.id.txtJokes);
txtStories=findViewById(R.id.txtStories);
myDatabase=new MyDatabase(this);
cd=new ConnectionDetector(this);
txtJokes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,
ViewData.class);
intent.putExtra("category","Jokes");
startActivity(intent);
}
});
txtStories.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,
ViewData.class);
intent.putExtra("category","Stories");
startActivity(intent);
}
});
//inserting to SQLite
myDatabase.insertData(id,title,category,description);
if(category.equals("Jokes"))
totalJokes++;
else
totalStories++;
}
//setting data
txtJokes.setText(totalJokes+"");
txtStories.setText(totalStories+"");
//handling clicks
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.admin:
Intent intent=new Intent(MainActivity.this,Login.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Displaying Data
view_data.xml
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/recyclerview"
android:layout_height="wrap_content"/>
</LinearLayout>
list_items.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title: MyTitle"
android:textSize="18sp"
android:textStyle="bold"
android:lines="1"
android:id="@+id/txtTitle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Category: Jokes"
android:textSize="16sp"
android:textStyle="bold"
android:id="@+id/txtCategory"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Description: This is description"
android:lines="2"
android:id="@+id/txtDescription"
android:textSize="16sp"
android:textStyle="bold"/>
</LinearLayout>
description.xml
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Modify Jokes/Stories"
android:textAllCaps="false"
android:textSize="18sp"
android:visibility="gone"
android:id="@+id/btnModify"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title: MyTitle"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:id="@+id/txtTitle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Category: Jokes"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:id="@+id/txtCategory"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Description: This is description"
android:id="@+id/txtDescription"
android:textSize="18sp"
android:layout_marginTop="10dp"
android:textStyle="bold"/>
</LinearLayout>
DataModel.java
RecyclerViewAdapter.java
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View listItem= layoutInflater.inflate(R.layout.list_items,
parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final DataModel current=data.get(position);
holder.txtTitle.setText("Title: "+current.getTitle());
holder.txtCategory.setText("Category: "+current.getCategory());
holder.txtDescription.setText("Description: "+
current.getDescription());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(context,Description.class);
intent.putExtra("id",current.getId());
intent.putExtra("title",current.getTitle());
intent.putExtra("category",current.getCategory());
intent.putExtra("description",current.getDescription());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return data.size();
}
ViewData.java
txtTitle=findViewById(R.id.txtTitle);
txtCategory=findViewById(R.id.txtCategory);
txtDescription=findViewById(R.id.txtDescription);
btnModify=findViewById(R.id.btnModify);
if(isLogin)
btnModify.setVisibility(View.VISIBLE);
Intent intent=getIntent();
id=intent.getIntExtra("id",0);
title=intent.getStringExtra("title");
category=intent.getStringExtra("category");
description=intent.getStringExtra("description");
txtTitle.setText("Title:\n"+title);
txtCategory.setText("Category: "+category);
txtDescription.setText("Description:\n"+description);
btnModify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(Description.this,
ModifyJokesStories.class);
intent.putExtra("id",id);
intent.putExtra("title",title);
intent.putExtra("category",category);
intent.putExtra("description",description);
startActivity(intent);
finish();
}
});
}
}
Admin Panel
login.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:layout_margin="10dp"
android:textSize="20sp"
android:id="@+id/edtPassword"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_margin="10dp"
android:textSize="20sp"
android:id="@+id/btnLogin" />
</LinearLayout>
Login.java
edtUsername=findViewById(R.id.edtUsername);
edtPassword=findViewById(R.id.edtPassword);
btnLogin=findViewById(R.id.btnLogin);
cd=new ConnectionDetector(this);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isInternetPresent=cd.isConnectingToInternet();
if(isInternetPresent)
CheckLogin();
else
Toast.makeText(Login.this,"Internet Connection
Required !",Toast.LENGTH_LONG).show();
}
});
}
};;
queue.add(stringRequest);
}
}
admin_panel.xml
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Jokes/Story"
android:textSize="20sp"
android:layout_margin="10dp"
android:textAllCaps="false"
android:id="@+id/btnCreate" />
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/recyclerview"
android:layout_height="match_parent"/>
</LinearLayout>
AdminPanel.java
recyclerView=findViewById(R.id.recyclerview);
btnCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(AdminPanel.this,
AddJokesStories.class);
startActivity(intent);
}
});
@Override
public void onErrorResponse(VolleyError error) {
//displaying error response message
Toast.makeText(AdminPanel.this,error.toString(),
Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
@Override
protected void onResume(){
super.onResume();
loadData();
}
Adding Jokes/Stories
add_jokes_stories.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Title"
android:id="@+id/edtTitle"
android:textSize="18sp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:id="@+id/spCategory"
android:entries="@array/category" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Description"
android:textSize="18sp"
android:layout_margin="10dp"
android:lines="5"
android:id="@+id/edtDescription"
android:gravity="start" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Submit"
android:id="@+id/btnSubmit" />
</LinearLayout>
AddJokesStories.java
edtTitle=findViewById(R.id.edtTitle);
edtDescription=findViewById(R.id.edtDescription);
spCategory=findViewById(R.id.spCategory);
btnSubmit=findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title=edtTitle.getText().toString();
String category=spCategory.getSelectedItem().toString();
String description=edtDescription.getText().toString();
if(title.equals(""))
Toast.makeText(AddJokesStories.this,"Please Enter
Title !",Toast.LENGTH_LONG).show();
else if(category.equals("Select Category"))
Toast.makeText(AddJokesStories.this,"Please Select
Category !",Toast.LENGTH_LONG).show();
else if(description.equals(""))
Toast.makeText(AddJokesStories.this,"Please Enter
Description !",Toast.LENGTH_LONG).show();
else
submitData(title,category,description);
}
});
}
Modifying Jokes/Stories
modify_jokes_stories.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Title"
android:id="@+id/edtTitle"
android:textSize="18sp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:id="@+id/spCategory"
android:entries="@array/category" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Description"
android:textSize="18sp"
android:layout_margin="10dp"
android:lines="5"
android:id="@+id/edtDescription"
android:gravity="start" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Update Data"
android:id="@+id/btnUpdate" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Delete Data"
android:id="@+id/btnDelete" />
</LinearLayout>
ModifyJokesStories.java
edtTitle=findViewById(R.id.edtTitle);
edtDescription=findViewById(R.id.edtDescription);
spCategory=findViewById(R.id.spCategory);
btnUpdate=findViewById(R.id.btnUpdate);
btnDelete=findViewById(R.id.btnDelete);
Intent intent=getIntent();
id=intent.getIntExtra("id",0);
title=intent.getStringExtra("title");
category=intent.getStringExtra("category");
description=intent.getStringExtra("description");
edtTitle.setText(title);
if(category.equals("Jokes"))
spCategory.setSelection(1);
else
spCategory.setSelection(2);
edtDescription.setText(description);
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
title=edtTitle.getText().toString();
category=spCategory.getSelectedItem().toString();
description=edtDescription.getText().toString();
url="http://10.0.2.2/myproject/updatedata.php";
if(title.equals(""))
Toast.makeText(ModifyJokesStories.this,"Please Enter
Title !",Toast.LENGTH_LONG).show();
else if(category.equals("Select Category"))
Toast.makeText(ModifyJokesStories.this,"Please Select
Category !",Toast.LENGTH_LONG).show();
else if(description.equals(""))
Toast.makeText(ModifyJokesStories.this,"Please Enter
Description !",Toast.LENGTH_LONG).show();
else
submitData();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
url="http://10.0.2.2/myproject/deletedata.php";
submitData();
}
});
Manifest File
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.raazu.jokesstories">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name=
"android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
</application>
</manifest>
build.gradle
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.android.support:recyclerview-v7:26.1.0'
}
Lab Sheet Questions (Sample)
Following are the list of some topics on which student’s can create their project on: