Android Development (ESE1)
Android Development (ESE1)
<Button
android:id="@+id/simpleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abhi Android"/>
Output:-
Submit
<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-->
<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->
2. ToggelButton:-
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->
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.
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)
You have simple way to create a notification. Follow the following steps in your application
to create a notification −
(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
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.
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.
// 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);
NotificationManager mNotificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
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
o LinearLayout
o RelativeLayout
o FrameLayout
o TableLayout
o CoordinatorLayout
o ConstraintLayout
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
new AlertDialog.Builder(this)
.setTitle("Title")
// Do something on OK
})
// Do something on Cancel
})
.show();
Components of AlertDialog:
2. DatePickerDialog
DatePickerDialog is used to display a calendar to allow the user to pick a date.
Creating a DatePickerDialog
Components of DatePickerDialog:
3. TimePickerDialog
TimePickerDialog is used to display a clock to allow the user to pick a time.
Creating a TimePickerDialog
Components of TimePickerDialog:
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.
dialog.show();
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
Example:
Example:
Example:
Example:
Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical
user interface for your app.
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 −
<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 −
We can use Menu APIs to represent user actions and other options in our android application
activities.
In android, we can define a Menu in separate XML file and use that file in
our activities or fragments based on our requirements.
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.
Options Menu
Context Menu
Popup Menu
<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:textColor="#000"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
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;
TextView textView;
RelativeLayout relativeLayout;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Link those objects with their respective id's that we have given in .XML file
registerForContextMenu(textView);
@Override
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Choose a color");
@Override
if (item.getTitle() == "Yellow") {
relativeLayout.setBackgroundColor(Color.YELLOW);
relativeLayout.setBackgroundColor(Color.GRAY);
relativeLayout.setBackgroundColor(Color.CYAN);
}
return true;
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
<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>
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
<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"
</menu>
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
Button button;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new View.OnClickListener() {
@Override
// Initializing the popup menu and giving the reference as current context
popupMenu.getMenuInflater().inflate(R.menu.popup_menu,
popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener() {
@Override
return true;
});
// Showing the popup menu
popupMenu.show();
});
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.
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.
6 Radio button have only 2 states namely- True & Checkbox have 3 states namely- Checked,
False. unchecked & indeterminate
public static Toast makeText(Context context, makes the toast message consist of
CharSequence text, int duration) text and time duration
public void setMargin (float horizontalMargin, changes the horizontal and vertical
float verticalMargin) differences
Step-By-Step Implementation
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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)
By using the content provider, data can be shared across applications. The content
applications can request Android to read/write that data through a fixed API.
Contacts are the best example – that exposes user information to other applications,
We need to assign a URI to each Content Provider, starting with “content://” and that
1. content:// – The content provider URIs should start with this value.
2. ‘authority’ – This is Java namespace of the content provider implementation passes the
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.
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:
Deleting data:
delete() method of the ContentProvider will return the number of records deleted.
<provider
android:name=".MyProvider"
android:authorities="packageName.MyProvider">
</provider>