0% found this document useful (0 votes)
8 views43 pages

MCAD

The document provides an overview of mobile application development with a focus on Android, detailing the Android operating system, development environment setup, and the creation and management of Android Virtual Devices (AVDs). It also covers essential components of Android applications, including activities, fragments, services, broadcast receivers, content providers, intents, layouts, resources, and the AndroidManifest.xml file. Additionally, it discusses the activity lifecycle and various layout types used in Android development, along with their attributes.

Uploaded by

Aditi Parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views43 pages

MCAD

The document provides an overview of mobile application development with a focus on Android, detailing the Android operating system, development environment setup, and the creation and management of Android Virtual Devices (AVDs). It also covers essential components of Android applications, including activities, fragments, services, broadcast receivers, content providers, intents, layouts, resources, and the AndroidManifest.xml file. Additionally, it discusses the activity lifecycle and various layout types used in Android development, along with their attributes.

Uploaded by

Aditi Parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Mobile Application Development Course Code: 4350703

Unit – I
Basics of Android Development
What is Android?
Android is an open source and Linux-based Operating System for mobile devices
such as smartphones and tablet computers. Android was developed by the Open
Handset Alliance, led by Google, and other companies.
Android offers a unified approach to application development for mobile devices
which means developers need only develop for Android, and their applications
should be able to run on different devices powered by Android.
Android development environment:
Step 1: Install Android Studio
Download Android Studio from the website: https://developer.android.com/studio
Run the downloaded installer and follow the installation wizard instructions.
During the installation, select the components that we want to install, such as the
Android SDK, emulator, and development tools.
Step 2: Launch Android Studio
After the installation is complete, launch Android Studio.
Step 3: Configure SDK and AVD Manager
On the Android Studio Welcome screen, click on "Configure" in the bottom-right
corner and select "SDK Manager."
The SDK Manager allows us to install SDK components, platform versions, and
system images for different device configurations.
Step 4: Install SDK Platforms and System Images
In the SDK Platforms tab, install the Android versions (API levels) that we want to
target in our app. For example, Android 11 (API 30).
In the SDK Tools tab, install the "Android Emulator" and "Intel x86 Emulator
Accelerator (HAXM Installer)" if system supports hardware acceleration (Intel-
based CPUs).
Step 5: Create an AVD (Android Virtual Device)
After installing the necessary SDK components, click on "AVD Manager" on the
Android Studio toolbar (the green Android icon with a phone).
In the AVD Manager, click on "Create Virtual Device."
Choose the device type we want to emulate (e.g., Pixel 4) and click "Next."
Select a system image for the virtual device (e.g., Android 11, x86 or x86_64) and
click "Next."

VPMP Polytechnic, Computer Department. 7


Mobile Application Development Course Code: 4350703

Configure the AVD properties (e.g., device orientation, scale, RAM, and storage)
and click "Finish" to create the AVD.
Step 6: Run the AVD
Back in the AVD Manager, click the green "Play" button next to the AVD we
created to start the virtual device.
The AVD will start up, and the Android system running on the virtual device.
Step 7: Use AVD for Testing
In Android Studio, open Android project.
On the toolbar, select AVD from the device drop-down menu (next to the "Play"
button).
Click the "Run" button (green triangle) to run app on the selected AVD.

• Configure an AVD:
We can easily manage AVDs by creating new ones or editing existing ones through
the AVD Manager in Android Studio. This way, we can test our app on various
virtual devices with different screen sizes, resolutions, and Android versions.
Create and manage virtual devices
An Android Virtual Device (AVD) is a configuration that defines the characteristics
of an Android phone, tablet, Wear OS, Android TV, or Automotive OS device that
we want to simulate in the Android Emulator. The Device Manager is tools you can
launch from Android Studio that helps you create and manage AVDs.
To open the new Device Manager, do one of the following:
• From the Android Studio Welcome screen, select More Actions > Virtual
Device Manager.

VPMP Polytechnic, Computer Department. 8


Mobile Application Development Course Code: 4350703

• After opening a project, select View > Tool Windows > Device
Manager from the main menu bar, and then click Create device.

About AVDs
An AVD contains a hardware profile, system image, storage area, skin, and other
properties.
Hardware profile
The hardware profile defines the characteristics of a device as shipped from the
factory. The Device Manager comes pre-loaded with certain hardware profiles, such
as Pixel devices, and we can define or customize the hardware profiles as needed.

A device definition labeled with the Google Play logo in the Play Store column
includes both the Google Play Store app and access to Google Play services,
including a Google Play tab in the Extended controls dialog that provides a
convenient button for updating Google Play services on the device.
Devices with this logo and a device type of "Phone" are also CTS compliant and
might use system images that include the Play Store app.

VPMP Polytechnic, Computer Department. 9


Mobile Application Development Course Code: 4350703

System images
A system image labeled with Google APIs includes access to Google Play services.

