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

Android Development (ESE1)

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

Android Development (ESE1)

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

Android Development

1.What is mean by button? explain different type of buttons available in


Android studio?

 In Android, Button represents a push button.
 A Push buttons can be clicked, or pressed by the user to perform an action.
 There are different types of buttons used in android such as
CompoundButton, ToggleButton, RadioButton, ImageButton.
 Button is a subclass of TextView class and compound button is the subclass of
Button class.
 On a button we can perform different actions or events like click event,
pressed event, touch event etc.
 Android buttons are GUI components which are sensible to taps (clicks) by the
user. When the user taps/clicks on button in an Android app, the app can
respond to the click/tap. These buttons can be divided into two categories: the
first is Buttons with text on, and second is buttons with an image on. A button
with images on can contain both an image and a text. Android buttons with
images on are also called ImageButton.

Button code in XML:


The below code will create Button and write “Submit” text on it.

<Button
android:id="@+id/simpleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abhi Android"/>

Output:-
Submit

Attributes of Button in Android:

<Button
android:id="@+id/simpleButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Abhi Android"
android:layout_centerInParent="true"
android:gravity="right|center_vertical"/><!--set the gravity of button-->

1. id: id is an attribute used to uniquely identify a text Button. above is the


example code in which we set the id of a Button.
2. gravity: The gravity attribute is an optional attribute which is used to control
the alignment of the text like left, right, center, top, bottom, center_vertical,
center_horizontal etc.
3. text: text attribute is used to set the text in a Button. We can set the text
in xml as well as in the java class.
4. textColor: textColor attribute is used to set the text color of a Button. Color
value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
5. textSize: textSize attribute is used to set the size of the text on Button. We can
set the text size in sp(scale independent pixel) or dp(density pixel).
6. textStyle: textStyle attribute is used to set the text style of a Button. The
possible text styles are bold, italic and normal. If we need to use two or more
styles for a Button then “|” operator is used for that.
7. background: background attribute is used to set the background of a Button.
We can set a color or a drawable in the background of a Button.
8. drawableBottom, drawableTop, drawableRight And drawableLeft: we can
draw drawable to the bottom, left, right or top of text

Type of buttons available in Android studio:-


1. ImageButton

 In Android, ImageButton is used to display a normal button with a custom


image in a button. In simple words we can say, ImageButton is a button with
an image that can be pressed or clicked by the users. By default it looks like a
normal button with the standard button background that changes the color
during different button states.
 An image on the surface of a button is defined within a xml (i.e. layout ) by
using src attribute or within java class by using setImageResource() method.
We can also set an image or custom drawable in the background of the image
button.
 ImageButton has all the properties of a normal button so you can easily
perform any event like click or any other event which you can perform on a
normal button

Attributes of ImageButton in Android:

<ImageButton
android:id="@+id/simpleImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/home"/> <!--src(source)file from drawable folder which
display an imagebutton-->
android:background="#000"/><!-- black background color for image button-->
android:padding="30dp"/><!-- set 30dp padding from all the sides of the view->

1. id: id is an attribute used to uniquely identify a image button


2. src: src is an attribute used to set a source file of image or you can say
image in your image button to make your layout look attractive.
3. background: background attribute is used to set the background of an
image button. We can set a color or a drawable in the background of a
Button.
4. padding: padding attribute is used to set the padding from left, right, top
or bottom of the ImageButton.
Setting Image Source In ImageButton Using Java class:
We can also set the source image at run time programmatically in java class. For that
we use setImageResource() function as shown in below example code.

/*Add in Oncreate() funtion after setContentView()*/


ImageButton simpleImageButton = (ImageButton)findViewById(R.id.simpleImageButton);
simpleImageButton.setImageResource(R.drawable.home); //set the image programmatica
lly

2. ToggelButton:-

 In Android, ToggleButton is used to display checked and unchecked state of


a button. ToggleButton basically an off/on button with a light indicator
which indicate the current state of toggle button. The most simple example
of ToggleButton is doing on/off in sound, Bluetooth, wifi, hotspot etc. It is a
subclass of compoundButton.
 ToggleButton are the subclasses of CompoundButton class.

How To Check Current State Of ToggleButton:


 To check current state of a toggle button programmatically we use isChecked()
method. This method returns a Boolean value either true or false. If a toggle
button is checked then it returns true otherwise it returns false. Below
is the code which checks the current state of a toggle button.

