0% found this document useful (0 votes)
15 views35 pages

MAD Solved Notes

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

MAD Solved Notes

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

MAD solved notes

Q1. What are intents and intent objects? Differentiate between the types of intents with example
in mobile application development.

A. Certainly! Let's dive deeper into intents and intent objects in the context of mobile
application development.

1. **Intent**: An intent is essentially a message that's used to communicate between different


components of an application or between different applications on the device. It can be used for
a variety of purposes such as starting activities, services, or broadcasting messages.

2. **Intent Objects**: Intent objects encapsulate the information necessary to perform an


action or to pass data between components. They can contain metadata about the action to be
performed (such as the type of action and the data involved) and optional extras (additional
data) to be passed along.

Now, let's differentiate between the types of intents with examples:

**Explicit Intents**:
- These intents explicitly specify the target component that should handle the action.
- They are used when you know exactly which component you want to start.
- Typically used within the same application to navigate between different activities.

Example:
java
Intent explicitIntent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(explicitIntent);

In this example, `CurrentActivity` wants to start `TargetActivity` explicitly within the same
application.

**Implicit Intents**:
- These intents do not specify the target component but instead describe the action to be
performed.
- The system resolves the appropriate component to handle the intent based on its contents and
available applications.
- Used when you want the system to determine the best component to handle the action, such
as opening a webpage in a browser or sending an email.

Example:
java
Intent implicitIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));
startActivity(implicitIntent);
Here, the implicit intent requests to view a webpage. The system will find and launch an
appropriate activity (e.g., a web browser) capable of handling this action.

In summary, explicit intents are used for intra-application communication when the target
component is known, while implicit intents are used for inter-application communication when
the system needs to determine the appropriate component based on the action requested.

Q2. Describe the significance of SQLite Database and SQLiteOpenHelper in Android.10 marks

A. SQLite Database and SQLiteOpenHelper play significant roles in Android development, particularly in
managing and persisting data within an application. Here's a detailed explanation of their significance:

1. **Data Persistence**: One of the primary roles of SQLite Database in Android is to provide a
mechanism for storing and retrieving structured data persistently. Android applications often need to
store data locally, such as user preferences, application settings, or cached data. SQLite provides a
lightweight, file-based relational database that can be easily integrated into Android applications.

2. **Structured Storage**: SQLite Database offers a structured storage mechanism, allowing developers
to define tables with columns and constraints to organize and manage their data efficiently. This enables
developers to implement complex data structures and relationships within their applications.

3. **SQL Support**: SQLite is based on SQL (Structured Query Language), which is a widely-used
standard for managing relational databases. This familiarity with SQL makes it easier for developers to
work with SQLite in Android applications, as they can use familiar SQL queries to perform operations
such as inserting, updating, deleting, and querying data.

4. **Performance**: SQLite Database is designed to be lightweight and efficient, making it well-suited


for use in resource-constrained environments such as mobile devices. It has a small memory footprint
and performs well even on devices with limited processing power and storage capacity.

5. **Transaction Support**: SQLite supports transactions, which allow developers to group multiple
database operations into a single atomic unit. This ensures data integrity and consistency, as either all of
the operations within a transaction are successfully completed, or none of them are applied.

6. **Concurrency Control**: SQLite provides built-in support for concurrency control, allowing multiple
threads or processes to access the database simultaneously. SQLiteOpenHelper helps manage database
connections and ensures that they are properly handled to prevent issues such as database corruption or
deadlock.

7. **SQLiteOpenHelper**: SQLiteOpenHelper is a helper class provided by the Android framework that


simplifies database creation and management tasks. It assists in managing database creation and version
management, handling database upgrades, and providing access to a writable or readable database
instance.

8. **Database Versioning**: SQLiteOpenHelper helps in managing database versioning, which is


essential for maintaining backward compatibility and handling schema changes gracefully. By
incrementing the database version number and implementing upgrade logic, developers can ensure that
existing data is migrated properly when deploying new versions of their applications.

9. **Initialization**: SQLiteOpenHelper facilitates the initialization of the database by providing hooks


for executing SQL scripts or statements to create tables, indexes, and other database objects when the
database is first created.

10. **Abstraction Layer**: SQLiteOpenHelper abstracts away many low-level details of working with
SQLite databases, allowing developers to focus on application-specific logic rather than boilerplate code
for database management tasks.

In conclusion, SQLite Database and SQLiteOpenHelper are essential components of Android


development, providing a robust and efficient mechanism for data persistence and management in
Android applications. They simplify the process of working with relational databases, offer performance
benefits, and help maintain data integrity and consistency across different versions of an application.