The Recommended tab lists recommended system images. The other tabs include a
more complete list. The right pane describes the selected system image.
Storage area
The AVD has a dedicated storage area on development machine. It stores the device
user data, such as installed apps and settings, as well as an emulated SD card. If
needed, we can use the Device Manager to wipe user data so the device has the same
data as if it were new.
Skin
An emulator skin specifies the appearance of a device. The Device Manager
provides some predefined skins.
Create an AVD
To create a new AVD:
1. Open the Device Manager.
2. Click Create Device.
The Select Hardware window appears.

VPMP Polytechnic, Computer Department. 10


Mobile Application Development Course Code: 4350703

Only some hardware profiles include Play Store. These profiles are
fully CTS compliant and might use system images that include the Play Store app.
3. Select a hardware profile, then click Next.
The System Image window appears.

4. Select the system image for a particular API level, and then click Next.
The Verify Configuration window appears.

5. Change the AVD properties as needed, and then click Finish.


Click Show Advanced Settings to show more settings, such as the skin.
The new AVD appears in the Virtual tab of the Device Manager and the target
device menu.
To create an AVD starting with a copy:
1. From the Virtual tab of the Device Manager, click Menu and
select Duplicate.
The Verify Configuration window appears.

VPMP Polytechnic, Computer Department. 11


Mobile Application Development Course Code: 4350703

2. Click Previous if need to make changes on the System Image or Select


Hardware windows.
3. Make any changes you need, and then click Finish.
The AVD appears in the Virtual tab of the Device Manager.
Create a hardware profile
The Device Manager provides predefined hardware profiles for common devices so
you can easily add them to your AVD definitions. If you need to define a different
device, you can create a new hardware profile.
You can define a new hardware profile from the beginning or copy a hardware
profile as a starting point. The preloaded hardware profiles aren't editable.
To create a new hardware profile from the beginning:
1. In the Select Hardware window, click New Hardware Profile.
2. In the Configure Hardware Profile window, change the hardware profile
properties as needed.

3. Click Finish.
New hardware profile appears in the Select Hardware window. You can create an
AVD that uses the hardware profile by clicking Next or click Cancel to return to
the Virtual tab or target device menu.
To create a hardware profile using a copy as a starting point:
1. In the Select Hardware window, select a hardware profile and click Clone
Device or right-click a hardware profile and select Clone.
2. In the Configure Hardware Profile window, change the hardware profile
properties as needed.
3. Click Finish.

VPMP Polytechnic, Computer Department. 12


Mobile Application Development Course Code: 4350703

New hardware profile appears in the Select Hardware window. Create an AVD that
uses the hardware profile by clicking Next or click Cancel to return to
the Virtual tab or target device menu.
Edit existing AVDs
You can perform the following operations on an AVD from the Device
Manager's Virtual tab:

• To edit an AVD, click Edit this AVD and make your changes.
• To delete an AVD, click Menu and select Delete.
• To show the associated AVD INI and IMG files on disk, click Menu and
select Show on Disk.
• To view AVD configuration details that you can include in bug reports to the
Android Studio team, click Menu and select View Details.
Edit existing hardware profiles
We can't edit or delete the preloaded hardware profiles, but can perform the
following operations on other hardware profiles from the Select Hardware window:
• To edit a hardware profile, select it and click Edit Device. We can also right-
click a hardware profile and select Edit. Next, make your changes.
• To delete a hardware profile, right-click it and select Delete.
Run and stop an emulator and clear data
From the Virtual tab, we can perform the following operations on an emulator:

• To run an emulator that uses an AVD, click Launch .


• To stop a running emulator, click Menu and select Stop.
• To clear the data for an emulator, click Menu and select Wipe Data.

Various Components available in Android Application:


Android applications are built using various components that interact with each
other to provide the desired functionality and user experience.

Activities: An activity represents a single screen with a user interface. It is the most
fundamental component of an Android app and is responsible for interacting with
the user. An application may consist of one or multiple activities. Each activity
extends the Activity class and typically corresponds to a specific user interaction.

Fragments: Fragments are modular sections of an activity that can be combined and
reused across multiple activities. They are useful for creating responsive user

VPMP Polytechnic, Computer Department. 13


Mobile Application Development Course Code: 4350703

interfaces, especially on devices with varying screen sizes. Fragments extend the
Fragment class and are managed by activities.

Services: A service is a component that runs in the background, independent of any


user interface. It performs long-running operations or handles tasks that should
continue to execute even when app is not in the foreground. Services can be used to
play music, download data, or handle network transactions.

Broadcast Receivers: A broadcast receiver is a component that listens for and


responds to system-wide broadcasts. These broadcasts can be sent by the Android
system or other apps. Broadcast receivers allow your app to respond to events, such
as incoming SMS messages, network connectivity changes, or battery status updates.

Content Providers: A content provider allows the app to share data with other apps
securely. It acts as an interface to access and manage the app's data, which can be
stored in a database, file, or any other data source. Content providers enable inter-
app data sharing, allowing other apps to read or modify the data based on defined
permissions.

Intents: Intents are messaging objects used to communicate between components


