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

Android Notes

AVD (Android Virtual Device) is an emulator configuration that allows developers to test and debug Android applications on various device types without physical hardware. The process of creating an AVD in Android Studio involves steps such as accessing the AVD Manager, selecting a hardware profile, choosing a system image, configuring the AVD settings, and launching the emulator. Additionally, the document discusses the activity lifecycle in Android, various layout types, the use of Spinner for user selection, and the distinction between activities and services.

Uploaded by

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

Android Notes

AVD (Android Virtual Device) is an emulator configuration that allows developers to test and debug Android applications on various device types without physical hardware. The process of creating an AVD in Android Studio involves steps such as accessing the AVD Manager, selecting a hardware profile, choosing a system image, configuring the AVD settings, and launching the emulator. Additionally, the document discusses the activity lifecycle in Android, various layout types, the use of Spinner for user selection, and the distinction between activities and services.

Uploaded by

rrdr1530
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/ 36

Q1.What Is AVD?

Explain The Process of Creating AVD in Android Application


Development.
AVD stands for Android Virtual Device, a key component in the Android
application development environment. It is an emulator configuration that models a
physical Android device, enabling developers to test and debug applications on
different Android versions and device types without needing the actual hardware.
AVDs are managed through the Android Emulator, which is bundled with Android
Studio, the official IDE for Android development. The emulator mimics all the
hardware and software features of a real Android device, allowing developers to
simulate incoming calls, messages, GPS locations, and other interactions.
An Android Virtual Device (AVD) is an emulator configuration that allows
developers to test the application by simulating the real device capabilities. We can
configure the AVD by specifying the hardware and software options. AVD manager
enables an easy way of creating and managing the AVD with its graphical interface.
We can create as many AVDs as we need, based on the types of devices we want to
test for.
AVD plays a critical role in Android development by offering a flexible, powerful,
and cost-effective way to test and debug applications across a wide variety of device
configurations. With the support of Android Studio’s intuitive interface, creating
and managing AVDs becomes a seamless part of the development lifecycle.
Step-by-Step Process to Create an AVD in Android Studio
Here is a detailed breakdown of the steps required to create an Android Virtual
Device:
Step 1: Open Android Studio
• Launch Android Studio on your machine.
• Ensure the Android SDK is installed and up to date.
Step 2: Access AVD Manager
• Go to the top menu bar: Tools → Device Manager or click the Device Manager
icon on the toolbar.
• This opens the Device Manager/AVD Manager window.

Step 3: Create a New Virtual Device


