Android notes
Android notes
1 marks
1) What is SDK?
SDK stands for Software Development Kit. It is a collection
of tools, libraries, documentation, and samples that
developers use to create software applications for a
specific platform or framework
2) What is Activity?
an Activity is a fundamental component of an application
that represents a single screen with a user interface. It
serves as the entry point for interacting with the user and
handling user interactions such as button clicks, text input,
and more
3) How to close database using SQLite?
To close a SQLite database in Android, you simply need to
call the close() method on the SQLiteDatabase object
4) SQLite Database.
SQLite is a lightweight, embedded relational database
engine that is widely used in Android applications for
storing and managing structured data.
5) SQLite OpenHelper.
SQLiteOpenHelper is a helper class provided by the
Android framework to manage database creation and
version management for SQLite databases.
6) What is meant by google map?
Google Maps is a web mapping service developed by
Google that provides detailed maps, satellite imagery,
street views, and route planning capabilities for users
worldwide. It offers various features and functionalities to
help users navigate, explore, and discover locations both
locally and globally.
7) define cursor in SQlite?
In SQLite, a cursor is a pointer or iterator that allows you
to traverse and manipulate the result set of a query. When
you execute a SELECT statement in SQLite, it returns a
result set, which is essentially a table of data that meets
the criteria specified in the query.
8) What is context menu?
A context menu in Android is a floating menu that appears
when the user performs a long press or right-click on a
specific view or item within an application's user interface.
9) Example of text view?
EditTextView
TextView
10) Explain use of Datepicker.
The DatePicker is a user interface control in Android that
allows users to select a date from a calendar-style
interface. It is commonly used in applications where users
need to input or specify a date, such as in forms, booking
apps, reminders, and more.
11) Enlist the types of Menu.
Content Menu
Option Menu
Popup Menu
12) Define AVD.
AVD stands for Android Virtual Device. It is an emulator
configuration that allows developers to simulate Android
devices on their development machine for testing and
debugging purposes.
13) What is Fragment?
A Fragment is a modular, reusable component of an
Android user interface that represents a portion of a user
interface or behavior within an Activity.
14) What is viewGroup?
A ViewGroup in Android is a special type of View that acts
as a container for other Views (including other
ViewGroups) and defines the layout structure of the user
interface.
3 marks
1) Explain the term displaying Google Map in detail.
1. Displaying Google Maps involves integrating the Google
Maps API into your application.
2. You need to obtain an API key from the Google Cloud
Console.
3. Incorporate the API key into your application to enable
access to Google Maps services.
4. Utilize the appropriate Google Maps components, such
as MapView or MapFragment, in your layout.
5. Configure the map settings and customize its
appearance as needed.
6. Implement features like markers, polylines, or overlays
to enhance the map's functionality.
7. Handle user interactions and events on the map, like
clicks or gestures.
8. Ensure proper error handling and permissions for map
usage in your application.
2) Note on List Fragment and Dialog Fragment.
List Fragment:
1. Specialized fragment for displaying a list of items.
2. Extends the Fragment class and typically uses a ListView
or RecyclerView to present the data.
3. Supports various adapters like ArrayAdapter or
CursorAdapter for populating the list.
4. Handles item selection events through interfaces like
OnItemClickListener.
5. Can be used to create master-detail interfaces or
standalone lists within an activity.
6. Suitable for displaying dynamic data fetched from
databases or APIs.
7. Provides methods for managing the list's state, such as
scrolling to a specific position or updating the dataset.
Dialog Fragment:
1. Represents a fragment that displays a modal dialog
window.
2. Extends the DialogFragment class and typically inflates a
layout to represent the dialog's content.
3. Can be used for various purposes like alerts,
notifications, or user interactions.
4. Supports customization of dialog appearance and
behavior using onCreateDialog() or onCreateView()
methods.
5. Enables communication between the dialog and its
parent activity or fragment through interfaces.
6. Provides lifecycle methods for managing the dialog's
state, such as onCreate() or onDestroyView().
7. Can handle user interactions within the dialog, like
button clicks or input validation.
3) Explain different kinds of Layout.
1. Linear Layout:
Organizes child views in a single direction (horizontal or
vertical).
Views are arranged linearly, one after another.
Supports weighting to distribute space proportionally.
2. Relative Layout:
Positions child views relative to each other or to the
parent layout.
Views are placed based on relationships like above,
below, to the left, or to the right of other views.
Offers flexibility in designing complex UIs by specifying
view positions relative to one another.
3. Constraint Layout:
Allows creating complex layouts with a flat view
hierarchy.
Utilizes constraints to define the position and alignment
of views relative to each other and to the parent layout.
Supports guidelines, barriers, and chains for advanced
layout management.
Offers improved performance compared to nested
layouts.
4. Frame Layout:
Places child views on top of each other, with the last
added view appearing at the top.
Typically used for displaying single views or overlapping
views, like fragments in a container.
Suitable for scenarios where only one view needs to be
visible at a time.
5. Table Layout:
Organizes child views in rows and columns, similar to an
HTML table.
Views are arranged in a grid-like structure.
Supports specifying column stretch or shrink behavior
and row span for cells.
6. Grid Layout:
Arranges child views in a grid of rows and columns.
Supports both row-based and column-based positioning.
Offers alignment and justification options for precise
layout control.
Provides flexibility in designing responsive UIs for
different screen sizes and orientations.
4) Write any five features of android.
1. Customizable User Interface:
Android allows extensive customization of the user
interface through themes, styles, and layouts.
Users can personalize their devices with widgets,
wallpapers, and custom launchers.
Developers can create unique and branded UI
experiences tailored to their apps.
2. Multitasking and Background Processing:
Android supports multitasking, allowing users to switch
between apps seamlessly.
Apps can run in the background to perform tasks like
syncing data, receiving notifications, or playing media.
Background services enable continuous operation even
when the app is not in the foreground.
3. Rich Development Environment:
Android provides a rich set of development tools,
including Android Studio, SDK Manager, and Android
Debug Bridge (ADB).
Developers have access to a vast array of libraries, APIs,
and resources to build powerful and feature-rich
applications.
Support for various programming languages like Java
and Kotlin enhances flexibility and productivity.
4. Connectivity and Integration:
Android devices offer extensive connectivity options,
including Wi-Fi, Bluetooth, NFC, and USB.
Integration with cloud services like Google Drive and
Firebase enables seamless data synchronization and
backup.
Support for hardware peripherals and sensors facilitates
the development of IoT and wearable applications.
5. Security and Privacy:
Android incorporates multiple layers of security to
protect user data and privacy.
Features like app sandboxing, permissions system, and
Google Play Protect mitigate security risks.
Regular security updates and patches are provided to
address vulnerabilities and ensure device security.
5) What is scroll view? Explain with example.
ScrollView is a layout container in Android that enables
scrolling of its content if it exceeds the available screen
space. It allows users to view all the content by scrolling
vertically or horizontally.
Example:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Sed et eros nec nisi gravida
aliquet." />
</ScrollView>
In this example:
The ScrollView wraps around a LinearLayout that holds
multiple views.
If the combined height of the views exceeds the screen
height, the ScrollView enables vertical scrolling.
Users can scroll through the content to view all the text in
the TextView or any other views within the layout.
6) With the help of example explain spinner.
A Spinner in Android is a dropdown menu that allows
users to select an item from a list of options. It displays the
currently selected item and provides a dropdown list of
available options when clicked, allowing users to choose a
different item.
Example:
xml
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In this example, the Spinner widget is defined in the XML
layout file. To populate the Spinner with data, you can use
an ArrayAdapter or a CursorAdapter. Here's an example of
populating the Spinner with an ArrayAdapter:
java
Spinner spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this,
R.array.planets_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simpl
e_spinner_dropdown_item);
spinner.setAdapter(adapter);
In this code:
`R.array.planets_array` refers to an array resource
containing the list of options (e.g., planets).
`android.R.layout.simple_spinner_item` is the layout for
each item in the dropdown list.
`android.R.layout.simple_spinner_dropdown_item` is the
layout for the dropdown list itself.
The ArrayAdapter is set to the Spinner using `setAdapter()`
method.
Now, the Spinner is populated with data, and users can
select an item from the dropdown menu. You can handle
item selection events using listeners like
`OnItemSelectedListener` to perform actions based on the
selected item.
7) What is video view? Explain with example
VideoView videoView = findViewById(R.id.videoView);
String videoPath = "android.resource://" +
getPackageName() + "/" + R.raw.video_sample; // Example
video file in raw resources
videoView.setVideoURI(Uri.parse(videoPath));
videoView.setOnPreparedListener(new
MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
videoView.start();
}
});
videoView.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
// Perform actions when video playback completes
}
});
8) List and explain methods of SQlite open Helper.
SQLiteOpenHelper is a helper class that manages database
creation and version management. Here are some of the
key methods of SQLiteOpenHelper:
1. `SQLiteOpenHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version)`:
Constructor for SQLiteOpenHelper class. It initializes the
helper class with the provided database name, factory, and
version.
2. `onCreate(SQLiteDatabase db)`: Called when the
database is created for the first time. You should execute
SQL statements here to create necessary tables and
initialize the database schema.
3. `onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion)`: Called when the database needs to be
upgraded, typically because the version number has
changed. You should execute SQL statements here to
modify the database schema or data to accommodate the
new version.
4. `onDowngrade(SQLiteDatabase db, int oldVersion, int
newVersion)`: Called when the database needs to be
downgraded, typically because the version number has
decreased. You should execute SQL statements here to
revert changes made in the `onUpgrade` method.
5. `onOpen(SQLiteDatabase db)`: Called when the database
has been opened. You can perform additional initialization
tasks here if needed.
These methods provide hooks for managing database
creation, upgrades, downgrades, and additional
initialization tasks in an SQLite database within an Android
application.
9) What is Fragments? Explain types of it.
Fragments in Android are modular components that
represent a portion of a user interface or behavior in an
activity. They allow developers to create more flexible and
reusable UI designs by breaking the UI into smaller, self-
contained pieces.
Types of Fragments:
1. Single Fragment: A standalone fragment that represents
a complete UI screen or functionality within an activity. It's
typically used for simple UI components or standalone
features.
2. List Fragment: Specialized fragment for displaying a list
of items, often used with ListView or RecyclerView to
present data in a scrollable list format.
3. Dialog Fragment: Represents a modal dialog window
that overlays the current UI, commonly used for displaying
alerts, notifications, or interactive dialogs.
4. Dynamic Fragments: Fragments that are dynamically
added or replaced within an activity's layout at runtime.
They offer flexibility in adapting the UI based on user
interactions or device configurations.
5. Master-Detail Fragments: Used in conjunction with each
other to create master-detail interfaces, where a list of
items (master) is displayed alongside detailed information
(detail) when an item is selected.
6. Navigation Fragments: Fragments that represent
different destinations within a navigation graph, used with
Navigation Component to manage navigation between
screens in an app.
By leveraging different types of fragments, developers can
build versatile and responsive UIs that adapt to various
screen sizes, orientations, and user interactions in Android
applications.
10) List and explain Image views.
List of Image Views in Android:
1. ImageView: The basic widget used to display images in
an Android application. It supports various scale types for
controlling how the image is displayed within the view.
2. ImageButton: A subclass of ImageView that represents a
clickable image button. It's often used for implementing
custom buttons with image icons.
3. RoundedImageView: A custom ImageView
implementation that displays images with rounded
corners. It's commonly used for achieving a circular or
rounded image appearance.
4. GlideImageView: A custom ImageView implementation
that integrates with the Glide library for efficient image
loading and caching. It simplifies the process of loading
images from URLs or local files.
5. PicassoImageView: A custom ImageView
implementation that integrates with the Picasso library for
image loading and caching. It provides an easy-to-use
interface for loading images asynchronously.
6. CircleImageView: A custom ImageView implementation
that displays images in a circular shape. It's useful for
creating profile picture views or circular avatars.
7. PaletteImageView: A custom ImageView implementation
that extracts prominent colors from an image using the
Palette library. It allows developers to dynamically update
the UI based on the colors in the image.
These are some common types of Image Views used in
Android development for displaying images with different
functionalities and appearances.
4 marks
1) What is Menu? Explain types of Menus.
In Android, a menu is a UI component that provides users
with a set of options or actions they can perform within an
application. Menus can be displayed as either options
menus, context menus, or popup menus.
Types of Menus:
1. Options Menu:
The options menu is typically displayed in the app's
action bar or toolbar.
It contains a set of actions or options that are relevant to
the current context or activity.
Options menu items are accessed by tapping the "menu"
icon or by pressing the device's menu button.
Options menu items can have icons, text, or both, and
they can be dynamically updated based on the
application's state.
2. Context Menu:
Context menus are typically triggered by long-pressing
on a view or item within an application.
They provide a context-specific set of actions or options
related to the selected item.
Context menu items are displayed as a popup menu
anchored to the selected item.
Context menus are commonly used in lists, grids, or other
interactive components to provide actions like delete, edit,
or share.
3. Popup Menu:
Popup menus are versatile menus that can be displayed
anywhere on the screen.
They can be triggered by tapping on a view, button, or
any other UI element.
Popup menus provide a list of actions or options that are
relevant to the selected UI element.
Popup menus are often used for displaying additional
options in a more compact or contextual manner.
2) Explain any Four types of Buttons.
Four types of buttons commonly used in Android
development:
1. Standard Button (Button):
Represents a basic clickable button in an Android
application.
Typically used for triggering actions or submitting forms.
Can be customized with different background colors, text
colors, and styles.
2. Image Button (ImageButton):
A button that displays an image instead of text.
Often used for implementing custom buttons with icon-
based actions.
Supports setting an image as the button's background.
3. Floating Action Button (FloatingActionButton):
A circular button with an icon that floats above the
content in a UI.
Commonly used for promoting primary actions or actions
with high visibility.
Positioned in the bottom right corner by default, but can
be customized for different positions.
4. Toggle Button (ToggleButton):
Represents a two-state button that can be toggled on or
off.
Each press alternates between the checked and
unchecked states.
Useful for implementing binary options or settings where
users can switch between two states.
3) Describe life cycle of fragment diagrammatically.
The lifecycle of a Fragment in Android includes several
callback methods that are invoked at different stages of its
existence. Here's an overview of the lifecycle stages of a
Fragment:
1. onAttach():
Called when the fragment is attached to an activity.
The fragment gains access to the hosting activity through
the `Context`.
2. onCreate():
Invoked when the fragment is being created.
Initialization tasks, such as creating data structures,
should be performed here.
3. onCreateView():
Called to create the fragment's UI view hierarchy, usually
from a layout resource.
Inflates the layout and returns the root View for the
fragment UI.
4. onViewCreated():
Called after `onCreateView()` when the fragment's view
hierarchy has been created.
UI setup tasks, such as finding views and initializing UI
components, can be performed here.
5. onActivityCreated():
Invoked when the hosting activity's `onActivityCreated()`
method is called.
Fragment's activity is fully created, and it can access the
activity via `getActivity()`.
6. onStart():
Called when the fragment becomes visible to the user.
UI updates or tasks that should be performed when the
fragment becomes visible can be done here.
7. onResume():
Invoked when the fragment is visible and interactive to
the user.
Fragment gains focus and user interaction is possible.
8. onPause():
Called when the fragment is no longer interactive but still
visible to the user.
Any ongoing operations that are not critical to the user
experience should be paused.
9. onStop():
Invoked when the fragment is no longer visible to the
user.
Resources or operations that are not needed when the
fragment is not visible can be released here.
10. onDestroyView():
Called when the fragment's view hierarchy is being
destroyed.
Cleanup tasks, such as releasing references to views,
should be performed here.
11. onDestroy():
Invoked when the fragment is being destroyed.
Clean up any resources or finalize operations that were
held by the fragment.
12. onDetach():
Called when the fragment is detached from its hosting
activity.
The fragment loses access to the hosting activity.
4) What is VideoView? How Optimize Video View?
VideoView:
1. It's a widget in Android for playing videos from various
sources.
2. It handles video playback and display within the UI.
3. It's a subclass of SurfaceView and MediaPlayer,
providing a convenient way to play videos.
Optimizing VideoView:
1. Use Appropriate Video Formats: Choose formats like
MP4 with H.264 video and AAC audio for better
compatibility.
2. Optimize Video Resolution: Match video resolution to
the display size to reduce processing overhead.
3. Implement Buffering: Preload video content for
smoother playback and reduce interruptions.
5) What is Toggle button? How to create it? Explain
with example.
Toggle Button:
1. A toggle button is a UI component in Android that
represents an on/off or binary state.
2. Users can switch between two states by tapping the
button.
Creating a Toggle Button:
1. XML Layout:
xml
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="Off"
android:textOn="On" />
2. Java Code:
java
ToggleButton toggleButton =
findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton
buttonView, boolean isChecked) {
// Handle toggle state change
if (isChecked) {
// Toggle is On
} else {
// Toggle is Off
}
}
});
1. Define Intent:
Create an Intent object to specify the target activity.
2. Set Destination Activity:
Set the class of the target activity to the Intent using
`setClass()` or `setComponent()` method.
3. Optional: Add Data:
If you need to pass data between activities, use
`putExtra()` to add data to the Intent.
4. Start Activity:
Call `startActivity()` with the Intent to navigate to the
target activity.
Example:
Assuming you have two activities: `MainActivity` and
`SecondActivity`.
In `MainActivity`, to navigate to `SecondActivity`:
java
// Inside MainActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
If you need to pass data:
java
// Inside MainActivity
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("key", value);
startActivity(intent);
In `SecondActivity`, to retrieve the data:
java
// Inside SecondActivity
Intent intent = getIntent();
String value = intent.getStringExtra("key");
3) Write the use of onCreate( ), onUpgrade ( ) and
getWritable Database( ) methods. With example.
Sure, here's a brief explanation of the `onCreate()`,
`onUpgrade()`, and `getWritableDatabase()` methods in
Android's SQLiteOpenHelper class, along with an example:
1. onCreate() Method:
This method is called when the database is created for
the first time.
It should contain code to create the database schema,
including tables and initial data.
Example:
java
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE contacts (id INTEGER
PRIMARY KEY, name TEXT, phone TEXT)");
}
2. onUpgrade() Method:
This method is called when the database needs to be
upgraded due to a schema change.
It should contain code to handle schema migrations, such
as dropping and recreating tables or altering existing
tables.
Example:
java
@Override
public void onUpgrade(SQLiteDatabase db, int
oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
3. getWritableDatabase() Method:
This method returns a SQLiteDatabase object that allows
writing (inserting, updating, deleting) data in the database.
It automatically calls `onCreate()` or `onUpgrade()` if
necessary before returning the database.
Example:
java
SQLiteDatabase db = dbHelper.getWritableDatabase();
In this example, `dbHelper` is an instance of your
`SQLiteOpenHelper` subclass.
These methods are crucial when working with SQLite
databases in Android, providing the necessary hooks to
create, upgrade, and obtain a writable database instance.
4) Write an application to send Email (Using To,
Subject and Message) Intent.
5) Explain List View using adapter with the help of
example.
1. Layout XML (activity_main.xml):
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/andr
oid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
2. Java Code (MainActivity.java):
java
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Sample data
String[] countries = {"USA", "Canada", "Australia",
"UK", "Germany", "France"};
// Initialize the ListView
ListView listView = findViewById(R.id.listView);
// Create ArrayAdapter and set it to the ListView
ArrayAdapter<String> adapter = new
ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
countries);
listView.setAdapter(adapter);
}
}
In this example, we define a ListView in the layout XML file
(activity_main.xml). Then, in the MainActivity.java file, we
initialize the ListView, create an ArrayAdapter with some
sample data (countries), and set the ArrayAdapter to the
ListView. This will display the list of countries in the
ListView using the default layout provided by
`android.R.layout.simple_list_item_1`.
6) How to create database in sQlite? Give an example
To create a SQLite database in an Android application, you
typically use a subclass of SQLiteOpenHelper. Here's an
example of how to create a SQLite database:
1. Create a subclass of SQLiteOpenHelper:
java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME =
"mydatabase.db";
private static final int DATABASE_VERSION = 1;
public MyDBHelper(Context context) {
super(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create the database schema
String createTableQuery = "CREATE TABLE mytable
(_id INTEGER PRIMARY KEY AUTOINCREMENT, name
TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int
oldVersion, int newVersion) {
// Upgrade the database if needed (not implemented
in this example)
}
}
2. Use the SQLiteOpenHelper subclass to create the
database:
java
// In your activity or other application component
MyDBHelper dbHelper = new MyDBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
This will create a new database file named
"mydatabase.db" with a table named "mytable" containing
an "_id" column as the primary key and a "name" column.
You can then use the returned SQLiteDatabase object
(`db`) to perform various database operations such as
inserting, updating, deleting, and querying data.
7) Location based Services & Google Map.
Example:
xml
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button1" />
</androidx.constraintlayout.widget.ConstraintLayout>