within an app or between different apps. They facilitate starting activities, services,
or broadcasting events. Intents can carry data along with them to pass information
between components.

Layouts: Android uses XML-based layout files to define the user interface of an
activity or fragment. These layout files specify how different UI elements are
arranged and displayed on the screen.

Resources: Android apps use resources such as strings, colors, styles, and images.
These resources are kept separately from the code, allowing for easy localization and
management.

Manifest File: The AndroidManifest.xml file contains important information about


the app, such as the app's package name, components, permissions required, and
hardware features used. It acts as a configuration file for the app.

Gradle Build System: Gradle is used to manage the build process of an Android
app. It defines dependencies, compiles code, and packages the app for distribution.

VPMP Polytechnic, Computer Department. 14


Mobile Application Development Course Code: 4350703

Android: Activity Life Cycle

Activity is a window that contains the user interface of your application. As there
are various states of activity like Running, Paused, Stopped and Killed.
Activity base class contains events that govern the life cycle of an activity.
onCreate(): Called when the activity is first created
onStart(): Called when the activity becomes visible to the user
onResume(): Called when the activity starts interacting with the user
onPause(): Called when the current activity is being paused and the previous
activity is being resumed
onStop(): Called when the activity is no longer visible to the user
onDestroy(): Called before the activity is destroyed by the system
onRestart(): Called when the activity has been stopped and is restarting again

VPMP Polytechnic, Computer Department. 15


Mobile Application Development Course Code: 4350703

Unit – II
Modeling GUI Using Android
Android Layout Types
There are number of Layouts provided by Android which you will use in almost all
the Android applications to provide different view, look and feel.

Types of Android Layout

• Android Linear Layout:

LinearLayout is a ViewGroup subclass, used to provide child View elements


one by one either in a particular direction either horizontally or vertically
based on the orientation property.

• Android Relative Layout:

RelativeLayout is a ViewGroup subclass, used to specify the position of child


View elements relative to each other like (A to the right of B) or relative to the
parent (fix to the top of the parent).

• Android Constraint Layout:

ConstraintLayout is a ViewGroup subclass, used to specify the position of


layout constraints for every child View relative to other views present. A
ConstraintLayout is similar to a RelativeLayout, but having more power.
ConstraintLayout provides you the ability to completely design your UI with
the drag and drop feature provided by the Android Studio design editor.It
helps to improve the UI performance over other layouts.With the help of
ConstraintLayout, we can control the group of widgets through a single line of
code.With the help of ConstraintLayout, we can easily add animations to the
UI components which we used in our app.

• Android Frame Layout:

FrameLayout is a ViewGroup subclass, used to specify the position of View


elements it contains on the top of each other to display only a single View
inside the FrameLayout.

• Android Table Layout:

VPMP Polytechnic, Computer Department. 7


Mobile Application Development Course Code: 4350703

TableLayout is a ViewGroup subclass, used to display the child View


elements in rows and columns.

• Android Web View:

WebView is a browser that is used to display the web pages in our activity
layout.

• Android ListView:

ListView is a ViewGroup, used to display scrollable lists of items in a single


column.

• Android Grid View:

GridView is a ViewGroup that is used to display a scrollable list of items in a


grid view of rows and columns.

Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout.
There are few common attributes among all the layouts and there are other attributes
which are specific to that layout. Following are common attributes and will be
applied to all the layouts:

Attribute Description
android:id This is the ID which uniquely identifies the view.
android:layout_width This is the width of the layout.
android:layout_height This is the height of the layout
This is the extra space on the top side of the
android:layout_marginTop
layout.
This is the extra space on the bottom side of the
android:layout_marginBottom
layout.
This is the extra space on the left side of the
android:layout_marginLeft
layout.
This is the extra space on the right side of the
android:layout_marginRight
layout.
android:layout_gravity This specifies how child Views are positioned.

VPMP Polytechnic, Computer Department. 8


Mobile Application Development Course Code: 4350703

This specifies how much of the extra space in the


android:layout_weight
layout should be allocated to the View.
android:layout_x This specifies the x-coordinate of the layout.
android:layout_y This specifies the y-coordinate of the layout.
android:layout_width This is the width of the layout.
android:layout_width This is the width of the layout.
android:paddingLeft This is the left padding filled for the layout.
android:paddingRight This is the right padding filled for the layout.
android:paddingTop This is the top padding filled for the layout.
android:paddingBottom This is the bottom padding filled for the layout.

For example, a simple vertical linear layout with a text view and a button looks like
this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"

android:orientation="vertical" >
<TextView android:id="@+id/text"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>

Android UI Controls
We have a different type of UI controls available in android to implement the user
interface for our android applications.

VPMP Polytechnic, Computer Department. 9


Mobile Application Development Course Code: 4350703

Control Description Related Classes


Type

Button A push-button that can be pressed, or Button


clicked, by the user to perform an
action.

Text field An editable text field. You can use EditText,AutoCompleteText


theAutoCompleteTextView widget to View
create a text entry widget that
provides auto-complete suggestions