Q3. . Explain the Activity LifeCycle 10 marks

A. Sure, let's dive into each stage of the Activity Lifecycle in more detail:

1. **onCreate():** This method is called when the activity is first created. It's where you typically
initialize essential components of the activity, such as layout inflating (setting the UI layout with
setContentView()), initializing variables, and performing one-time setup tasks. This method receives a
Bundle parameter, which is used to restore the activity's previous state if it was destroyed and recreated
(for example, during a configuration change like screen rotation). You can check whether the activity is
being created for the first time or being recreated by checking if the Bundle is null.
2. **onStart():** Called when the activity becomes visible to the user. At this point, the activity is about
to become visible, but it is not yet in the foreground. You can perform tasks like registering broadcast
receivers or acquiring resources that are needed while the activity is visible.

3. **onResume():** This method is called when the activity starts interacting with the user. It's the point
where the activity is at the top of the activity stack and is in the foreground. Here, you should initialize
components that you release in onPause(), such as starting animations, acquiring resources that are
needed only while the activity is visible, or updating UI elements.

4. **onPause():** Called when the activity is partially obscured by another activity. This could happen,
for example, when a dialog box or another activity comes in front of the current one. In this method, you
should release resources that are not needed while the activity is paused, such as stopping animations or
releasing system resources like GPS or sensors.

5. **onStop():** This method is called when the activity is no longer visible to the user. It's where you
should stop or unregister any resources that were started or registered in onStart(). For example, you can
stop background services or release resources like camera or audio playback.

6. **onDestroy():** Called before the activity is destroyed. This is where you should release any
resources associated with the activity, such as unregistering broadcast receivers or freeing up resources
like network connections or database handles. This method is also a good place to save any final state
data that should be persisted beyond the activity's lifecycle.

Additionally, there's **onRestart():** This method is called when the activity is being restarted after
being stopped. It's followed by onStart().

Understanding and properly implementing these lifecycle methods is crucial for ensuring your app
behaves correctly across various scenarios and device configurations.
Q4. . Explain the need of Async Task and its call back methods along with the limitations of Async Task.
15 marks

A. syncTask is an abstract class in Android that offers us the freedom to


execute demanding tasks in the background while keeping the UI
thread light and the application responsive. When launched, an
Android application operates in a single thread. Due to this single-
thread approach, tasks that take a long time to fetch a response may
cause the program to become unresponsive.
We use Android AsyncTask to perform these heavy tasks in the
background on a separate thread and return the results back to the UI
thread in order to prevent this. As a result, the UI thread is alway
s responsive when AsyncTask is used in an Android application.

https://www.geeksforgeeks.org/asynctasks-in-android/

The limitations of AsyncTask include:

1. **Memory Leaks**: AsyncTask can lead to memory leaks if not handled properly, especially in
cases where the Activity or Fragment is destroyed while the task is still running.

2. **Configuration Changes**: AsyncTask can be problematic during configuration changes (like


screen rotation) since the AsyncTask instance might get tied to the previous Activity or Fragment,
leading to potential crashes or memory leaks.

3. **Not Suitable for Long-Running Tasks**: AsyncTask is not suitable for tasks that need to run
for an extended period, such as downloading large files or performing continuous background
operations, as it's tied to the Activity's lifecycle.

4. **Limited Control**: AsyncTask provides limited control over the execution of tasks, such as
cancellation and error handling.

5. **Not Suitable for Concurrent Tasks**: AsyncTask is designed for serial execution of tasks. If
you need to execute tasks concurrently, you'll need to use other mechanisms, such as
ThreadPoolExecutor or RxJava.

Q5. What is an Adapter? Explain its any two types 5 MRKS

A. In mobile application development, an adapter is a crucial component used to bind data to user
interface elements, such as lists or grids. It acts as a bridge between the data source and the UI
components, facilitating the display of data in a structured and presentable manner. Here are two
common types of adapters used in mobile app development:

1. **ArrayAdapter:**

- An ArrayAdapter is used when the data source is a simple array or a list of objects. It converts each
item within the array into a corresponding view to be displayed within a UI component, such as a
ListView or Spinner.

- This adapter is often used when dealing with static data or data that doesn't require complex
manipulation before being displayed.
- ArrayAdapter provides a simple way to bind data to views, but it may not be suitable for more
complex data structures or custom view layouts.

2. **RecyclerViewAdapter:**

- RecyclerViewAdapter is more flexible and efficient compared to ArrayAdapter. It is used in


conjunction with the RecyclerView widget, which provides more advanced features for displaying large
sets of data with dynamic content.

