Android Notes
Android Notes
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:
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.
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)
ContactsContract.Contacts.CONTENT_URI,
);
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
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.
• 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.
• 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.
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
• 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
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.
<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">
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<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:
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:
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.
implementation "androidx.room:room-runtime:2.6.1"
annotationProcessor "androidx.room:room-compiler:2.6.1"
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;
}
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);
Build the Room Database by extending RoomDatabase and include the DAO.
Initialize the database in your application class or the entry point of your app.
@Override
public void onCreate() {
super.onCreate();
appDatabase = AppDatabase.getDatabase(this);
}
}
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.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Initialize UI components
etLoginId = findViewById(R.id.etLoginId);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
if (TextUtils.isEmpty(loginId) || TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter login credentials",
Toast.LENGTH_SHORT).show();
return;
}
userDao.insert(testUser);
}
}
});
}
}
Q9. Create an app that loads and displays Images from the Gallery.
1. Custom Adapter
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;
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View view=
LayoutInflater.from(context).inflate(R.layout.gellary_item,null,true);
@Override
if(image_file.exists()){
Glide.with(context).load(image_file).into(holder.image);
@Override
return images_list.size();
this.context = context;
this.images_list = images_list;
super(itemView);
image=itemView.findViewById(R.id.gallery_item);
2. MainActivity
package com.example.piceditor;
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;
RecyclerView recyclerView;
ArrayList<String> images;
GalleryAdapter adapter;
GridLayoutManager manager;
@Override
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();
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
boolean
accepted=grantResults[0]==PackageManager.PERMISSION_GRANTED;
if(accepted){
loadImages();
}else{
}else{
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);
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:
<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.
<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>
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"/>
<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>
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
</application>
</manifest>
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.