Checkbox An on/off switch that can be toggled CheckBox


by the user. You should use
checkboxes when presenting users
with a group of selectable options that
are not mutually exclusive.

Radio Similar to checkboxes, except that RadioGroup


button only one option can be selected in the RadioButton
group.

Toggle An on/off button with a light ToggleButton


button indicator.

Spinner A drop-down list that allows users to Spinner


select one value from a set.

Pickers A dialog for users to select a single DatePicker,TimePicker


value for a set by using up/down
buttons or via a swipe gesture. Use
aDatePickercode> widget to enter the
values for the date (month, day, year)
or a TimePicker widget to enter the
values for a time (hour, minute,
AM/PM), which will be formatted
automatically for the user's locale.

Android ProgressBar:
In android, ProgressBar is a user interface control which is used to indicate the
progress of an operation. For example, downloading a file, uploading a file.

VPMP Polytechnic, Computer Department. 10


Mobile Application Development Course Code: 4350703

By default the ProgressBar will be displayed as a spinning wheel, in case if we want


to show it like a horizontal bar then we need to change the style property to
horizontal like style="?android:attr/progressBarStyleHorizontal".
Example:

Create Android ProgressBar in XML Layout File

In android, we can create ProgressBar in XML layout file using <ProgressBar>


element with different attributes like as shown below

<ProgressBar
android:id="@+id/pBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:minWidth="200dp"
android:max="100"
android:indeterminate="true"
android:progress="1" />

we defined a progress bar (<ProgressBar>) with different attributes.

XML Attributes of ProgressBar:

Attribute Description

android:id It is used to uniquely identify the control

android:minHeight It is used to set the height of the progress bar.

android:minWidth It is used to set the width of the progress bar.

android:max It is used to set the maximum value of the progress bar.

android:progress It is used to set default progress value between 0 and max.

ImageView:
ImageView class is used to display any kind of image resource in the android
application.

VPMP Polytechnic, Computer Department. 11


Mobile Application Development Course Code: 4350703

XML Attributes of ImageView:

Attribute Description

android:id To uniquely identify an image view

android:src/app:srcCompat To add the file path of the inserted image

android:background To provide a background color to the inserted image

android:layout_width To set the width of the image

android:layout_height To set the height of the image

To add padding to the image from the left, right, top, or


android:padding
bottom of the view

android:scaleType To re-size the image or to move it in order to fix its size


Example:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/image" />

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>

VPMP Polytechnic, Computer Department. 12


Mobile Application Development Course Code: 4350703

Unit– III
Event Handling in Android Application
Android - 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. We can capture these events in our
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.
• 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.
Event Listeners & Event Handlers:

Event Handler Event Listener & Description

OnClickListener()
This is called when the user either clicks or touches or
onClick()
focuses upon any widget like button, text, image etc. You
will use onClick() event handler to handle such event.

OnLongClickListener()
This is called when the user either clicks or touches or
onLongClick()
focuses upon any widget like button, text, image etc. for
one or more seconds. You will use onLongClick() event

VPMP Polytechnic, Computer Department. 7


Mobile Application Development Course Code: 4350703

handler to handle such event.

OnFocusChangeListener()
This is called when the widget looses its focus ie. user
onFocusChange()
goes away from the view item. You will use
onFocusChange() event handler to handle such event.

OnFocusChangeListener()
This is called when the user is focused on the item and
onKey()
presses or releases a hardware key on the device. You will
use onKey() event handler to handle such event.

OnTouchListener()
This is called when the user presses the key, releases the
onTouch()
key, or any movement gesture on the screen. You will use
onTouch() event handler to handle such event.

OnMenuItemClickListener()
This is called when the user selects a menu item. You will
onMenuItemClick()
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)

Event Handling Examples:


Event Listeners Registration Using an Anonymous Inner Class
Here you will create an anonymous implementation of the listener and will be
useful if each class is applied to a single control only and you have advantage to
pass arguments to event handler. In this approach event handler methods can
access private data of Activity. No reference is needed to call to Activity.
But if you applied the handler to more than one control, you would have to cut and
paste the code for the handler and if the code for the handler is long, it makes the
code harder to maintain.

VPMP Polytechnic, Computer Department. 8


Mobile Application Development Course Code: 4350703

Following are the simple steps to show how we will make use of separate Listener
class to register and capture click event. Similar way you can implement your
listener for any other required event type.

Step Description

1 Use Android studio IDE to create an Android application

2 Modify src/MainActivity.java file to add click event listeners and


handlers for the two buttons defined.

3 Modify the detault content of res/layout/activity_main.xml file to


include Android UI controls.

4 No need to declare default string constants.Android studio takes care


default constants.

5 Run the application to launch Android emulator and verify the result
of the changes done in the aplication.

Navigating between Activities using Intent:

Intents could be Implicit, for instance, calling intended actions, and explicit as
well, such as opening another activity after some operations like onClick or
anything else. Below are some applications of Intents:
1. Sending the User to Another App
2. Getting a Result from an Activity
3. Allowing Other Apps to Start Your Activity
Some Important Method of Intent and their Description