• Click on “+ Create Device”.
• A window will appear to select the hardware profile.
• Choose a predefined device (e.g., Pixel 6, Nexus 5, 7” Tablet, etc.).
• You can also define custom hardware profiles if required.
• Click Next.
Step 4: Select a System Image
• Choose a system image corresponding to the Android version you want to
emulate (e.g., Android 13 - API 33, Android 14 - API 34).
• You can choose between images based on architecture: x86, ARM, x86_64
(recommended for performance).
• Download the image if not already installed.
• Click Next.
Step 5: Configure Your AVD
• Name your virtual device (e.g., "Pixel_API_34").
• Customize the following:
o Orientation (Portrait or Landscape)
o Startup Settings (Cold Boot or Quick Boot)
o Graphics Rendering (Hardware or Software)
o RAM and Storage
o SD Card Size (optional)
• Optionally enable or disable:
o Camera (front/back - emulator or host webcam)
o Network latency or speed emulation
o GPS location simulation
• Click Finish to create the AVD.
Step 6: Launch the AVD
• In the Device Manager, click the Play icon (green triangle) next to the device
name.
• The AVD will boot and display an emulated Android OS screen.
Importance and Purpose of AVD in Android Development
Multi-device Testing: Developers can simulate multiple devices with different
screen sizes, resolutions, RAM, and Android API levels.
Cost Efficiency: No need to purchase dozens of physical devices for testing.
Virtual devices cover most scenarios.
Debugging & Troubleshooting: Easier to reproduce and fix bugs that might occur
only on specific Android versions or hardware setups.
Q2.Draw and Explain Activity Life Cycle in Detail.
In Android, an activity is referred to as one screen in an application. It is very
similar to a single window of any desktop application. An Android app consists of
one or more screens or activities.
Each activity goes through various stages or a lifecycle and is managed by activity
stacks. So, when a new activity starts, the previous one always remains below it.
There are four stages of an activity.
1. If an activity is in the foreground of the screen i.e at the top of the stack, then it is
said to be active or running. This is usually the activity that the user is currently
interacting with.
2. If an activity has lost focus and a non-full-sized or transparent activity has
focused on top of your activity. In such a case either another activity has a higher
position in multi-window mode or the activity itself is not focusable in the
current window mode. Such activity is completely alive.
3. If an activity is completely hidden by another activity, it is stopped or hidden. It
still retains all the information, and as its window is hidden thus it will often be
killed by the system when memory is needed elsewhere.
4. The system can destroy the activity from memory by either asking it to finish or
simply killing its process. When it is displayed again to the user, it must be
completely restarted and restored to its previous state.
For each stage, android provides us with a set of 7 methods that have their own
significance for each stage in the life cycle. The image shows a path of migration
whenever an app switches from one state to another.
Detailed introduction on each of the method is stated as follows:
1. onCreate(): It is called when the activity is first created. This is where all the static
work is done like creating views, binding data to lists, etc. This method also
provides a Bundle containing its previous frozen state, if there was one.
2. onStart(): It is invoked when the activity is visible to the user. It is followed by
onResume() if the activity is invoked from the background. It is also invoked after
onCreate() when the activity is first started.
3. onRestart(): It is invoked after the activity has been stopped and prior to its
starting stage and thus is always followed by onStart() when any activity is revived
from background to on-screen.
4. onResume(): It is invoked when the activity starts interacting with the user. At
this point, the activity is at the top of the activity stack, with a user interacting with
it. Always followed by onPause() when the activity goes into the background or is
closed by the user.
5. onPause(): It is invoked when an activity is going into the background but has not
yet been killed. It is a counterpart to onResume(). When an activity is launched in
front of another activity, this callback will be invoked on the top activity (currently
on screen). The activity, under the active activity, will not be created until the active
activity's onPause() returns, so it is recommended that heavy processing should not
be done in this part.
6. onStop(): It is invoked when the activity is not visible to the user. It is followed
by onRestart() when the activity is revoked from the background, followed by
onDestroy() when the activity is closed or finished, and nothing when the activity
remains on the background only. Note that this method may never be called, in low
memory situations where the system does not have enough memory to keep the
activity's process running after its onPause() method is called.
7. onDestroy(): The final call received before the activity is destroyed. This can
happen either because the activity is finishing (when finish() is invoked) or because
the system is temporarily destroying this instance of the activity to save space. To
distinguish between these scenarios, check it with isFinishing().
Q3. List out various layouts available in android app. Explain with example.
Layouts in Android define the user interface and hold UI controls or widgets that
appear on the screen of an application. Every Android application consists of View
and ViewGroup elements. Since an application contains multiple activities—each
representing a separate screen—every activity has multiple UI components, which
are instances of View and ViewGroup. These components are structured using a
hierarchy of View and ViewGroup objects.
View and ViewGroup
A View is defined as an interactive U which is used to create interactive UI
components such as TextView, ImageView, EditText, RadioButton, etc., and is
responsible for event handling and drawing. They are Generally Called Widgets.

A ViewGroup act as a base class for layouts and layouts parameters that hold other
Views or ViewGroups and to define the layout properties. They are generally Called
layouts.

The Android framework will allow us to use UI elements or widgets in two ways:
• Use UI elements in the XML file
• Create elements in the Kotlin file dynamically
Types of Android Layout
• Android Linear Layout: LinearLayout is a ViewGroup subclass, used to
provide child View elements one by one either in a particular direction either
horizontally or vertically based on the orientation property.
• Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to
specify the position of child View elements relative to each other like (A to the
right of B) or relative to the parent (fix to the top of the parent).
• Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used
to specify the position of layout constraints for every child View relative to
other views present. A ConstraintLayout is similar to a RelativeLayout, but
having more power.
• Android Frame Layout: FrameLayout is a ViewGroup subclass, used to
specify the position of View elements it contains on the top of each other to
display only a single View inside the FrameLayout.
• Android Table Layout: TableLayout is a ViewGroup subclass, used to display
the child View elements in rows and columns.
• Android Web View: WebView is a browser that is used to display the web
pages in our activity layout.
• Android ListView: ListView is a ViewGroup, used to display scrollable lists
of items in a single column.
• Android Grid View: GridView is a ViewGroup that is used to display a
scrollable list of items in a grid view of rows and columns.
How to create a layout?
Here, we can create a layout similar to web pages. The XML layout file contains at
least one root element in which additional layout elements or widgets can be added
to build a View hierarchy. Following is an example.
activity_main.xml:
Q4. How To Use Spinner In Android App? Explain With Example.
Android Spinner is a view similar to the dropdown list which is used to select one
option from the list of options. It provides an easy way to select one item from the
list of items and it shows a dropdown list of all values when we click on it. The
default value of the android spinner will be the currently selected value and by
using Adapter we can easily bind the items to the spinner objects. Generally, we
populate our Spinner control with a list of items by using an ArrayAdapter in our
Kotlin/Java file.
In Android, a Spinner is a UI (User Interface) control that allows the user to select
one value from a dropdown list. It is similar to a ComboBox in other programming
languages or a select tag in HTML. Only the selected item is visible until the user
clicks on the spinner to view all available options.
To use a Spinner in your Android app, follow these steps:

1. Add Spinner to XML Layout


In your activity_main.xml or any layout file:
<Spinner
android:id="@+id/spinner_example"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

2. Prepare the Data (Array of Items)


You can define the data in two ways:
Option A: In strings.xml
<string-array name="items_array">
<item>Apple</item>
<item>Banana</item>
<item>Mango</item>
<item>Orange</item>
</string-array>
Spinner Implementation in Java
Below is a complete example using Java:
Step 1: Setup Spinner and Data in MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Step 1: Link Spinner with layout
spinner = findViewById(R.id.spinner_example);
// Step 2: Define Data Source (can also be from strings.xml)
String[] fruits = {"Apple", "Banana", "Mango", "Orange"};
// Step 3: Create an Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this,
android.R.layout.simple_spinner_item,
fruits
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_i
tem);
// Step 4: Set Adapter to Spinner
spinner.setAdapter(adapter);
// Step 5: Handle Spinner item selection
spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), "Selected: " + selectedItem,
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Optional: What to do when nothing is selected
}
});
}
}
Advantages of Using Spinner
Advantage Explanation
Space Efficient Shows only selected value, dropdown on demand
User-Friendly Easy and intuitive for users
Flexible Works with arrays, lists, and custom data
Customizable Can be styled with custom adapters

Limitations
• Does not allow multi-selection
• Not ideal for large data sets unless customized

A Spinner is a powerful and easy-to-use Android widget that allows users to select
one item from a list of choices. With the help of ArrayAdapter and
OnItemSelectedListener, developers can easily bind data and respond to user
interactions.
Q5. what is service. Differentiate between activity and service.
A Service is a component of an application that may conduct long-running activities
in the background. It does not have a graphical user interface. A service that has
been started may continue to run for some time after the user changes to another
program. A component can also bind to a service in order to communicate with it
and even execute interprocess communication (IPC). A service, for example, can
conduct network transactions, play music, execute file I/O, and communicate with a
content provider in the background. Let's understand it further in a more granular
manner:
Services are a unique component in Android that allows an application to run in the
background to execute long-running operation activities, on the other hand, an
activity, like a window or a frame in Java, represents a single screen with a user
interface. The Android activity class is a subclass of the ContextThemeWrapper
class.
A Service provides great flexibility by having three different types. They are
Foreground, Background, and Bound.
Foreground
A foreground service performs operations that is noticeable to the user. For
example, a foreground service would be playing audio. A foreground service
continues to run even when the user is not interacting with your app. It is important
to note that foreground services must display a status bar icon.
Background
A background service performs an operation that is not directly noticeable by the
user. For example, a service that compacts its storage or updates a database.
Bound: A service is bound when an application component binds to it through the
bindService() function. Bound service offers a client-server interface that allows an
application component to interact with the service, send requests, receive requests,
and even do so with interprocess communication (IPC).
Unlike other types of services, a bound service runs as long as another application
service is bound to it. For example, multiple components can bind to the service at
once, but when all the components unbind, the service is destroyed.
Lifecycle of a Service: The basic lifecycle methods of a Service include:
• onCreate(): Called when the service is first created.
• onStartCommand(): Called every time the service is started using startService().
• onBind(): Called when another component binds to the service (only for bound
services).
• onDestroy(): Called when the service is stopped.
Aspect Activity Service
Definition Represents a single screen A component that runs in the
with a user interface background to perform long-
running operations
User Interface Has a UI and interacts with Does not have a UI; runs in
the user background
Component Foreground (UI) component Background component
Type
Use Case Used for interacting with the Used for background tasks
user (e.g., login, dashboard) (e.g., music playback, file
download)
Lifecycle onCreate(), onStart(), onCreate(),
Methods onResume(), onPause(), onStartCommand(), onBind(),
onStop(), onDestroy() onDestroy()
User Interaction Allows direct user No direct user interaction
interaction
Runs in Foreground (UI thread) Background (still on the main
thread unless threaded
manually)
Starts With startActivity(Intent) startService(Intent) or
bindService(Intent,
ServiceConnection, int)
Termination Can be finished using Needs to be stopped
finish() or system action explicitly using stopService()
or stopSelf()
Multitasking Cannot run without being in Can continue running when
the foreground (unless the user moves to another
minimized) app
Return Result Can return data to another Typically does not return
Activity via data (unless it's a Bound
startActivityForResult() Service)
Resource Usage Heavyweight component — Lightweight — more
consumes more resources optimized for background
tasks
Example Login form, Profile page, Music streaming, Syncing
Settings screen data, Location tracking
Back Stack Stored in the activity stack Not part of back stack; not
and managed by the back affected by back button
button
Threading Runs on the UI thread by Also runs on the UI thread
default unless handled with a thread
(e.g., Handler, AsyncTask,
IntentService)
Notification Optional Mandatory for Foreground
Requirement Services (e.g., a music player
showing a persistent
notification)
Visibility to User Always visible unless Often invisible unless user is
minimized notified via status bar or
notification
Communication Uses Intents and Bundles Bound services can use AIDL
or Binder for IPC (Inter-
Process Communication)
Q6. Short Notes:
1.Widget
In Android, a Widget (also known as an App Widget) is a miniature application
view that can be embedded on the home screen or lock screen of the device. It
provides quick access to app information and functions without opening the full
app.
Widgets are an essential aspect of home screen customization. You can think of
them as "at-a-glance" views of an app's most important data and functionality that
are accessible right on the user's home screen. Users can move widgets across their
home screen panels, and, if supported, resize them to tailor the amount of
information in the widget to their preference.
Features of Widgets
• Display real-time information (e.g., weather, clock, calendar).
• Provide quick actions (e.g., play music, check email).
• Can be interactive (e.g., buttons, scrollable lists).
• Automatically update data (using timers or broadcasts).

Widget types
Information widgets typically display crucial information elements and track how
that information changes over time. Examples of information widgets are weather
widgets, clock widgets, or sports score tracking widgets. Tapping information
widgets typically launches the associated app and opens a detailed view of the
widget information.
Collection widgets
Collection widgets specialize in displaying multiple elements of the same type, such
as a collection of pictures from a gallery app, a collection of articles from a news
app, or a collection of emails or messages from a communication app. Collection
widgets can scroll vertically.
Collection widgets typically focus on the following use cases:
• Browsing the collection.
• Opening an element of the collection to its detail view in the associated app.
• Interacting with elements, such as marking them done—with support for
compound buttons in Android 12 (API level 31).
Control widgets

The main purpose of a control widget is to display frequently used functions so that
the user can trigger them from the home screen without having to open the app.
You can think of them as remote controls for an app. An example of a control
widget is a home control widget that lets users turn lights in the house on or off.

Interacting with a control widget might open an associated detail view in the app.
This depends on whether the control widget's function outputs any data, such as in
the case of a search widget.

Hybrid widgets

While some widgets represent one of the types in the preceding sections—
information, collection, or control—many widgets are hybrids that combine
elements of different types. For example, a music player widget is primarily a
control widget, but it also shows the user what track is currently playing, like an
information widget.
Advantages of Widgets
• Quick access to important data.
• Improves user experience without opening the full app.
• Saves time and reduces user interaction steps.
• Enhances app engagement.
Example Widget XML (res/xml/widget_info.xml)
<appwidget-provider
android:minWidth="250dp"
android:minHeight="100dp"
android:updatePeriodMillis="60000"
android:initialLayout="@layout/widget_layout" />
Limitations of Widgets
• Limited UI elements (uses RemoteViews, not full layouts).
• Complex to handle user interactions compared to activities.
• Frequent updates may consume battery and resources.
2. Content Resolver
In Android, the Content Resolver is a class (android.content.ContentResolver) that
acts as a bridge between an application and a content provider. It provides
methods to access, modify, insert, delete, and query data managed by content
providers.
It is the main interface to access shared data from other apps or databases using
Content Providers.
The Content Resolver is a powerful Android component that enables applications
to securely access and manage shared data through content providers. It supports a
unified interface for interacting with data across applications, making it essential for
Android data management.
Implementing contentResolver.

Role of Content Resolver


• Interacts with Content Providers using URI-based requests.
• Manages inter-process communication (IPC) for data sharing.
• Used to retrieve data like contacts, media, messages, and more.

Common Methods in Content Resolver

Method Description
query() Read data from a content provider
insert() Insert a new record
update() Modify existing data
delete() Remove data
getType() Get MIME type of data at a URI
openInputStream() Read binary data from a URI
How to Use Content Resolver (Example)

To read contacts using ContentResolver:

ContentResolver resolver = getContentResolver();

Cursor cursor = resolver.query(

ContactsContract.Contacts.CONTENT_URI,

null, null, null, null

);

if (cursor != null) {

while (cursor.moveToNext()) {

String name =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NA
ME));

Log.d("ContactName", name);

cursor.close();

}
Use Cases of Content Resolver
• Accessing contacts, images, SMS, calendar, etc.
• Sharing data between applications.
• Reading media files or documents using system apps.
Advantages
• Encapsulated access to data.
• Works across different apps and processes.
• Supports standard CRUD operations.

Limitations
• Requires permissions to access certain data (e.g., READ_CONTACTS).
• Can be slow for large datasets if not optimized.
• Limited to ContentProvider-backed data.
3.Fragment In Android

Fragment is a piece of an activity that enables a more modular activity design. A


fragment encapsulates functionality so that it is easier to reuse within activities and
layouts. Android devices exist in a variety of screen sizes and densities. Fragments
simplify the reuse of components in different layouts and their logic. You can

build single-pane layouts for handsets (phones) and multi-pane layouts for tablets.
You can also use fragments also to support different layouts for landscape and
portrait orientation on a smartphone. The below image shows the use cases of
fragments through navigations.

Fragment Lifecycle

Android fragments have their own lifecycle very similar to an android activity.

• onAttach(): The fragment instance is associated with an activity instance. The


fragment and the activity is not fully initialized. Typically you get in this method
a reference to the activity which uses the fragment for further initialization work.

• onCreate(): The system calls this method when creating the fragment. You
should initialize essential components of the fragment that you want to retain
when the fragment is paused or stopped, then resumed.

• onCreateView() : The system calls this callback when it's time for the fragment to
draw its user interface for the first time. To draw a UI for your fragment, you
must return a View component from this method that is the root of your
fragment's layout. You can return null if the fragment does not provide a UI.

• onActivityCreated() : The onActivityCreated() is called after the onCreateView()


method when the host activity is created. Activity and fragment instance have
been created as well as the view hierarchy of the activity. At this point, view can
be accessed with the findViewById() method. example. In this method you can
instantiate objects which require a Context object
• onStart(): The onStart() method is called once the fragment gets visible.

• onResume(): Fragment becomes active.

• onPause(): The system calls this method as the first indication that the user is
leaving the fragment. This is usually where you should commit any changes that
should be persisted beyond the current user session.

• onStop(): Fragment going to be stopped by calling onStop()

• onDestroyView(): Fragment view will destroy after call this method

• onDestroy(): called to do final clean-up of the fragment's state but Not


guaranteed to be called by the Android platform.

Types of Fragments

• Single frame fragments: Single frame fragments are using for hand hold
devices like mobiles, here we can show only one fragment as a view.

• List fragments: fragments having special list view is called as list fragment

• Fragments transaction: Using with fragment transaction. we can move one


fragment to another fragment.

Handling the Fragment Lifecycle: A Fragment exist in three states:

• Resumed: The fragment is visible in the running activity.

• Paused: Another activity is in the foreground and has focus, but the activity in
which this fragment lives is still visible (the foreground activity is partially
transparent or doesn't cover the entire screen).

• Stopped: The fragment is not visible. Either the host activity has been stopped
or the fragment has been removed from the activity but added to the back
stack. A stopped fragment is still alive (all state and member information is
retained by the system). However, it is no longer visible to the user and will be
killed if the activity is killed.
4.Navigation Drawer in Android

The navigation drawer is the most common feature offered by Android and the
navigation drawer is a UI panel that shows your app's main navigation menu. It is
also one of the important UI elements, which provides actions preferable to the
users, for example changing the user profile, changing the settings of the
application, etc. In this article, it has been discussed step by step to implement the
navigation drawer in Android. The code has been given in both Java and Kotlin
Programming Language for Android.

The user can view the navigation drawer when the user swipes a finger from the left
edge of the activity. They can also find it from the home activity by tapping the app
icon in the action bar. The drawer icon is displayed on all top-level destinations that
use a DrawerLayout. Have a look at the following image to get an idea about the
Navigation drawer.

A Navigation Drawer is a UI panel that slides in from the left edge of the screen
and displays the main navigation options of the app. It allows users to navigate
between different sections or features of an app.

It is part of Material Design guidelines and is commonly used in apps like Gmail,
YouTube, and Facebook.

Key Features

• Provides quick access to app destinations.


• Can be opened by swiping from the left or by tapping a hamburger icon (☰).
• Remains hidden until triggered.
• Can contain menu items, headers, profile info, etc.

Components Used in Navigation Drawer

Component Description
DrawerLayout The root layout that supports a drawer and main
content.
NavigationView A view inside DrawerLayout that holds the menu items.
AppBarLayout / Top bar with a hamburger icon to toggle the drawer.
Toolbar
Menu Resource XML file (menu.xml) that defines the items inside the
drawer.

Basic Layout Structure (XML)

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/drawer_layout"

android:layout_width="match_parent"

android:layout_height="match_parent">

<!-- Main Content -->

<FrameLayout

android:id="@+id/content_frame"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

<!-- Navigation Drawer -->

<com.google.android.material.navigation.NavigationView

android:id="@+id/nav_view"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:layout_gravity="start"

app:menu="@menu/drawer_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

Advantages
• Enhances navigation and user experience.
• Frees up screen space by hiding navigation options.
• Follows Material Design guidelines.
• Easy to implement with DrawerLayout and NavigationView.
Q7. Build an app with button that displays a message when clicked.

This code is an example of an Android app that demonstrates the use of a button
click event and a Toast message. The app contains a layout with a button and a text
field.
An Android demo application is a small, functional app designed to showcase
specific features or learn a particular aspect of Android development. The button
click event is one of the simplest and most commonly used events in Android,
where clicking a button triggers a predefined action, such as displaying a message
or navigating to a new screen.
🔺The onCreate() method initializes the button and text field.
🔺The setOnClickListener() method is used to set an event listener on the button
that listens for click events.
🔺When the button is clicked, a Toast message is displayed with the text entered in
the text field.
🔺The findViewById() method is used to get a reference to the button and text
field views, using their resource IDs.
🔺The getText().toString() method is used to get the text entered in the text field
and store it in a string variable.
🔺Finally, the makeText() method is used to create a Toast message that displays
the entered text, and the show() method is called to display the message.
How Does a Button Click Event Work in Android?
When a user clicks a button in an Android app:
• The Button widget detects the click.
• An OnClickListener attached to the button is invoked.
• The listener triggers the onClick() method, where you define the action to
execute.
Example Action:
• Displaying a Toast message.
• Changing text in a TextView.
• Starting a new activity.
Step-by-Step Guide to Setting Up an Android Demo App
Follow these steps to create your first Android application with a button click event:
1. Set Up Your Development Environment
• Install Android Studio, the official IDE for Android development.
• Ensure you have the necessary SDK and emulator configurations.
2. Create a New Project
1. Open Android Studio.
2. Select File > New Project.
3. Choose an Empty Activity and click Next.
4. Name your project (e.g., ButtonClickDemo) and select a package name.
5. Click Finish to generate your project files.
3. Design the User Interface
• Open the activity_main.xml file.
• Add a Button and TextView to your layout using XML:

4.Add Functionality with Java


• Open the MainActivity.java or MainActivity.kt file.
• Add an OnClickListener to handle the button click event.
Java Code:

Common Issues and Solutions

• Button Not Responding:


• Ensure you’ve set the correct id for your button in the XML layout.
• Verify the setOnClickListener code is correctly implemented.
• App Crashes on Launch:
• Check for typos in findViewById or missing references in the XML file.
• UI Layout Issues:
• Use Android Studio’s Design Editor to adjust margins and alignments.

Q8. Implement a small database to store user information.

SQLite and Room are both database solutions for Android applications, but they
serve different purposes and offer different features. While SQLite is a powerful and
widely-used database engine, Room offers a higher-level abstraction, better
developer experience, and improved support for modern Android development
practices. Room is particularly beneficial for developers who prefer an ORM
approach, value compile-time safety, and want to take advantage of the Android
Architecture Components.

Room database has some extra advantages which SQLite do not provide, such as:

Compile-Time Verification: Room provides compile-time verification of SQL


queries. If there are any issues with your queries, the compiler catches them during
the build process, reducing the chance of runtime errors.

LiveData and RxJava Integration: Room integrates seamlessly with LiveData and
RxJava. This allows you to observe changes in the database and automatically
update the UI when the data changes, making it easier to implement reactive UIs.

Step 1: Add Room Database Dependencies

In your app-level build.gradle file, add the following dependencies:

implementation "androidx.room:room-runtime:2.6.1"
annotationProcessor "androidx.room:room-compiler:2.6.1"

Step 2: Create the Entity Class

Define the structure of your User entity class, representing the user profile
information.

@Entity(tableName = "user_table")
public class User {
@PrimaryKey(autoGenerate = true)
public int id;

@ColumnInfo(name = "login_id")
public String loginId;
@ColumnInfo(name = "password")
public String password;

@ColumnInfo(name = "full_name")
public String fullName;

@ColumnInfo(name = "contact")
public String contact;
}

Step 3: Create the DAO (Data Access Object)

Define the Data Access Object interface to perform CRUD operations on the User
entity.

@Dao
public interface UserDao {
@Insert
void insert(User user);

@Update
void update(User user);

@Delete
void delete(User user);

@Query("SELECT * FROM user_table WHERE login_id = :userId")


User getUserByLoginId(String userId);

@Query("SELECT * FROM user_table")


List<User> getAllUsers();
}

tep 4: Create the Room Database

Build the Room Database by extending RoomDatabase and include the DAO.

@Database(entities = {User.class}, version = 1, exportSchema = false)


public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();

private static volatile AppDatabase INSTANCE;

public static AppDatabase getDatabase(final Context context) {


if (INSTANCE == null) {
synchronized (AppDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, DbConfig.ROOM_DB_NAME)
.build();
}
}
}
return INSTANCE;
}
}

Step 5: Implement CRUD Operations in Your Application

In your activities or fragments, use the UserDao methods to perform database


operations.

Step 6: Initialize the Database

Initialize the database in your application class or the entry point of your app.

public class InitDb extends Application {


public static AppDatabase appDatabase;

@Override
public void onCreate() {
super.onCreate();
appDatabase = AppDatabase.getDatabase(this);
}
}

Step 7: Create an Activity

In this example, we’re creating a login activity class to perform the database task.
But one important thing you must notice, performing a database query on the main
thread in Room is not allowed. To fix this issue, database operations must be
performed on a background thread and you should use the Executors class or Kotlin
Coroutines for background threading.

public class LoginActivity extends AppCompatActivity {

private final ExecutorService executorService =


Executors.newSingleThreadExecutor();
private EditText etLoginId;
private EditText etPassword;
private Button btnLogin;

private UserDao userDao;

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

// Initialize the UserDao


userDao = InitDb.appDatabase.userDao();

// Initialize UI components
etLoginId = findViewById(R.id.etLoginId);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);

// Set onClickListener for the login button


btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
login();
}
});

// Insert a test user for demonstration purposes


insertTestUser();
}

private void login() {


String loginId = etLoginId.getText().toString().trim();
String password = etPassword.getText().toString().trim();

if (TextUtils.isEmpty(loginId) || TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter login credentials",
Toast.LENGTH_SHORT).show();
return;
}

// Execute the database query on a background thread


executorService.execute(new Runnable() {
@Override
public void run() {
final User user = userDao.getUserByLoginId(loginId);
// Handle the result on the main thread
runOnUiThread(new Runnable() {
@Override
public void run() {
if (user != null && password.equals(user.getPassword())) {
// Successful login, navigate to the main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
} else {
// Invalid login credentials
Toast.makeText(LoginActivity.this, "Invalid login credentials",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
}

private void insertTestUser() {


executorService.execute(new Runnable() {
@Override
public void run() {
// Check if the test user 'admin' already exists in the db
if (userDao.getUserByLoginId("admin") == null) {
// Insert the test user
User testUser = new User();
testUser.setLoginId("admin");
testUser.setPassword("admin"); // Note: In a real application,
passwords should be hashed
testUser.setFullName("Admin User");
testUser.setContact("[email protected]");

userDao.insert(testUser);
}
}
});
}

}
Q9. Create an app that loads and displays Images from the Gallery.

Building the Image Gallery

Let's dive into the main components of our application:

1. Custom Adapter

The GalleryAdapter is a custom adapter responsible for binding images to the


RecyclerView. It includes an ArrayList that contains the paths of the images and
uses Glide to load them into an ImageView. The ViewHolder inner class references
the ImageView where each image will be displayed. Here's a snapshot of the
GalleryAdapter class:

package com.example.piceditor;

import android.content.Context;

import android.text.Layout;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ImageView;

import androidx.annotation.NonNull;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.io.File;

import java.util.ArrayList;

public class GalleryAdapter extends


RecyclerView.Adapter<GalleryAdapter.ViewHolder> {

private Context context;

private ArrayList<String> images_list;

@NonNull

@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {

View view=
LayoutInflater.from(context).inflate(R.layout.gellary_item,null,true);

return new ViewHolder(view);

@Override

public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

File image_file=new File(images_list.get(position));

if(image_file.exists()){

Glide.with(context).load(image_file).into(holder.image);

@Override

public int getItemCount() {

return images_list.size();

public GalleryAdapter(Context context, ArrayList<String> images_list) {

this.context = context;

this.images_list = images_list;

public class ViewHolder extends RecyclerView.ViewHolder{

private ImageView image;

public ViewHolder(@NonNull View itemView) {

super(itemView);
image=itemView.findViewById(R.id.gallery_item);

2. MainActivity

In MainActivity, we set up the RecyclerView with a GridLayoutManager. We also


implement permission handling to access external storage and load the images into
our ArrayList.

package com.example.piceditor;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;

import static android.os.Environment.MEDIA_MOUNTED;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;

import androidx.core.content.ContextCompat;

import androidx.recyclerview.widget.GridLayoutManager;

import androidx.recyclerview.widget.LinearLayoutManager;

import androidx.recyclerview.widget.RecyclerView;

import android.content.pm.PackageManager;

import android.database.Cursor;

import android.os.Bundle;

import android.os.Environment;

import android.provider.MediaStore;

import android.widget.TextView;

import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

static int PERMISSION_REQUEST_CODE=100;

RecyclerView recyclerView;

ArrayList<String> images;

GalleryAdapter adapter;

GridLayoutManager manager;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

recyclerView=findViewById(R.id.gallery_recycler);

images=new ArrayList<>();

adapter=new GalleryAdapter(this,images);

manager=new GridLayoutManager(this,3);

recyclerView.setAdapter(adapter);

recyclerView.setLayoutManager(manager);

checkPermissions();

private void checkPermissions() {

int result=
ContextCompat.checkSelfPermission(getApplicationContext(),READ_EXTERNAL_
STORAGE);

if(result== PackageManager.PERMISSION_GRANTED){

loadImages();

}else{
ActivityCompat.requestPermissions(this,new
String[]{READ_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE);

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[]


permissions, @NonNull int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if(grantResults.length > 0){

boolean
accepted=grantResults[0]==PackageManager.PERMISSION_GRANTED;

if(accepted){

loadImages();

}else{

Toast.makeText(this,"You have dined the


permission",Toast.LENGTH_LONG).show();

}else{

private void loadImages() {

boolean SDCard=
Environment.getExternalStorageState().equals(MEDIA_MOUNTED);

if(SDCard){

final String[]
colums={MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID};
final String order=MediaStore.Images.Media.DATE_TAKEN+" DESC";

Cursor
cursor=getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTE
NT_URI,colums,null,null,order);

int count =cursor.getCount();

for(int i=0;i<count;i++){

cursor.moveToPosition(i);

int colunmindex=cursor.getColumnIndex(MediaStore.Images.Media.DATA);

images.add(cursor.getString(colunmindex));

recyclerView.getAdapter().notifyDataSetChanged();

3. XML Layout

The XML layouts for our activity and gallery items are straightforward. We use a
RelativeLayout containing a RecyclerView for the main activity. Each item in the
RecyclerView is a CardView containing an ImageView.

MainActivity Layout:

In the activity_main.xml file, we layout the RecyclerView along with a TextView


displaying "All Photos."

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

<RelativeLayout 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">
<TextView

android:id="@+id/textView3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentEnd="true"
android:layout_marginLeft="30dp" android:layout_marginEnd="187dp"
android:fontFamily="@font/nunito_sans_black"

android:text="All Photos"

android:textColor="@color/black"

android:textSize="22sp" />

<androidx.recyclerview.widget.RecyclerView

android:id="@+id/gallery_recycler"

android:layout_width="383dp"

android:layout_height="621dp"

android:layout_alignBottom="@+id/textView3"

android:layout_marginStart="8dp"

android:layout_marginTop="16dp"

android:layout_marginEnd="8dp"

android:layout_marginBottom="-636dp"/>

</RelativeLayout>

These XML files define the visual structure of our image gallery. By combining the
RecyclerView with GridLayoutManager, we achieve a grid-like arrangement for our
images, and the CardView ensures a consistent look for each image.

Gallery Item Layout:

For individual gallery items, we use a CardView that wraps an ImageView


in gallery_item.xml:

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

<androidx.cardview.widget.CardView

xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"

android:layout_height="wrap_content">

<ImageView

android:id="@+id/gallery_item"

android:layout_width="120dp"

android:layout_height="120dp"

android:layout_margin="1dp"

android:scaleType="centerCrop" />

</androidx.cardview.widget.CardView>

Running the Application and Viewing the Output

Step 1: Set Up Permissions

Before running the application, make sure to declare the necessary permissions for
reading external storage in your AndroidManifest.xml file:

<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>

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

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

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

<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application

android:allowBackup="true"

android:dataExtractionRules="@xml/data_extraction_rules"

android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/Theme.PicEditor"

tools:targetApi="31">

<activity

android:name=".MainActivity"

android:exported="true">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<meta-data

android:name="preloaded_fonts"

android:resource="@array/preloaded_fonts" />

</application>

</manifest>

Step 2: Run the Application

Open the project in Android Studio. Connect your Android device or use an
emulator. Press the "Run" button (green play symbol) at the top of Android Studio.

You might also like