- This adapter allows for the implementation of complex layouts and custom view holders, making it
suitable for displaying data in various formats, such as lists, grids, or staggered grids.

- RecyclerViewAdapter also offers better performance optimizations, such as view recycling and
efficient scrolling, making it ideal for handling large datasets or data that frequently changes.

- Additionally, RecyclerViewAdapter supports different view types within the same RecyclerView,
enabling developers to create more dynamic and interactive user interfaces.

In summary, both ArrayAdapter and RecyclerViewAdapter play crucial roles in mobile app development
by facilitating the display of data within UI components. While ArrayAdapter is simpler and suitable for
basic data structures, RecyclerViewAdapter offers more flexibility, efficiency, and advanced features for
handling complex data and dynamic content.

Q6. Define Android. Explain its architecture in detail along with the diagram. 10 mrks

A. Android is an open-source operating system primarily designed for mobile devices such
as smartphones and tablets. It was developed by Google and the Open Handset Alliance,
a consortium of hardware, software, and telecommunication companies. Android is
based on the Linux kernel and provides a rich framework of APIs (Application
Programming Interfaces) that allow developers to create innovative and feature-rich
mobile applications.
Android Architecture:

Android's architecture is designed to be modular, flexible, and customizable,


allowing it to run on a wide range of devices with varying hardware capabilities. The
architecture can be broadly divided into four main layers:
1. Applications –
Applications is the top layer of android architecture. The pre-installed
applications like home, contacts, camera, gallery etc and third party
applications downloaded from the play store like chat applications, games
etc. will be installed on this layer only. It runs within the Android run time
with the help of the classes and services provided by the application
framework.
2. Application framework –
Application Framework provides several important classes which are used
to create an Android application. It provides a generic abstraction for
hardware access and also helps in managing the user interface with
application resources. Generally, it provides the services with the help of
which we can create a particular class and make that class helpful for the
Applications creation. It includes different types of services activity
manager, notification manager, view system, package manager etc. which
are helpful for the development of our application according to the
prerequisite.
3. Application runtime –
Android Runtime environment is one of the most important part of Android.
It contains components like core libraries and the Dalvik virtual
machine(DVM). Mainly, it provides the base for the application framework
and powers our application with the help of the core libraries. Like Java
Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based
virtual machine and specially designed and optimized for android to ensure
that a device can run multiple instances efficiently. It depends on the layer
Linux kernel for threading and low-level memory management. The core
libraries enable us to implement android applications using the standard
JAVA or Kotlin programming languages.
Note: Now, starting from Android 5.0 and above, we use ART (Android
Runtime) to compile bytecode into native code to leverage ahead-of-time
compilation.
4. Platform libraries –
The Platform Libraries includes various C/C++ core libraries and Java based
libraries such as Media, Graphics, Surface Manager, OpenGL etc. to provide
a support for android development.
• Media library provides support to play and record an audio and
video formats.
• Surface manager responsible for managing access to the display
subsystem.
• SGL and OpenGL both cross-language, cross-platform application
program interface (API) are used for 2D and 3D computer graphics.
• SQLite provides database support and FreeType provides font
support.
• Web-Kit This open source web browser engine provides all the
functionality to display web content and to simplify page loading.
• SSL (Secure Sockets Layer) is security technology to establish an
encrypted link between a web server and a web browser.
5. Linux Kernel –
Linux Kernel is heart of the android architecture. It manages all the available
drivers such as display drivers, camera drivers, Bluetooth drivers, audio
drivers, memory drivers, etc. which are required during the runtime. The
Linux Kernel will provide an abstraction layer between the device hardware
and the other components of android architecture. It is responsible for
management of memory, power, devices etc. The features of Linux kernel
are:
• Security: The Linux kernel handles the security between the
application and the system.
• Memory Management: It efficiently handles the memory
management thereby providing the freedom to develop our apps.
• Process Management: It manages the process well, allocates
resources to processes whenever they need them.
• Network Stack: It effectively handles the network communication.
• Driver Model: It ensures that the application works properly on the
device and hardware manufacturers responsible for building their
drivers into the Linux build.

Q7. What task should be carried out to run a simple application? Explain about emulator in
detail.

A. To run a simple application on Android, you'll need to follow these basic steps:

1. **Set Up Development Environment:**

- Install Android Studio, the official Integrated Development Environment (IDE) for Android app
development. Android Studio includes all the necessary tools, SDKs, and emulators needed for app
development.

- Once installed, launch Android Studio and set up the development environment by configuring
the SDK (Software Development Kit) and other necessary components.

2. **Create a New Project:**