Methods Description

This is to launch a new activity or get an existing


Context.startActivity()
activity to be action.

Context.startService() This is to start a new service or deliver instructions

VPMP Polytechnic, Computer Department. 9


Mobile Application Development Course Code: 4350703

Methods Description

for an existing service.

Context.sendBroadcast() This is to deliver the message to broadcast receivers.

Types of Android Intents:


There are two types of intents in android
1. Implicit
2. Explicit

Implicit Intent
Implicit Intent doesn’t specify the component. In such a case, intent provides
information on available components provided by the system that is to be invoked.
For example, you may write the following code to view the webpage.
Syntax:
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.geeksforgeeks.org/"));
startActivity(intent);
For Example: a webpage is going to be opened. As you type the name of your
desired webpage and click on the ‘CLICK’ button. Your webpage is opened.

Explicit Intent
Explicit Intent specifies the component. In such a case, intent provides the external
class to be invoked.
Syntax:
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);

VPMP Polytechnic, Computer Department. 10


Mobile Application Development Course Code: 4350703

For Example: In the given example, there are two activities (FirstActivity, and
SecondActivity). When you click on the ‘GO TO OTHER ACTIVITY’ Button in
the FirstActivity, then you move to the SecondActivity. When you click on the
‘GO TO HOME ACTIVITY’ button in the SecondActivity, then you move to the
first activity. This is getting done through Explicit Intent.

VPMP Polytechnic, Computer Department. 11


Mobile Application Development Course Code: 4350703

Android Listview in Java

Android ListView is a ViewGroup that is used to display the list of items in


multiple rows and contains an adapter that automatically inserts the items into the
list.

XML Attributes of ListView

Attribute Description

A color or drawable to separate list


android:divider
items.

android:dividerHeight Divider’s height.

Reference to an array resource that


android:entries
will populate the ListView.

When set to false, the ListView will


android:footerDividersEnabled not draw the divider before each
footer view.

When set to false, the ListView will


android:headerDividersEnabled not draw the divider before each
header view.

❖ How to add a ListView in an Android App


Step 1: Create a new project

1. Click on File, then New => New Project.

2. Choose “Empty Activity” for the project template.

3. Select language as Java.

4. Select the minimum SDK as per your need.

Step 2: Modify activity_main.xml file

Add a ListView in the activity_main.xml file.

VPMP Polytechnic, Computer Department. 12


Mobile Application Development Course Code: 4350703

Example: activity_main.xml
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

Step 3: Modify MainActivity.java file

➢ Go to MainActivity.java.

➢ Now in the java file create a string array and store the values you want to
display in the list.

➢ Also, create an object of ListView class.

➢ In onCreate() method find Listview by id using findViewById() method.

➢ Create an object of ArrayAdapter using a new keyword followed by a


constructor call.

Example: MainActivity.java
public class MainActivity extends Activity
{
ListView l;
String tutorials[]={ "Algorithms", "Data Structures",
"Languages", "Interview Corner"};

@Override
protected void onCreate(Bundle savedInstanceState)
{
l = findViewById(R.id.list);
ArrayAdapter<String> arr;
arr = new ArrayAdapter<String>(this,
R.layout.support_simple_spinner_dropdown_item,
tutorials);
l.setAdapter(arr);
}
}

Spinner in Android

➢ Android Spinner is a view similar to the dropdown list which is used to


select one option from the list of options.

VPMP Polytechnic, Computer Department. 13


Mobile Application Development Course Code: 4350703

➢ It provides an easy way to select one item from the list of items and it shows
a dropdown list of all values when we click on it.

➢ The default value of the android spinner will be the currently selected value
and by using Adapter we can easily bind the items to the spinner objects.

Different Attributes for Spinner Widget

Attribute Description

android:id Used to specify the id of the view.

Used to the text alignment in the


android:textAlignment
dropdown list.

Used to set the background of the


android:background
view.

android:padding Used to set the padding of the view.

android:visibility Used to set the visibility of the view.

Used to specify the gravity of the view


android:gravity
like center, top, bottom, etc

❖ Example to demonstrate the Spinner


Below is the example in which we display a list of bank names in a spinner and
whenever you select an item the value will be displayed using toast on Mobile
screen. Below is the final output and code:

Step 1: Create a new project in Android Studio and name it SpinnerExample.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following
code. Here we will create a Spinner inside Relative Layout.

activity_main.xml:
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />

VPMP Polytechnic, Computer Department. 14


Mobile Application Development Course Code: 4350703

Step 3: Now open app-> java -> package -> MainActivity.java and add the
following code. Here we will use ArrayAdapter to fill the data in Spinner. Also we
are using Toast to display when the item in Spinner is selected.
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener
{

String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};

protected void onCreate(Bundle savedInstanceState)


{
//Getting the instance of Spinner and applying OnItemSelectedListener
on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the bank name list


ArrayAdapter aa = new
ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);

aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_it
em);

//Setting the ArrayAdapter data on the Spinner


spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
public void onItemSelected(AdapterView<?> arg0, View arg1, int
position,long id)
{
Toast.makeText(getApplicationContext(), bankNames[position],
Toast.LENGTH_LONG).show();
}
}

VPMP Polytechnic, Computer Department. 15


Mobile Application Development Course Code: 4350703

❖ How to Request Permissions in Android Application?


➢ Starting from Android 6.0 (API 23), users are not asked for permissions at
the time of installation rather developers need to request the permissions at
the run time. Only the permissions that are defined in the manifest file can
be requested at run time.

Types of Permissions
➢ Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the
permission is requested at the installation time at the Google Play Store.

➢ If the user Accepts the permissions, the app is installed. Else the
app installation is canceled.

➢ Run-Time Permissions: If the Android 6 (API 23) or higher, the


permission is requested at the run time during the running of the app.

VPMP Polytechnic, Computer Department. 16


Mobile Application Development Course Code: 4350703

➢ If the user accepts the permissions, then that feature of the app can be used.
Else to use the feature, the app requests permission again.

➢ So, now the permissions are requested at runtime.

➢ In this article, we will discuss how to request permissions in an Android


Application at run time.

Steps for Requesting permissions at run time


Step 1: Declare the permission in the Android Manifest file: In Android,
permissions are declared in the AndroidManifest.xml file using the uses-
permission tag.

<uses-permission android:name=”android.permission.PERMISSION_NAME”/>

➢ Here we are declaring storage and camera permission.

activity_main.xml:
<!--Declaring the required permissions-->
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Step 2: Modify activity_main.xml file to Add two buttons to request


permission on button click: Permission will be checked and requested on button
click. Open the activity_main.xml file and add two buttons to it.
<!--Button to request storage permission-->
<Button
android:id="@+id/storage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Storage"
android:layout_marginTop="16dp"
android:padding="8dp"
android:layout_below="@id/toolbar"
android:layout_centerHorizontal="true"/>

<!--Button to request camera permission-->


<Button
android:id="@+id/camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Camera"

VPMP Polytechnic, Computer Department. 17


Mobile Application Development Course Code: 4350703

android:layout_marginTop="16dp"
android:padding="8dp"
android:layout_below="@id/storage"
android:layout_centerHorizontal="true"/>

Step 3: Check whether permission is already granted or not. If permission


isn’t already granted, request the user for the permission: In order to use
any service or feature, the permissions are required. Hence we have to ensure
that the permissions are given for that. If not, then the permissions are
requested.

Check for permissions: Beginning with Android 6.0 (API level 23), the user
has the right to revoke permissions from any app at any time, even if the app
targets a lower API level. So to use the service, the app needs to check for
permissions every time.

Syntax:

if(ContextCompat. checkSelfPermission (thisActivity,


Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED)
{
// Permission is not granted
}

Request Permissions: When PERMISSION_DENIED is returned from


the checkSelfPermission() method in the above syntax, we need to prompt the
user for that permission.

➢ Android provides several methods that can be used to request permission,


such as requestPermissions().

Syntax:

ActivityCompat.requestPermissions (MainActivity.this,
permissionArray,
requestCode);

➢ Here permissionArray is an array of type String.

Java File:
// Function to check and request permission
public void checkPermission(String permission, int requestCode)
{

VPMP Polytechnic, Computer Department. 18


Mobile Application Development Course Code: 4350703

// Checking if permission is not granted

if (ContextCompat.checkSelfPermission(MainActivity.this,
permission) == PackageManager.PERMISSION_DENIED)
{
ActivityCompat.requestPermissions(MainActivity.this, new String[] {
permission }, requestCode);
}
else
{
Toast.makeText(MainActivity.this, "Permission already
granted", Toast.LENGTH_SHORT).show();
}
}

➢ This function will show a Toast message if permission is already granted


otherwise prompt the user for permission.

❖ How to add Toggle Button in an Android


➢ ToggleButton is basically a stop / play or on/off button with indicator light
indicating the current state of ToggleButton.

➢ ToggleButton is widely used, some examples are on/off audio, Bluetooth,


WiFi, hot-spot etc.

➢ This is a subclass of Composite Button.

➢ ToggleButton allows users to change settings between two states from your
phone’s Settings menu such as turning your WiFi, Bluetooth, etc. on / off.

activity_main.xml:

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="onToggleClick" />
Java File:
public class MainActivity extends Activity
{

ToggleButton togglebutton;
TextView textview;

VPMP Polytechnic, Computer Department. 19


Mobile Application Development Course Code: 4350703

@Override
protected void onCreate(Bundle savedInstanceState)
{
togglebutton = (ToggleButton)findViewById(R.id.toggleButton);
textview = (TextView)findViewById(R.id.textView);
}

public void onToggleClick(View view)


{
if (togglebutton.isChecked())
{
textview.setText("Toggle is ON");
}
else
{
textview.setText("Toggle is OFF");
}
}
}

VPMP Polytechnic, Computer Department. 20


Mobile Application Development Course Code: 4350703

Unit– IV
Dialog, Menu and Database with RecyclerView
And CardView

❖ Menu in Android
➢ There are 3 types of menus in Android:

• Option Menu

• Context Menu

• Pop-up Menu

❖ Option Menu

➢ The options menu is the primary collection of menu items for an activity.

➢ It's where you should place actions that have a overall impact on the app,
such as Search, Compose Email and Settings.

VPMP Polytechnic, Computer Department. 7


Mobile Application Development Course Code: 4350703

❖ Context Menu

➢ A context menu is a floating menu that appears when the user performs a
long-click on an element.

➢ It provides actions that affect the selected content or context frame.

❖ PopUp Menu

VPMP Polytechnic, Computer Department. 8


Mobile Application Development Course Code: 4350703

➢ A popup menu displays a list of items in a vertical list that is


anchored(sticked) 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.

❖ How to create a Menu?


➢ For all menu types mentioned above, 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 i.e load the XML files as a Menu
object in your activity.

Menu_example.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/mail"
android:icon="@drawable/ic_mail"
android:title="@string/mail" />

<item android:id="@+id/upload"
android:icon="@drawable/ic_upload"
android:title="@string/upload"
android:showAsAction="ifRoom" />

<item android:id="@+id/share"
android:icon="@drawable/ic_share"
android:title="@string/share" />
</menu>

Attributes Description

android: id It is used to uniquely identify an element in the application.

android:icon It is used to set the item's icon from drawable folder.

android: title It is used to set the item's title

VPMP Polytechnic, Computer Department. 9


Mobile Application Development Course Code: 4350703

❖ Load Android Menu from an Activity


public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_example, menu);
}
➢ If you observe above code we are calling our menu using
MenuInflater.inflate() method in the form of R.menu.menu_file_name.