/*Add in Oncreate() funtion after setContentView()*/


ToggleButton simpleToggleButton = (ToggleButton) findViewById(R.id.simpleToggleBut
ton); // initiate a toggle button
Boolean ToggleButtonState = simpleToggleButton.isChecked(); // check current state
of a toggle button (true or false)

Attributes of ToggleButton:

<ToggleButton

android:id="@+id/simpleToggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true" /><!-- set the current state of the toggle button-->
android:gravity="right|center_vertical"/><!-- gravity of the toggle button-->
android:textOff="Disable"
android:textOn="Enable"/> <!--text to be displayed whenever toggle button is c
hecked-->
android:textColor="#f00" /><!--red color for displayed text-->
android:textSize="25sp"/>
android:textStyle="bold|italic"/> <!-- bold and italic text style for displaye
d text-->
android:background="#000"/><!--Black Color Background-->
android:padding="40dp"/> <!--40dp padding from all the side's of toggle butto->

1. id: id is an attribute used to uniquely identify a toggle button.


2. checked: checked is an attribute of toggle button used to set the current state
of a toggle button. The value should be true or false where true shows the
checked state and false shows unchecked state of a toggle button. The default
value of checked attribute is false.
3. gravity: The gravity attribute is an optional attribute which is used to control
the alignment of the text in ToogleButton like left, right, center, top, bottom,
center_vertical, center_horizontal etc.
4. textOn And textOff: textOn attribute is used to set the text when toggle
button is in checked/on state. We can set the textOn in XML as well as in
the java class.
5. textColor: textColor attribute is used to set the text color of a toggle button.
Color value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
6. textSize: textSize attribute set the size of the text of a toggle button. We can
set the text size in sp(scale independent pixel) or dp(density pixel).
7. textStyle: textStyle attribute is used to set the text style of the text of a Toggle
button. You can set bold, italic and normal. If you need to use two or more
styles for a text view then “|” operator is used for that.
8. background: background attribute is used to set the background of a toggle
button. We can set a color or a drawable in the background of a toggle button.
9. padding: padding attribute is used to set the padding from left, right, top or
bottom.

3. RadioButton:-
 In Android, RadioButton are mainly used together in a RadioGroup.
In RadioGroup checking the one radio button out of several
radio button added in it will automatically unchecked all the others. It means
at one time we can checked only one radio button from a group of radio
buttons which belong to same radio group
 RadioButon is a two state button that can be checked or unchecked. If a radio
button is unchecked then a user can check it by simply clicking on it. Once a
RadiaButton is checked by user it can’t be unchecked by simply pressing on
the same button. It will automatically unchecked when you press any
other RadioButton within same RadioGroup.
 RadioGroup is a widget used in Android for the grouping of radio buttons and
provide the feature of selecting only one radio button from the set. When a
user try to select any other radio button within same radio group the
previously selected radio button will be automatically unchecked.

Checking Current State Of Radio Button:


 You can check the current state of a radio button programmatically by using
isChecked() method. This method returns a Boolean value either true or false.
if it is checked then returns true otherwise returns false. Below is an example
code with explanation in which we checked the current state of a radio button.

/*Add in Oncreate() funtion after setContentView()*/


RadioButton simpleRadioButton = (RadioButton) findViewById(R.id.simpleRadioButton)
; // initiate a radio button

Boolean RadioButtonState = simpleRadioButton.isChecked(); // check current state o


f a radio button (true or false)

Attributes of RadioButton In Android:


Same as Above buttons

2. Difference between Events Listeners and Event Handlers?



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 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 Handler Event Listener & Description

OnClickListener()
This is called when the user either
clicks or touches or focuses upon
onClick() 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 focuses upon
onLongClick()
any widget like button, text,
image etc. for one or more
seconds. You will use
onLongClick() event handler to
handle such event.

OnFocusChangeListener()
This is called when the widget
looses its focus ie. user goes
onFocusChange()
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 presses
onKey() 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 key,
onTouch() or any movement gesture on the
screen. You will use onTouch()
event handler to handle such
event.

OnMenuItemClickListener()
This is called when the user
onMenuItemClick() selects a menu item. You will use
onMenuItemClick() event handler
to handle such event.