- In Android Studio, create a new project by selecting "File" > "New" > "New Project". Follow the
wizard to configure your project settings such as project name, package name, and minimum SDK
version.

- Choose the activity template for your app (e.g., "Empty Activity", "Basic Activity") and proceed to
create the project.

3. **Write Your Code:**

- Android applications are written primarily in Java or Kotlin programming languages. Write the
code for your application's functionality, UI layout, and behavior using Android APIs and libraries.

4. **Build and Run:**

- After writing your code, build your project by selecting "Build" > "Make Project" from the Android
Studio menu.

- Once the build process is successful, run your application by selecting "Run" > "Run 'app'" or by
clicking the green "Play" button in the toolbar.

- Android Studio will compile your code, package it into an APK (Android Package), and deploy it
to a connected device or emulator.

5. **Testing and Debugging:**

- Test your application on various devices and screen sizes to ensure compatibility and
responsiveness.

- Use Android Studio's built-in debugging tools to identify and fix any issues in your code.

Now, let's delve into the emulator in detail:

### Emulator in Android Development:

An emulator is a software tool that mimics the behavior of a physical device, allowing developers to
test and debug their applications without the need for actual hardware. In Android development, the
Android Emulator provides a virtual environment for running and testing Android applications on a
computer.
#### Features of Android Emulator:

1. **Device Simulation:**

- The Android Emulator simulates various aspects of a physical Android device, including the
operating system, hardware components (e.g., CPU, memory, storage), sensors (e.g., accelerometer,
GPS), and network conditions.

- Developers can create virtual devices with different configurations such as screen size, resolution,
Android version, and hardware capabilities to test their applications under various scenarios.

2. **Testing Different Android Versions:**

- Android Emulator supports running multiple versions of the Android operating system, allowing
developers to test their applications on different API levels and platform versions.

- This enables developers to ensure backward and forward compatibility of their apps across a wide
range of Android devices.

3. **Debugging and Profiling:**

- Android Emulator integrates seamlessly with Android Studio's debugging and profiling tools,
allowing developers to debug their applications, monitor performance, and analyze behavior directly
within the emulator environment.

- Developers can set breakpoints, inspect variables, simulate sensor inputs, and analyze CPU and
memory usage to diagnose and fix issues in their code.

4. **Integration with Android Studio:**

- Android Emulator is tightly integrated with Android Studio, making it easy to create, configure,
launch, and manage virtual devices directly from the IDE.

- Developers can quickly deploy their applications to the emulator for testing and debugging
without needing to install additional software or drivers.

Overall, the Android Emulator is an essential tool in Android development, providing developers with
a convenient and efficient way to test their applications across different devices and configurations,
identify and fix bugs, and optimize performance before deploying them to real-world users.
Q8. explain (a) Broadcast Intents (b) Broadcast Receivers.

A. Sure, let's break down Broadcast Intents and Broadcast Receivers:

### Broadcast Intents:

In Android, a Broadcast Intent is a message that can be broadcasted system-wide by the Android
system or by applications to inform other components or applications about a particular event or
state change. It's a way for different parts of an app or different apps to communicate with each
other indirectly. Broadcast Intents are often used for system events, such as battery low warnings,
screen on/off events, network connectivity changes, etc.

Key points about Broadcast Intents:

1. **Action:** A Broadcast Intent specifies an action that describes the event being broadcasted. For
example, "android.intent.action.BATTERY_LOW" indicates that the battery is running low.

2. **Data:** Optionally, a Broadcast Intent can carry additional data (extras) to provide more
information about the event.

3. **Implicit or Explicit:** Broadcast Intents can be either implicit (not targeted at a specific
component) or explicit (targeted at a specific component).

4. **Ordered or Unordered:** Broadcast Intents can be sent as ordered broadcasts, where receivers
are notified sequentially and can modify or cancel the broadcast, or as unordered broadcasts, where
receivers are notified simultaneously.

5. **Permission:** Some Broadcast Intents may require permissions to be received, especially those
related to system events or sensitive information.

### Broadcast Receivers:

A Broadcast Receiver is an Android component that listens for Broadcast Intents and responds to
them by executing a predefined behavior. It acts as a gateway for receiving and processing
broadcasted messages. Applications can register Broadcast Receivers either statically in the
AndroidManifest.xml file or dynamically at runtime.

Key points about Broadcast Receivers:


1. **Lifecycle:** Broadcast Receivers have a short lifecycle. They are activated when a matching
broadcast is received and are typically destroyed after completing their task.

2. **Asynchronous:** Broadcast Receivers operate asynchronously, meaning they do not block the
main application thread. Long-running operations should be offloaded to background threads or
services.