➢ Here our xml file name is menu_example.xml so we used file


name menu_example.

❖ Handle Android Menu Click Events


➢ In android, we can handle a menu item click event using
ItemSelected() event based on the menu type.

➢ To handle a context menu item click event, use onContextItemSelected()


method.

❖ How to Create an Alert Dialog Box in Android?


➢ Alert Dialog shows the Alert message and gives the answer in the form of
yes or no. Alert Dialog displays the message to warn you and then according
to your response, the next step is processed. Android Alert Dialog is built
with the use of three fields: Title, Message area, and Action Button.

➢ In order to make an alert dialog, you need to make an object of


AlertDialogBuilder which an inner class of AlertDialog.

➢ Its syntax is given below

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

➢ Now you have to set the positive (yes) or negative (no) button using the
object of the AlertDialogBuilder class.

➢ Its syntax is,


alertDialogBuilder.setPositiveButton(CharSequence text,
DialogInterface.OnClickListener listener);
alertDialogBuilder.setNegativeButton(CharSequence text,
DialogInterface.OnClickListener listener);

VPMP Polytechnic, Computer Department. 10


Mobile Application Development Course Code: 4350703

➢ Alert Dialog code has three methods:


• setTitle() method for displaying the Alert Dialog box Title
• setMessage() method for displaying the message
• setIcon() method is used to set the icon on the Alert dialog box.

❖ How to make custom dialog in android?


➢ The custom dialog uses DIALOG to create custom alert in android studio.

➢ Dialog display a small window i.e a popup which draws the user attention
over the activity before they continue moving forward.

➢ The dialog appears over the current window and display the content defined
in it.

AlertDialog Vs Custom AlertDialog:

➢ The Alert Dialog and Custom Alert Dialog both prompt a small window to
make decision.

➢ The AlertDialog make use of the defined components or methods like


setIcon, setTitle, setmessage etc but with Custom AlertDialog we can have
the dialog customized and can define the layout of dialog as required.

Example:
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
Button dialogButton = (Button)
dialog.findViewById(R.id.dialogButtonOK);

VPMP Polytechnic, Computer Department. 11


Mobile Application Development Course Code: 4350703

// if button is clicked, close the custom dialog


dialogButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
dialog.dismiss();

Toast.makeText(getApplicationContext(),"Dismissed..!!",Toas
t.LENGTH_SHORT).show();
}
});
dialog.show();
}
});

❖ Android - SQLite Database


➢ SQLite is a opensource SQL database that stores data to a text file on a
device. Android comes in with built in SQLite database implementation.

➢ SQLite supports all the relational database features.

➢ In order to access this database, you don't need to establish any kind of
connections for it like JDBC,ODBC etc.

❖ Database - Package
➢ The main package is android.database.sqlite that contains the classes to
manage your own databases

❖ Database - Creation
➢ In order to create a database you just need to call this method
openOrCreateDatabase with your database name and mode as a parameter.

➢ It returns an instance of SQLite database which you have to receive in your


own object.

➢ Its syntax is given below


SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);