onCreateContextMenuItemListener()
This is called when the context
onCreateContextMenu()
menu is being built(as the result
of a sustained "long click)

3. Explain the notification concept in android? And how to create notification


with managing the notification.
 Notification is a kind of message, alert, or status of an application (probably
running in the background) that is visible or available in the Android’s UI elements.
This application could be running in the background but not in use by the user. The
purpose of a notification is to notify the user about a process that was initiated in the
application either by the user or the system. This article could help someone who’s
trying hard to create a notification for developmental purposes.
 Notifications could be of various formats and designs depending upon the
developer. In General, one must have witnessed these four types of notifications:
1. Status Bar Notification (appears in the same layout as the current time, battery
percentage)
2. Notification drawer Notification (appears in the drop-down menu)
3. Heads-Up Notification (appears on the overlay screen, ex: Whatsapp notification, OTP
messages)
4. Lock-Screen Notification (I guess you know it)

Create and Send Notifications

You have simple way to create a notification. Follow the following steps in your application
to create a notification −

Step 1 - Create Notification Builder

As a first step is to create a notification builder using NotificationCompat.Builder.build().


You will use Notification Builder to set various Notification properties like its small and
large icons, title, priority etc.

NotificationCompat.Builder mBuilder = new


NotificationCompat.Builder(this)
Step 2 - Setting Notification Properties

(Once you have Builder object, you can set its Notification properties using Builder object
as per your requirement. But this is mandatory to set at least following −z

 A small icon, set by setSmallIcon()


 A title, set by setContentTitle()
 Detail text, set by setContentText)
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click
Me!");
mBuilder.setContentText("Hi, This is Android
Notification Detail!");

You have plenty of optional properties which you can set for your notification. To learn more
about them, see the reference documentation for NotificationCompat.Builder.

Step 3 - Attach Actions

This is an optional part and required if you want to attach an action with the notification. An
action allows users to go directly from the notification to an Activity in your application,
where they can look at one or more events or do further work.

The action is defined by a PendingIntent containing an Intent that starts an Activity in your
application. To associate the PendingIntent with a gesture, call the appropriate method
of NotificationCompat.Builder. For example, if you want to start Activity when the user
clicks the notification text in the notification drawer, you add the PendingIntent by
calling setContentIntent().

A PendingIntent object helps you to perform an action on your applications behalf, often at a
later time, without caring of whether or not your application is running.

We take help of stack builder object which will contain an artificial back stack for the started
Activity. This ensures that navigating backward from the Activity leads out of your
application to the Home screen.

Intent resultIntent = new Intent(this, ResultActivity.class);


TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);

// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

Step 4 - Issue the notification

Finally, you pass the Notification object to the system by calling


NotificationManager.notify() to send your notification. Make sure you
call NotificationCompat.Builder.build() method on builder object before notifying it. This
method combines all of the options that have been set and return a new Notification object.

NotificationManager mNotificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);

// notificationID allows you to update the notification


later on.
mNotificationManager.notify(notificationID,
mBuilder.build());

4. What is mean by AVD in android (android emulator)?



o The Android emulator is an Android Virtual Device (AVD), which represents a
specific Android device. We can use the Android emulator as a target device to
execute and test our Android application on our PC. The Android emulator provides
almost all the functionality of a real device. We can get the incoming phone calls and
text messages. It also gives the location of the device and simulates different
network speeds. Android emulator simulates rotation and other hardware sensors. It
accesses the Google Play store, and much more
o Testing Android applications on emulator are sometimes faster and easier than
doing on a real device. For example, we can transfer data faster to the emulator than
to a real device connected through USB.
o The Android emulator comes with predefined configurations for several Android
phones, Wear OS, tablet, Android TV devices.

Requirement and recommendations


The Android emulator takes additional requirements beyond the basic system
requirement for Android Studio. These requirements are given below:

o SDK Tools 26.1.1 or higher


o 64-bit processor
o Windows: CPU with UG (unrestricted guest) support
o HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)

Install the emulator


The Android emulator is installed while installing the Android Studio. However some
components of emulator may or may not be installed while installing Android Studio.
To install the emulator component, select the Android Emulator component in
the SDK Tools tab of the SDK Manager.

Run an Android app on the Emulator


We can run an Android app form the Android Studio project, or we can run an app
which is installed on the Android Emulator as we run any app on a device.

To start the Android Emulator and run an application in our project:

1. In Android Studio, we need to create an Android Virtual Device (AVD) that the
emulator can use to install and run your app. To create a new AVD:-

1.1 Open the AVD Manager by clicking Tools > AVD Manager.

1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog.
Then Select Hardware page appears.
1.3 Select a hardware profile and then click Next. If we don?t see the hardware profile
we want, then we can create or import a hardware profile. The System Image page
appears.

1.4 Select the system image for the particular API level and click Next. This leads to
open a Verify Configuration page.
1.5 Change AVD properties if needed, and then click Finish.

2. In the toolbar, choose the AVD, which we want to run our app from the target device
from the drop-down menu.

3. Click Run

Q.6. Write a note on view and view group


1-View:-View is the fundamental building block of the User Interface, and It is a small
rectangular box that answer to user inputs. Likewise, View is the base class for all User
interface widgets. If we want to give an example about the View class, they can be listed as
follows.
o TextView
o EditText
o Button
o Image Button
o Date Picker
o RadioButton
o CheckBox buttons
o Image View

ViewGroup:- The ViewGroup class is a subclass of the View. classViewGroup is a


invisible container that include all Views in it. It is base class for layouts that holds all Views

and determine(ViewGroup.LayoutParams) their properties. If we want to give an example


about the ViewGroup class, they can be listed as follows

o LinearLayout

o RelativeLayout

o FrameLayout

o TableLayout

o CoordinatorLayout

o ConstraintLayout

Q.7. Explain in detail All Input Events Dialogs.


 In Android, dialogs are used to provide critical information, prompt the user for a
decision, or facilitate various input interactions. There are several types of dialogs
available in Android, each serving different purposes. Here are the primary types of
dialogs and their uses in handling input events:

Types of Dialogs
1. AlertDialog
2. DatePickerDialog
3. TimePickerDialog
4. Custom Dialogs
1. AlertDialog
AlertDialog is one of the most commonly used dialogs. It can display a title, a
message, buttons, and even custom layouts. It is used for simple alerts,
confirmations, and prompts.

Creating an AlertDialog

To create an AlertDialog, use the AlertDialog.Builder class.

new AlertDialog.Builder(this)

.setTitle("Title")

.setMessage("This is an alert dialog")

.setPositiveButton("OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

// Do something on OK

})

.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

// Do something on Cancel

})

.show();
Components of AlertDialog:

 Title: A string that appears at the top of the dialog.


 Message: A string that contains the main content of the dialog.
 Buttons: Positive, negative, and neutral buttons for user actions.
 Custom Layout: You can set a custom view to the dialog.

2. DatePickerDialog
DatePickerDialog is used to display a calendar to allow the user to pick a date.

Creating a DatePickerDialog

To create a DatePickerDialog, use the DatePickerDialog class and set an


OnDateSetListener.

DatePickerDialog datePickerDialog = new DatePickerDialog(this, new


DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// Do something with the date chosen by the user
}
}, year, month, day);
datePickerDialog.show();

Components of DatePickerDialog:

 DatePicker: A widget for selecting a date.


 OnDateSetListener: A callback that is triggered when the user sets the date.

3. TimePickerDialog
TimePickerDialog is used to display a clock to allow the user to pick a time.

Creating a TimePickerDialog

To create a TimePickerDialog, use the TimePickerDialog class and set an


OnTimeSetListener.

TimePickerDialog timePickerDialog = new TimePickerDialog(this, new


TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}, hour, minute, true); // true for 24-hour time
timePickerDialog.show();

Components of TimePickerDialog:

 TimePicker: A widget for selecting a time.


 OnTimeSetListener: A callback that is triggered when the user sets the time.

4. Custom Dialogs
Custom Dialogs are used when you need more control over the layout and behavior
of the dialog. You can create a custom dialog by inflating a custom layout.

Creating a Custom Dialog

To create a custom dialog, use the Dialog class or customize an AlertDialog.

Dialog dialog = new Dialog(this);


dialog.setContentView(R.layout.custom_dialog_layout);

Button button = dialog.findViewById(R.id.dialogButton);


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do something
dialog.dismiss();
}
});

dialog.show();

Steps to Create a Custom Dialog:

1. Define a custom layout: Create an XML layout file for the dialog.
2. Create the Dialog: Use the Dialog class and set the content view to the custom
layout.
3. Handle Input Events: Set up listeners for buttons or other input elements within the
custom layout.
9. Explain the crud operation? And write a note on cursor in android?
 CRUD is nothing but an abbreviation for the basic operations that
we perform in any database. And the operations are

 Create
 Read
 Update
 Delete

Create (Insert Data)


This operation allows the user to add new data to the database. In Android, this
usually involves collecting data from the user via a form (such as an EditText field)
and inserting it into the database.

Example:

 User enters a name into an EditText field.


 The app collects the input and inserts it into the SQLite database using a method like
insertData() in the SQLiteOpenHelper class.

Read (Retrieve Data)


This operation involves reading data from the database and displaying it to the user.
It typically involves querying the database to fetch records and then displaying them
in a UI component like a RecyclerView.

Example:

 The app queries the database to get all entries.


 It then populates a RecyclerView to display the fetched data to the user.
Update (Modify Data)
This operation allows the user to modify existing data in the database. The user
selects an item to update, makes changes, and the app updates the database with
the new information.

Example:

 User selects an item from the RecyclerView.


 The app shows a dialog or a new activity where the user can edit the data.
 The app updates the database with the new data using a method like updateData().
Delete (Remove Data)
This operation allows the user to remove data from the database. The user selects an
item to delete, and the app removes it from the database.

Example:

 User selects an item from the RecyclerView.


 The app deletes the selected item from the database using a method like deleteData().

15. Explain in details all Input Controls.



Input controls are the interactive components in your app's user interface. Android provides
a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars,
check box, zoom buttons, toggle buttons, and many more.

Android UI Controls

There are number of UI controls provided by Android that allow you to build the graphical
user interface for your app.

Sr.No. UI Control & Description

TextView
1
This control is used to display text to the user.

EditText
2 EditText is a predefined subclass of TextView that includes rich
editing capabilities.

AutoCompleteTextView
3 The AutoCompleteTextView is a view that is similar to EditText,
except that it shows a list of completion suggestions automatically
while the user is typing.

Button
4 A push-button that can be pressed, or clicked, by the user to perform
an action.

ImageButton
5 An ImageButton is an AbsoluteLayout which enables you to specify
the exact location of its children. This shows a button with an image
(instead of text) that can be pressed or clicked by the user.
CheckBox
6 An on/off switch that can be toggled by the user. You should use
check box when presenting users with a group of selectable options
that are not mutually exclusive.

ToggleButton
7
An on/off button with a light indicator.

RadioButton
8
The RadioButton has two states: either checked or unchecked.

RadioGroup
9
A RadioGroup is used to group together one or more RadioButtons.

ProgressBar
10 The ProgressBar view provides visual feedback about some ongoing
tasks, such as when you are performing a task in the background.

Spinner
11
A drop-down list that allows users to select one value from a set.

TimePicker
12 The TimePicker view enables users to select a time of the day, in
either 24-hour mode or AM/PM mode.

DatePicker
13
The DatePicker view enables users to select a date of the day.

To create a UI Control/View/Widget you will have to define a view/widget in the layout file
and assign it a unique ID as follows −

<?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_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>

Then finally create an instance of the Control object and capture it from the layout, use the
following −

TextView myText = (TextView) findViewById(R.id.text_id);


Q18.Write a note on menu control in an android? Explain Context menu and
popup menu.

Menu is a part of the user interface (UI) component which is used to handle some common
functionality around the application. By using Menus in our applications, we can provide better
and consistent user experience throughout the application.

We can use Menu APIs to represent user actions and other options in our android application
activities.

Following is the pictorial representation of using menus in the android application.

In android, we can define a Menu in separate XML file and use that file in
our activities or fragments based on our requirements.

Define an Android Menu in XML File


For all menu types, Android provides a standard XML format to define menu items. Instead of
building a menu in our activity's code, we should define a menu and all its items in an XML menu
resource and load menu resource as a Menu object in our activity or fragment.

In android, to define menu, we need to create a new folder menu inside of our project resource
directory (res/menu/) and add a new XML file to build the menu with the following elements.
Element Description

<menu> It’s a root element to define a Menu in XML file and it will hold one or more and elements.

<item> It is used to create a menu item and it represents a single item on the menu. This element may
contain a nested <menu> element in order to create a submenu.

<group> It’s an optional and invisible for <item> elements. It is used to categorize the menu items so they
share properties such as active state and visibility.

Android Different Types of Menus


In android, we have a three fundamental type of Menus available to define a set of options and
actions in our android applications.

The following are the commonly used Menus in android applications.

 Options Menu
 Context Menu
 Popup Menu

Android Options Menu


In android, Options Menu is a primary collection of menu items for an activity and it is useful to
implement actions that have a global impact on the app, such as Settings, Search, etc.

Android Context Menu


In android, Context Menu is a floating menu that appears when the user performs a long click
on an element and it is useful to implement actions that affect the selected content or context
frame.
Step By Step Implementation

Step 1: Create a New Project in Android Studio

Step 2: Working with the XML Files


Open res -> Layout -> activity_main.xml and write the following code. In this file add
only a TextView to display a simple text.

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

<!-- Relative Layout to display all the details -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/relLayout"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#fff"

android:padding="16dp"

tools:context=".MainActivity">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_marginTop="20dp"

android:text="Long press me!"

android:textColor="#000"

android:textSize="20sp"

android:textStyle="bold" />
</RelativeLayout>

Step 3: Working with the MainActivity file


Open the app -> Java -> Package -> Mainactivity.java file. In this step, add the code to
show the ContextMenu. Whenever the app will start make a long click on a text and display
the number of options to select of them for specific purposes. Comments are added inside
the code to understand the code in more detail.

import android.graphics.Color;

import android.os.Bundle;

import android.view.ContextMenu;

import android.view.MenuItem;

import android.view.View;

import android.widget.RelativeLayout;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

TextView textView;

RelativeLayout relativeLayout;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Link those objects with their respective id's that we have given in .XML file

textView = (TextView) findViewById(R.id.textView);

relativeLayout = (RelativeLayout) findViewById(R.id.relLayout);


// here you have to register a view for context menu you can register any view

// like listview, image view, textview, button etc

registerForContextMenu(textView);

@Override

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo


menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

// you can set menu header with title icon etc

menu.setHeaderTitle("Choose a color");

// add menu items

menu.add(0, v.getId(), 0, "Yellow");

menu.add(0, v.getId(), 0, "Gray");

menu.add(0, v.getId(), 0, "Cyan");

// menu item select listener

@Override

public boolean onContextItemSelected(MenuItem item) {

if (item.getTitle() == "Yellow") {

relativeLayout.setBackgroundColor(Color.YELLOW);

} else if (item.getTitle() == "Gray") {

relativeLayout.setBackgroundColor(Color.GRAY);

} else if (item.getTitle() == "Cyan") {

relativeLayout.setBackgroundColor(Color.CYAN);
}

return true;

Android Popup Menu


In android, Popup Menu displays a list of items in a vertical list that’s anchored to the view that
invoked the menu and it’s useful for providing an overflow of actions that related to specific
content.
Step By Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New
Project in Android Studio. The code for that has been given in both Java and Kotlin
Programming Language for Android.
Step 2: Working with the XML Files
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the
code for the activity_main.xml file.

 XML

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

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">
<Button

android:id="@+id/clickBtn"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="#0F9D58"

android:text="Click Me"

android:textColor="#ffffff"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Before moving further let’s add some color attributes in order to enhance the app bar. Go
to app > res > values > colors.xml and add the following color attributes.

 XML

<resources>

<color name="colorPrimary">#0F9D58</color>
<color name="colorPrimaryDark">#16E37F</color>

<color name="colorAccent">#03DAC5</color>

</resources>

Step 3: Create Menu Directory and Menu file


First, we will create a menu director which will contain the menu file. Go to app > res >
right-click > New > Android Resource Directory and give the Directory name and
Resource type as menu.

Now, we will create a popup_menu file inside that menu resource directory. Go to app >
res > menu > right-click > New > Menu Resource File and create a menu resource file
and name it popup_menu. In the popup_menu file, we will add menu items. Below is the
code snippet for the popup_menu.xml file.

 XML

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

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

android:id="@+id/java"

android:title="Java" />

<item

android:id="@+id/kotlin"

android:title="Kotlin" />

<item

android:id="@+id/android"

android:title="Android" />

<item

android:id="@+id/react_native"

android:title="React Native" />

</menu>

Step 4: Working with the MainActivity file


In the MainActivity file, we will get the reference of the Button and initialize it. Add
onClick behavior to the button and inflate the popup menu to it. Below is the code snippet
for the MainActivity file.
 Java
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.PopupMenu;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button button;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Referencing and Initializing the button

button = (Button) findViewById(R.id.clickBtn);


// Setting onClick behavior to the button

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

// Initializing the popup menu and giving the reference as current context

PopupMenu popupMenu = new PopupMenu(MainActivity.this, button);

// Inflating popup menu from popup_menu.xml file

popupMenu.getMenuInflater().inflate(R.menu.popup_menu,
popupMenu.getMenu());

popupMenu.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener() {

@Override

public boolean onMenuItemClick(MenuItem menuItem) {

// Toast message on menu item clicked

Toast.makeText(MainActivity.this, "You Clicked " + menuItem.getTitle(),


Toast.LENGTH_SHORT).show();

return true;

});
// Showing the popup menu

popupMenu.show();

});

19. Difference between radio button and checkbox.?

What is a Radio Button?


Radio buttons are an important term that belongs to the HTML family. They are
mostly used in HTML forms. A radio button is operated to choose only one
alternative out of multiple functional options.

What is a Checkbox?
Checkboxes are also mostly used in HTML forms. A checkbox allows you to choose
one or many options to be selected from a list of options.

Difference between Radio Button and Checkbox


S.No. Radio button Checkbox

1 Radio buttons are used when we need to pick a single A checkbox authorises us to choose one or
option out of various available alternatives. more options.

2 Here we use an HTML <input> tag and set the radio as We use the HTML <input> tag followed by
a type attribute. the checkbox attribute.

3 Radio button is a single control unit. Checkbox is a multiple control unit.


4 When we need to restrict the user’s selection to just It is operated when we need to permit the
one option, then we use it. user to choose multiple options.

5 It is shown as a little circle on the screen. It is shown as a small square box.

6 Radio button have only 2 states namely- True & Checkbox have 3 states namely- Checked,
False. unchecked & indeterminate

20. Explain the toast concept with suitable example syntax?


 In Android, Toast is used to display information for a period of time. It contains a
message to be displayed quickly and disappears after specified period of time. It does not
block the user interaction. Toast is a subclass of Object class. In this we use two constants for
setting the duration for the Toast. Toast notification in android always appears near the
bottom of the screen. We can also create our custom toast by using custom layout(xml file).

Constants of Toast class


Constants Description

public static final int LENGTH_LONG displays for a long time


Constants Description

public static final int LENGTH_SHORT displays for a short time

Methods of Toast class


Methods Description

public static Toast makeText(Context context, makes the toast message consist of
CharSequence text, int duration) text and time duration

public void show() displays a toast message

public void setMargin (float horizontalMargin, changes the horizontal and vertical
float verticalMargin) differences

Step-By-Step Implementation

Step 1: Create a New Project in Android Studio

Step 2: Working with the XML Files


Open the “activity_main.xml” file and add a Button to show the Toast message in
a Constraint Layout. Also, Assign an ID to the button component as shown in the image
and the code below. The assigned ID to the button helps to identify and to use files.
android:id="@+id/id_name"
Here the given ID is Button01 This will make the UI of the Application:

Step 3: Working with the MainActivity File


Now, after the UI, this step will create the Backend of the App. For this, Open the
“MainActivity” file and instantiate the component (Button) created in the XML file using
the findViewById() method. This method binds the created object to the UI Components
with the help of the assigned ID.
General Syntax:
ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);
The syntax for the used component (Click Button):
Button btn = (Button)findViewById(R.id.Button01);

Step 4: Operations to Display the Toast Message


Add the listener on the Button and this Button will show a toast message.
btn.setOnClickListener(new View.OnClickListener() {});
Now, Create a toast message. The Toast.makeText() method is a pre-defined method that
creates a Toast object. Syntax:
public static Toast makeText (Context context, CharSequence text, int duration)
Parameters: This method accepts three parameters:
A. context: A first parameter is a Context object which is obtained by calling
getApplicationContext().
Context context = getApplicationContext();
B. text: The second parameter is your text message to be displayed.
CharSequence text=”Your text message here”
C. duration: The last parameter is the time duration for the message.
int duration=Toast.LENGTH_LONG;
Display the created Toast Message using the show() method of the Toast class.
Syntax:
public void show ()
The code to show the Toast message:
Toast.makeText(getApplicationContext(), "This a toast message",
Toast.LENGTH_LONG).show();

Step 5: Now Run the App


Operate it as follows:
 When the app is opened, it displays a “Click” button.
 Click the Click button.
 Then “This a toast message” will be displayed on the screen as a Toast Message.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


// Defining the object for button
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Bind the components to their respective objects by assigning


// their IDs with the help of findViewById() method
Button btn = (Button)findViewById(R.id.Button01);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Displaying simple Toast message
Toast.makeText(getApplicationContext(), "This
a toast message", Toast.LENGTH_LONG).show();
}
});
}
}

OUTPUT:-
21. Write a note on cursor in android?
 The basic purpose of a cursor is to point to a single row of the result fetched by the
query. We load the row pointed by the cursor object. By using cursor we can save lot
of ram and memory. Here, we pass the table name, column name only then we receive
the cursor
 Cursor is the Interface which represents a 2 dimensional table of any database. When
you try to retrieve some data using SELECT statement, then the database will first
create a CURSOR object and return its reference to you.
 The pointer of this returned reference is pointing to the 0th location which is
otherwise called as before first location of the Cursor, so when you want to retrive
data from the cursor, you have to first move to the first record so we have to
use moveToFirst
 When you invokes moveToFirst() method on the Cursor, it takes the cursor pointer
to the first location. Now you can access the data present in the first record
 In simple words, Cursor is a Interface whice returns collection of your query
data. moveToFirst() is used to point the cursor position from where you want to get
data from your cursor. There are
methods moveToLast(), moveToNext(), moveToPrevious(), moveToPosition(position
) by which you can iterate through your cursor by desired way.
 For example, you have data in your Cursor

Lalit
Rithesh
Paresh
Chandra
 moveToFirst() - If you use cursor.moveToFirst() then in this case it will point Lalit, as it is the
first data in your cursor. To get the next data from cursor you can use moveToNext().
 moveToLast() - This will point Chandra as the current data in your cursor. To get the previous
data from cursor you can use moveToPrevious()
 A Cursor represents the result of a query and basically points to one row of the
query result. This way Android can buffer the query results efficiently; as it does
not have to load all data into memory.

 To get the number of elements of the resulting query use the getCount() method.
 To move between individual data rows, you can use
the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check
if the end of the query result has been reached.
 Cursor provides typed get*() methods,
e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the
current position of the result. The "columnIndex" is the number of the column
you are accessing.
 Cursor also provides the getColumnIndexOrThrow(String) method which allows to get
the column index for a column name of the table.
 A Cursor needs to be closed with the close() method call. A query returns a Cursor
object
The following methods are available in the Cursor interface which iterate through
the Cursor, setting the Cursor pointer to the desired position:
 moveToFirst()
 moveToLast()
 moveToNext()
 moveToPrevious()
 moveToPosition(position)

Q.23 Explain the Sharing Data between Applications with Content


Providers
Content Providers in Android provide a structured way to share data between
applications. They encapsulate data and provide mechanisms for defining data
security, offering a unified interface for accessing structured data sets. Here’s an in-
depth look at how Content Providers work and how they facilitate data sharing
between applications.

What is a Content Provider?


A Content Provider manages access to a central repository of data. It's part of the
Android application architecture that allows applications to share data with other
apps while maintaining control over how the data is accessed and modified.

By using the content provider, data can be shared across applications. The content

provider is a set of data wrapped up in a custom API to read and write.

Applications/Processes have to register themselves as a provider of data. Other

applications can request Android to read/write that data through a fixed API.

Content provider API has methods to perform operations(CRUD) on data.

Contacts are the best example – that exposes user information to other applications,

Media store-Allows other applications to access, store media files.

There is some standard methods – insert(), query(), update(), delete(), to access

application data. So it is easy to implement a content provider.

We need to assign a URI to each Content Provider, starting with “content://” and that

will be recognized by applications.


1. Create a class for ContentProvider.
2. Define content URI
3. Implement all the unimplemented methods. insert(), update(), query(), delete(), getType().
4. Declare the content provider in AndroidManifest.xmluthority/Path/Id

1. content:// – The content provider URIs should start with this value.

2. ‘authority’ – This is Java namespace of the content provider implementation passes the

Java package name.

3. ‘path’ – This is a virtual directory within the provider that identifies, what kind of data

being requested.

4. ‘id’ – This is an optional part that specifies the primary key of a record being requested.

This part can be ignored to access all data.

Add data:
We need to override insert() method. If data inserted successful, it will return the URI value
with the associated with ID.
For example: If we passed – content://packageName/sample
Method will return content://packageName/sample/1

Updating data:

update() method of the ContentProvider is used to update records.

This method will return the number of rows updated.

Deleting data:

delete() method of the ContentProvider will return the number of records deleted.

We need to register the content providers in the AndroidManifest.xml.

<provider
android:name=".MyProvider"
android:authorities="packageName.MyProvider">
</provider>

You might also like