3. **Registered Components:** Broadcast Receivers can be registered statically in the


AndroidManifest.xml file or dynamically at runtime using the registerReceiver() method.

4. **Intent Filters:** Broadcast Receivers specify intent filters to indicate which Broadcast Intents
they are interested in receiving. An intent filter includes actions, data types, categories, and
permissions.

5. **Ordering:** If multiple Broadcast Receivers are registered to receive the same broadcast, they
are invoked based on their priority, as well as whether the broadcast is ordered or unordered.

In summary, Broadcast Intents are messages used for system-wide communication, while Broadcast
Receivers are components responsible for listening to and responding to these broadcasted
messages. They facilitate loose coupling between different parts of an app or between different apps,
enabling them to communicate and coordinate effectively.

Q9. Define content providers and way to access content providers

A. Content Providers in Android are components that manage access to a structured set of data. They
encapsulate data and provide a standard interface for interacting with it, allowing different applications
to securely share and access the data. Content Providers are primarily used for data storage, retrieval,
and sharing across applications, making them a fundamental part of Android's data-sharing mechanism.

Key points about Content Providers:

1. **Data Abstraction:** Content Providers abstract the underlying data source, whether it's a SQLite
database, file system, network, or any other data storage mechanism.

2. **Data Access:** They provide a set of CRUD (Create, Read, Update, Delete) operations to interact
with the underlying data, enabling applications to insert, query, update, and delete data.

3. **URI-based Access:** Content Providers use Uniform Resource Identifiers (URIs) to identify data
resources and perform operations on them. URIs typically follow the "content://" scheme.

4. **Security:** Content Providers enforce permissions to control access to data. Applications must have
the appropriate permissions to read or write data through a Content Provider.

5. **Data Sharing:** Content Providers facilitate data sharing between different applications by allowing
them to access and manipulate shared data.
6. **Integration with Other Components:** They can be integrated with other Android components
such as Loaders, Cursors, and CursorAdapters to efficiently manage and display large datasets in UI
components.

### Accessing Content Providers:

There are two primary ways to access Content Providers in Android:

1. **Using ContentResolver:**

- The ContentResolver class is used to interact with Content Providers from within an application.

- To access data from a Content Provider, an application obtains a ContentResolver instance using the
getContentResolver() method.

- The ContentResolver provides methods such as query(), insert(), update(), and delete() to perform
CRUD operations on the Content Provider's data.

Example of accessing a Content Provider using ContentResolver:

2. **Using Loader Framework (Optional):**

- The Loader framework is a recommended approach for asynchronously loading data from a Content
Provider into UI components such as ListView or RecyclerView.

- Loaders are managed by the LoaderManager and automatically handle data loading, reloading, and
updates in response to Content Provider data changes.

- Loaders provide better performance and responsiveness by loading data asynchronously on a


background thread, preventing UI freezes.

Example of using Loader framework to access Content Provider data:

In summary, Content Providers are used to manage access to structured data in Android applications,
and they can be accessed using ContentResolver for CRUD operations or optionally using the Loader
framework for asynchronous data loading in UI components.
Q10.explain shared preferences 10 marks

A. https://www.geeksforgeeks.org/shared-preferences-in-android-with-examples/

Q11. Explain nested classes of shared preferences.(5)

A. In Android development, SharedPreferences is a mechanism used for storing key-value pairs


of primitive data types persistently. Nested classes within SharedPreferences provide a
convenient way to organize related functionality or improve code readability. Here's an
explanation of nested classes commonly used with SharedPreferences:

1. **Editor:**

- The Editor interface is a nested class within SharedPreferences that allows for modifying the
preferences data. It provides methods to insert, remove, or update key-value pairs within the
SharedPreferences object.

- This class is typically used to create an instance to edit the SharedPreferences data by calling
the edit() method on a SharedPreferences object.

- Example:

SharedPreferences preferences = context.getSharedPreferences("my_prefs",


Context.MODE_PRIVATE);

SharedPreferences.Editor editor = preferences.edit();

editor.putString("key", "value");

editor.apply(); // Commit the changes

```

2. **OnSharedPreferenceChangeListener:**

- The OnSharedPreferenceChangeListener interface is another nested class within


SharedPreferences. It defines a callback method that is invoked when a change is detected in
the SharedPreferences data.

- Developers can implement this interface to listen for changes in preference values and
perform appropriate actions in response to those changes.

- Example:
SharedPreferences.OnSharedPreferenceChangeListener listener = new
SharedPreferences.OnSharedPreferenceChangeListener() {

@Override

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String


key) {

// Handle preference change

};

preferences.registerOnSharedPreferenceChangeListener(listener);

These nested classes provide a structured way to interact with SharedPreferences in Android
applications. The Editor class facilitates the modification of preference values, while the
OnSharedPreferenceChangeListener class allows developers to react to changes in preference
values effectively. By utilizing these nested classes, developers can write cleaner and more
organized code when working with SharedPreferences.

Q13. Categrorize different types of adapter.(7)

A. In Android development, adapters are crucial components used to bind data to UI elements like
RecyclerViews, ListViews, GridViews, etc. Here are the main types of adapters commonly used in
Android:

Sure, let's delve deeper into each type of adapter in Android:

1. **ArrayAdapter**:

- It's a subclass of BaseAdapter that binds an array of data to a ListView or Spinner.

- It's straightforward to use and suitable for small datasets where the data is stored in an array or
ArrayList.

- ArrayAdapter handles the process of converting each item in the array into a view that can be
displayed within the ListView or Spinner.

2. **BaseAdapter**:

- BaseAdapter is an abstract class that provides a skeletal implementation of the Adapter interface.
- It's commonly subclassed to create custom adapters when ArrayAdapter or CursorAdapter isn't
sufficient for your needs.

- BaseAdapter gives you more control over the binding process, allowing you to define how data is
mapped to views and how views are recycled.

3. **CursorAdapter**:

- CursorAdapter is used to bind data from a database Cursor to a ListView.

- It's specifically designed to work with SQLite database queries, where the data is retrieved using a
Cursor object.

- CursorAdapter efficiently manages the movement of the Cursor and updates the ListView
accordingly as the underlying data changes.

4. **RecyclerView.Adapter**:

- RecyclerView.Adapter is used with RecyclerView, a more flexible and efficient replacement for
ListView and GridView.

- It's responsible for creating and binding views to items in a dataset.

- RecyclerView.Adapter provides methods for creating view holders, binding data to views, and
handling view recycling.

5. **PagerAdapters**:

- PagerAdapters are used with ViewPager, a UI component that allows users to swipe between
multiple pages.

- There are different implementations of PagerAdapter available, such as FragmentPagerAdapter


and FragmentStatePagerAdapter.

- PagerAdapters manage the lifecycle of pages displayed in the ViewPager and provide methods
for instantiating, destroying, and updating pages as the user interacts with the ViewPager.

6. **ListAdapter**:

- ListAdapter is an extension of RecyclerView.Adapter introduced in Android Jetpack's RecyclerView


library.

- It's optimized for efficiently updating UIs with large datasets by automatically computing
differences between old and new lists.
- ListAdapter is particularly useful when working with dynamic data sources that frequently change,
such as LiveData or RxJava streams.

Each type of adapter serves a specific purpose and offers different levels of flexibility, efficiency, and
convenience for binding data to UI elements in Android applications. Choosing the right adapter
depends on the requirements of your application and the characteristics of your data source.

Q14. Compare implicit and explicit intent 5 marks

A. In Android development, both implicit and explicit intents are mechanisms for communication
between different components of an application or between different applications. Here's a comparison
between implicit and explicit intents:

1. **Definition**:

- **Implicit Intent**: An implicit intent is used to activate components of other applications in your
device without specifying the exact component. For example, opening a web page or sending an email.

- **Explicit Intent**: An explicit intent is used to activate components within your own application or
to target a specific component within another application. You specify the exact component that should
be called.

2. **Target Component**:

- **Implicit Intent**: The target component is not explicitly defined. The Android system determines
the appropriate component based on the intent's action, data, and category.

- **Explicit Intent**: The target component is explicitly defined by providing the component's class
name or its package name.

3. **Usage**:

- **Implicit Intent**: Used when you want to delegate a task to another application or component
without knowing which application or component will handle it. For example, opening a URL in a web
browser.

- **Explicit Intent**: Used when you want to specifically target a particular component within your
own application or another application. For example, navigating from one activity to another within the
same app.
4. **Action**:

- **Implicit Intent**: Specifies a general action that should be performed, such as viewing, editing, or
sending data. The system then identifies the appropriate component capable of handling that action.

- **Explicit Intent**: Specifies the exact action and the target component that should perform that
action.

5. **Security**:

- **Implicit Intent**: Since the target component is not explicitly defined, there can be security
concerns as any application capable of handling the specified action can respond to the intent.

- **Explicit Intent**: Provides better security as only the specified component will respond to the
intent.

Q15. Thread and lifecycle

A. Threads on Android

Every Android application is started with numerous threads that are bundled with
the Linux process and the Dalvik VM to manage the internal execution of the
application. But the application is exposed to system threads like the UI and Binder
threads, and creates background threads of its own. It is now time to get in under the
hood of threading on the Android platform:

• Differences and similarities between UI, Binder and background threads.


• The Linux thread coupling.
• How thread scheduling is affected by the application process rank.
• Observe running Linux threads.
Android Application Threads

All application threads are based on the native pthreads in Linux with
a Thread representation in Java, but the platform still assigns special properties to
threads that make them differ. From an application perspective the thread types are
UI, binder, and background threads.

UI Thread

The UI thread is started when the application is started and stays alive during the
lifetime of the Linux process. The UI thread is the main thread of the application,
used for executing Android components and updating the UI elements on the screen.
If the platform detects that UI updates are attempted from any other thread, it will
promptly notify the application by throwing a CalledFromWrongThreadException.
This harsh platform behavior is required because the Android UI Toolkit is not
thread-safe, so the runtime allows access to the UI elements from one thread only.
Java is a multi-threaded programming language which means we can develop
multi-threaded program using Java. A multi-threaded program contains two or more
parts that can run concurrently and each part can handle a different task at the same
time making optimal use of the available resources specially when your computer
has multiple CPUs.
By definition, multitasking is when multiple processes share common processing
resources such as a CPU. Multi-threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single application
into individual threads. Each of the threads can run in parallel. The OS divides
processing time not only among different applications, but also among each thread
within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle
of a thread.

Following are the stages of the life cycle −


• New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task. A thread transitions back
to the runnable state only when another thread signals the waiting thread to
continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is waiting
for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order
in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread priorities
cannot guarantee the order in which threads execute and are very much platform
dependent.

Threading in Android

In Android, you can categorize all threading components into two basic categories:

1. Threads that are attached to an activity/fragment: These threads are


tied to the lifecycle of the activity/fragment and are terminated as soon as
the activity/fragment is destroyed.

2. Threads that are not attached to any activity/fragment: These threads


can continue to run beyond the lifetime of the activity/fragment (if any)
from which they were spawned.
1. Threading Components that Attach to an Activity/Fragment

AsyncTask

Loaders

2. Threading Components that Don’t Attach to an


Activity/Fragment

Service

Intent Service

For the above two threading components,There are five types of thread are using in
Android Mobile Development which areas:-

Main thread

UI thread

Worker thread

Any thread

Binder thread
Now Let’s discuss for threads one by one:-

1. Main thread:

When an application is launched in Android, it creates the first thread of execution,


known as the “main” thread. The main thread is responsible for dispatching events
to the appropriate user interface widgets as well as communicating with
components from the Android UI toolkit.

To keep your application responsive, it is essential to avoid using the main


thread to perform any operation that may end up keeping it blocked.
Network operations and database calls, as well as loading of certain components,
are common examples of operations that one should avoid in the main thread. When
they are called in the main thread, they are called synchronously, which means that
the UI will remain completely unresponsive until the operation completes. For
this reason, they are usually performed in separate threads, which thereby
avoids blocking the UI while they are being performed (i.e., they have
performed asynchronously from the UI).

2. UI thread:

Definition 1:

The UIThread is the main thread of execution for your application.


This is where most of your application code is run. All of your
application components (Activities, Services, ContentProviders,
BroadcastReceivers) are created in this thread, and any system
calls to those components are performed in this thread.

For instance, let’s say your application is a single Activity class.


Then all of the lifecycle methods and most of your event handling
code is run in this UIThread. These are methods
like onCreate, onPause, onDestroy, onClick, etc. Additionally, this is where
all of the updates to the UI are made. Anything that causes the UI
to be updated or changed HAS to happen on the UI thread.

When you explicitly spawn a new thread to do work in the


background, this code is not run on the UIThread. So what happens
if this background thread needs to do something that changes the
UI? This is what the runOnUiThread is for. Actually you're supposed to
use a Handler. It provides these background threads the ability to
execute code that can modify the UI. They do this by putting the UI-
modifying code in a Runnable object and passing it to the
runOnUiThread method.

Definition 2:

UI Thread allows your tasks to do background work and then


move the results to UI elements such as bitmaps.

Every app has its own special thread that runs UI objects such
as View objects, This thread is called the UI thread. Only objects
running on the UI thread have access to other objects on that
thread. Because tasks that you run on a thread from a thread
pool aren't running on your UI thread, they don't have access to UI
objects. To move data from a background thread to the UI thread,
use a Handler that's running on the UI thread.

3. Worker thread:
Worker threads are background threads. They are the threads that
are created separately, other than the UI thread. Since blocking the
UI thread is restricted according to the rule, the user should run the
child processes and tasks in worker threads.

An example of the creation and working of worker thread is given


below:-

Public void onClick(View v) { new Thread(new Runnable() {

public void run() {

Bitmap b =
loadImageFromNetwork(“http://example.com/image.png");

mImageView.setImageBitmap(b);}

}).start(); }
In the above example code, the download operation is handled by
a second thread other than the UI thread. But the program violates
the second rule. The image View from UI thread is manipulating
from this worker thread.

According to the second rule, UI could not be accessed from outside


the UI thread. The solution for such a restriction is
runOnUiThread(Runnable) method. The main or UI thread can be
accessed from other threads using runOnUiThread(Runnable)
method.

As a result, the specified runnable action passed through this


method will run on the UI thread. The action will execute
immediately if the current thread is in the UI itself. Else the action
will be posted to the event queue.

4. Any thread:
@Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.VALUE_PARAMETER])
class Any Thread

Denotes that the annotated method can be called from any thread
(e.g. it is “thread-safe”.) If the annotated element is a class, then all
methods in the class can be called from any thread.

The main purpose of this method is to indicate that you believe a


method can be called from any thread; static tools can then check
that nothing you call from within this method or class has more
strict threading requirements.

Example:
<code>

@AnyThread

public void deliverResult(D data) { ... }

</code>

5. Binder thread:
Definition 1:

Binder thread represents a separate thread of your service. Binder


is a mechanism that provides Inter-Process Communication.

Let’s consider an example. Imagine that you have service Process B


(see picture). And you have several applications that communicate
with this service B (one of this application is, for instance, Process
A). Thus, one service B should provide different results
simultaneously to different applications. Thus, you need to run
several replicas of Service B for different applications. Android runs
these replicas in different threads of Process B and these threads
are called “Binder Thread #N”.
Definition 2:

Binder Thread is used in Android Service Binding with


Interprocess Communication. Most of the time you will encounter
this concept in Service calls with interfaces defined by Android
Interface Definition Language (AIDL).

In the AIDL case, Service calls are executed by threads maintained


by a default Thread Pool created with your application. Those
threads are called Binder Threads. This grants the Service
the ability to work on multiple calls happening at the same time.

Usually, Service calls with the interface defined by “Extending the


Binder class” and “Using a Messenger” are executed sequentially
in one thread.

Q16. .compare Sql DML and DDL.(7)

A. Sure, here's a comparison of SQL DML (Data Manipulation Language) and DDL (Data

Definition Language):

1. **Purpose**:

- DDL: Data Definition Language is used to define the structure of the database schema

such as creating, altering, or dropping database objects like tables, indexes, etc.
- DML: Data Manipulation Language is used to manipulate data within the database like

inserting, updating, deleting, and retrieving data from the tables.

2. **Operations**:

- DDL: DDL operations include CREATE, ALTER, and DROP. These operations are

used to create, modify, or delete the structure of the database objects.

- DML: DML operations include SELECT, INSERT, UPDATE, and DELETE. These

operations are used to manipulate the data stored in the database.

3. **Effects**:

- DDL: DDL statements directly affect the structure of the database schema. For

example, creating a table, altering its structure, or dropping it entirely.

- DML: DML statements affect the data stored within the database. For example,

inserting new records, updating existing records, or deleting records from a table.

4. **Transactions**:

- DDL: DDL statements typically implicitly commit the current transaction. This means

that changes made by DDL statements are automatically committed and cannot be rolled

back.
- DML: DML statements are usually part of a transaction that can be committed to make

changes permanent or rolled back to revert the changes.

5. **Usage**:

- DDL: DDL is used by database administrators or developers to design and manage the

structure of the database.

- DML: DML is used by application developers or users to interact with the data stored

in the database.

6. **Examples**:

- DDL:

- CREATE TABLE Employees (id INT, name VARCHAR(50), salary DECIMAL(10,

2));

- ALTER TABLE Employees ADD COLUMN age INT;

- DROP TABLE Employees;

- DML:

- INSERT INTO Employees (id, name, salary, age) VALUES (1, 'John Doe', 50000, 30);

- UPDATE Employees SET salary = 55000 WHERE id = 1;


- DELETE FROM Employees WHERE id = 1;

7. **Control**:

- DDL: DDL statements are used to control the structure and organization of data in the

database.

- DML: DML statements are used to control the content and manipulation of data in the
database.

In summary, DDL is concerned with the structure of the database, while DML is concerned

with the manipulation of data within that structure.

You might also like