VPMP Polytechnic, Computer Department. 12


Mobile Application Development Course Code: 4350703

❖ Database - Insertion
➢ We can create table or insert data into table using execSQL method defined
in SQLiteDatabase class.

➢ Its syntax is given below


mydatabase.execSQL("CREATE TABLE IF NOT EXISTS student(Username
VARCHAR, Password VARCHAR);");
mydatabase.execSQL("INSERT INTO student VALUES('vpmp','654');");

❖ Database - Fetching
➢ We can retrieve anything from database using an object of the Cursor class.

➢ We will call a method of this class called rawQuery and it will return a
resultset with the cursor pointing to the table.

➢ We can move the cursor forward and retrieve the data.


Cursor resultSet = mydatbase.rawQuery("Select * from student",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);

❖ Database - Helper class


➢ For managing all the operations related to the database, a helper class has
been given and is called SQLiteOpenHelper.

➢ It automatically manages the creation and update of the database.

➢ Its syntax is given below


public class DBHelper extends SQLiteOpenHelper
{
public DBHelper()
{
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) { }
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { }
}

VPMP Polytechnic, Computer Department. 13


Mobile Application Development Course Code: 4350703

❖ Android RecyclerView, Android CardView


CardView: CardView is an extended version of Framelayout which can be used to
show items inside the card format.

➢ With the help of CardView, we can add radius and elevation to our items of
RecyclerView. CardView gives a rich look and feels to our list of data.

RecyclerView: RecyclerView is an extended version of ListView.

➢ In RecyclerView we can load a large amount of data and items of


RecyclerView can have a custom design.

➢ RecyclerView works on the ViewHolder design pattern so we have to create


a Data class that holds data for RecyclerView and a ViewHolder class which
will set data to each item of RecyclerView.

➢ RecyclerView is divided into 3 sections:

• Card Layout.
• Modal Class.
• ViewHolder class.

VPMP Polytechnic, Computer Department. 14


Mobile Application Development Course Code: 4350703

Unit– V
Introduction to Android Development using Kotlin
❖ What is Kotlin?
➢ Kotlin is a statically typed, object-oriented programming language that is
interoperable with the Java virtual machine (JVM), Java Class Libraries and
Android.

➢ The Kotlin programming language was originally designed to improve


the Java programming language and is often used in conjunction with Java.

❖ What is Kotlin used for?


Kotlin is a general-purpose development language used mainly for Android mobile
app development. Besides Android apps, Kotlin is also useful for the following:

• Server-side development: Back-end web app development traditionally


uses Java. Kotlin can be used alongside Java for development on the server.
Kotlin supports Java Class Libraries.

• Full-stack web development: Developers use Kotlin for JavaScript to


translate Kotlin lines of code into JavaScript for front-end web development.
This approach lets them use the same code on the front and back ends.

• Multiplatform mobile development: Developers use Kotlin for Android


and other mobile platforms, including Apple iOS, Apple watchOS and
Linux.

• Data science: Kotlin is often used for data science tasks, such as building
data pipelines and putting machine learning models into production.

VPMP Polytechnic, Computer Department. 7


Mobile Application Development Course Code: 4350703

❖ Kotlin Hello World App


➢ To develop android application launch Android Studio and select option
'Start a new Android Studio project'.

➢ Provide an application name ('Hello World') and check 'Include Kotlin


support' and proceed.

VPMP Polytechnic, Computer Department. 8


Mobile Application Development Course Code: 4350703

➢ Select API level for android application and click next.

➢ Select Activity type and click next.

VPMP Polytechnic, Computer Department. 9


Mobile Application Development Course Code: 4350703

activity_main.xml
Create an activity_main.xml file in layout folder and add the following code.

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.and
roid.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.app.javatpoint.helloworld.MainActivity">

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

VPMP Polytechnic, Computer Department. 10


Mobile Application Development Course Code: 4350703

</android.support.constraint.ConstraintLayout>

MainActivity.kt
Create MainActivity.kt file in example.app.javatpoint.helloworld package add the
following code.

package example.app.javatpoint.helloworld

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

class MainActivity : AppCompatActivity()


{

override fun onCreate(savedInstanceState: Bundle?)


{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
➢ Now run your app.

VPMP Polytechnic, Computer Department. 11


Mobile Application Development Course Code: 4350703

Output:

❖ Kotlin Android Toast


➢ Android Toast is used to display a sort time notification to the user without
affecting the user interaction with UI.
➢ The message displayed using Toast class displays quickly, and it disappears
after some time.
➢ The message in the Toast can be of type text, image or both.
➢ The applicationContest returns the instance of Context class.
➢ The message is of String type.
➢ The Toast.LENGTH_SHORT and Toast.LENGTH_LONG are the
constant defines the time duration for message display.
➢ The show() method of Toast class used to display the toast message.
Example:

val myToast = Toast.makeText(applicationContext, "toast message",


Toast.LENGTH_SHORT) ;

myToast.show() ;

VPMP Polytechnic, Computer Department. 12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy