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

Android

Uploaded by

vinupriyatpc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Android

Uploaded by

vinupriyatpc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Android basic Question

1. What is Android and the latest version of Android?


Android is an operating system that is built basically for Mobile phones. It is
based on the Linux Kernel and other open-source software and is developed by
Google. It is used for touchscreen mobile devices such as smartphones and
tablets. But nowadays these are used in Android Auto cars, TV, watches,
cameras, etc. It has been one of the best-selling OS for smartphones. Android OS
was developed by Android Inc.
The latest version of Android is Android 14 (API level 34) and the initial stable
release date is October 4, 2023.

2. What’s Activity in Android?


Activity class is one of the very important parts of the Android component. Any
app, no matter how small it is (in terms of code and scalability), has at least one
Activity class. Unlike most programming languages, in which the main() method
is the entry point for that program or application to start its execution, the
android operating system initiates the code in an Activity instance by invoking
specific callback methods that correspond to specific stages of its lifecycle. So it
can be said that An activity is the entry point for interacting with the user.

3. Why is XML used for frontend development in Android?


XML stands for Extensible Markup Language. XML is a markup language
much like HTML used to describe data. XML itself is well readable both by
humans and machines. Also, it is scalable and simple to develop. In Android, we
use XML for designing our layouts because XML is a lightweight language, so it
doesn’t make our layout heavy.

4. What are the components of the Android Application?


There are some necessary building blocks that an Android application consists
of. These loosely coupled components are bound by the application manifest file
which contains the description of each component and how they interact. The
four main components of android applications are:
 Activities
 Services
 Content Providers
 Broadcast Receiver
 Intents
Android basic Question

5. What is the Dalvik Virtual Machine?


DVM is a virtual machine to execute Android applications. The Java
bytecode(.class file) generated by the javac compiler is converted into Dalvik
bytecode to make the application source files executable on the DVM. Since
Android devices have a definite processing capacity, memory, and battery life,
the DVM design principle aims to optimize itself so that it can load fastly and
run smoothly even on low memory/powered devices. This virtual machine is
very efficient in running multiple instances on the same device.

6. What are the differences between Dalvik and ART?


Dalvik Virtual Machine Android Run Time

Faster Booting time Rebooting is significantly longer

Cache builds up overtime The cache is built during the first boot

Consumes a lot of storage space


Occupies less space due to JIT
internally due to AOT

Works best for small storage


Works best for Large storage devices
devices

Experimental and new – not much app


Stable and tested virtual machine
support comparatively

Extremely Faster and smoother Faster


Longer app loading time and app loading time and lower
processor usage

Uses JIT compiler (JIT: Just-In-


Time) Uses AOT compiler(Ahead-Of-Time)
Thereby resulting in lower storage thereby compiling apps when installed
space consumption
Android basic Question

Dalvik Virtual Machine Android Run Time

Application lagging due to garbage Reduced application lagging and better


collector pauses and JIT user experience

App installation time is


App installation time is longer as
comparatively lower as the
compilation is done during installation
compilation is performed later

ART converts it just once at the time of


app installation. That makes CPU
DVM converts bytecode every time
execution easier.
you launch a specific app.
Improved battery life due to faster
execution.

7. How does an Android App Work?


Developing an android application involves several processes that happen
sequentially. After writing the source code files, when developers click the Run
button on the Android studio, plenty of operations and processes start at the
backend.
 Building the APK File
o Code Compilation
o Conversion into Dalvik bytecodes
o Generating .apk file
o App Distribution
 Deploy the Application
o Establish the ADB Server
o Transfer .apk file to the Device
 Run the Application
o App launch request
o Conversion of the .dex code to native OAT format

8. What is Toast in Android?


A Toast is a short alert message shown on the Android screen for a short interval
of time. Android Toast is a short popup notification that is used to display
Android basic Question

information when we perform any operation in our app. It disappears


automatically. If the user wants a permanently visible message, then
a notification can be used.

9. What’s Service in Android?


Services in Android are a special component that facilitates an application to run
in the background in order to perform long-running operation tasks. The prime
aim of a service is to ensure that the application remains active in the
background so that the user can operate multiple applications at the same time. A
user interface is not desirable for android services as it is designed to operate
long-running processes without any user intervention. A service can run
continuously in the background even if the application is closed or the user
switches to another application.

10. What’s Content Provider in Android?


In Android, Content Providers are a very important component that serves the
purpose of a relational database to store the data of applications. The role of the
content provider in the android system is like a central repository in which data
of the applications are stored, and it facilitates other applications to securely
access and modify that data based on the user requirements. The Android
system allows the content provider to store the application data in several ways.
Users can manage to store the application data like images, audio, videos, and
personal contact information by storing them in SQLite Database, in files, or
even on a network.

11. What’s Broadcast Receiver in android?


Broadcast in android is the system-wide event that can occur when the device
starts, when a message is received on the device, when incoming calls are
received, or when a device goes to airplane mode, etc. Broadcast Receivers are
used to respond to these system-wide events. Broadcast Receivers allow us to
register for the system and application events, and when that event happens, then
the registered receivers get notified. There are mainly two types of Broadcast
Receivers:
 Static Broadcast Receivers: These types of Receivers are declared in the
manifest file and work even if the app is closed.
Android basic Question

 Dynamic Broadcast Receivers: These types of receivers work only if the


app is active or minimized.

12. What’s Gradle and write down its usage in Android?


Gradle is a build system (open source) that is used to automate building, testing,
deployment, etc. “Build.gradle” are scripts where one can automate the tasks.
For example, the simple task to copy some files from one directory to another
can be performed by Gradle build script before the actual build process happens.
Usage: Every Android project needs a Gradle for generating an apk from
the .java and .xml files in the project. Simply put, a Gradle takes all the source
files (java and XML) and applies appropriate tools, e.g., converts the java files
into dex files and compresses all of them into a single file known as apk that is
actually used.

13. What’s Fragment in android?


In Android, the fragment is the part of Activity that represents a portion of the
User Interface(UI) on the screen. It is the modular section of the android activity
that is very helpful in creating UI designs that are flexible in nature and auto-
adjustable based on the device screen size. There are mainly 3 types of
fragments:
 Single Fragment
 List Fragment
 Fragment Transaction

14. What’s RecyclerView in Android & How it works?


RecyclerView is a ViewGroup added to the Android Studio as a successor of the
GridView and ListView. It is an improvement on both of them. It has been
created to make possible construction of any lists with XML layouts as an item
that can be customized vastly while improving the efficiency of ListViews and
GridViews. This improvement is achieved by recycling the views which are out
of the visibility of the user. For example, if a user scrolled down to a position
where items 4 and 5 are visible; items 1, 2, and 3 would be cleared from the
memory to reduce memory consumption.

15. What’s the Difference Between Intent and Intent filters?


Android basic Question

An Intent is an object passed to Context.startActivity(), Context.startService()


or Activity.startActivityForResult() etc. to launch an activity or get an existing
activity to do something new. On the other hand, an Intent filter describes the
capability of the component(like activities, services, and broadcast receivers).

16. What is the AndroidManifest.xml?


Every project in Android includes a manifest file, which is
AndroidManifest.xml, stored in the root directory of its project hierarchy. The
manifest file is an important part of our app because it defines the structure and
metadata of our application, its components, and its requirements. This file
includes nodes for each of the Activities, Services, Content Providers, and
Broadcast Receivers that make the application and using Intent Filters and
Permissions determines how they coordinate with each other and other
applications. The manifest file also specifies the application metadata, which
includes its icon, version number, themes, etc., and additional top-level nodes
can specify any required permissions, unit tests, and define hardware, screen, or
platform requirements.

17. What’s Android SDK and its Components?


Android SDK stands for Android Software Development Kit which is
developed by Google for Android Platform. With the help of Android SDK, we
can create Android Apps easily. Android SDK is a collection of libraries and
Software Development tools that are essential for Developing Android
Applications. Whenever Google releases a new version or update of Android
Software, a corresponding SDK also releases with it. In the updated or new
version of SDK, some more features are included which are not present in the
previous version. Android SDK consists of some tools which are very essential
for the development of Android Application. These tools provide a smooth flow
of the development process from developing and debugging. Android SDK is
compatible with all operating systems such as Windows, Linux, macOS, etc.
Components:
 Android SDK Build tool.
 Android Emulator.
 Android SDK Platform-tools.
 Android SDK Tools.
Android basic Question

18. Disadvantages of Android


 Fragmentation provides a very intuitive approach for user experience, but it
has some drawbacks, where the development team needs time to adjust with
the various screen sizes of mobile smartphones that are now available in the
market and invoke the particular features in the application.
 The Android devices might vary broadly. So the testing of the application
becomes more difficult.
 As the development and testing consume more time, the cost of the
application may increase, depending on the application’s complexity and
features.

19. Explain the Activity Lifecycle in brief.


These are the different stages of the Activity Lifecycle:

 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.
 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.
Android basic Question

 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 the screen.
 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.
 onPause(): It is invoked when an activity is going into the background but
has not yet been killed. It is a counterpart to onResume()
 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.
 onDestroy(): The final call received before the activity is destroyed. This
can happen either because the activity is finished (when finish() is invoked)
or because the system is temporarily destroying this instance of the activity
to save space.

20. Why do we need to call setContentView() in onCreate() of Activity


class?
The reason for doingso is that the activity life cycle onCreate() method is called
only once. And this is the big reason we need to call the setContentView() in
onCreate(). And it will be inefficient to call this function in onResume(),
onStart(), and somewhere else because those methods are called more than once.
21. Explain the Fragment Lifecycle in Brief.
These are the different stages of the Activity Lifecycle:
Android basic Question

Methods Description

The very first method to be called when the fragment


onAttach() has been associated with the activity. This method
executes only once during the lifetime of a fragment.

This method initializes the fragment by adding all the


onCreate()
required attributes and components.

System calls this method to create the user interface


of the fragment. The root of the fragment’s layout is
onCreateView()
returned as the View component by this method to
draw the UI.

It indicates that the activity has been created in which


onActivityCreated() the fragment exists. View hierarchy of the fragment
also instantiated before this function call.

The system invokes this method to make the fragment


onStart()
visible on the user’s device.

This method is called to make the visible fragment


onResume()
interactive.

It indicates that the user is leaving the fragment.


onPause() System calls this method to commit the changes made
to the fragment.

Method to terminate the functioning and visibility of


onStop()
fragments from the user’s screen.

onDestroyView() System calls this method to clean up all kinds of


resources as well as view hierarchy associated with
Android basic Question

Methods Description

the fragment.

It is called to perform the final clean-up of the


onDestroy()
fragment’s state and its lifecycle.

The system executes this method to disassociate the


onDetach()
fragment from its host activity.

22. What is the difference between a Fragment and an Activity?


Activity Fragment

Activity is an application
The fragment is only part of an activity,
component that gives a user
it basically contributes its UI to that
interface where the user can
activity.
interact.

Activity is not dependent on Fragment is dependent on activity. It


fragment can’t exist independently.

we need to mention all activity it in Fragment is not required to mention in


the manifest.xml file the manifest file

We can’t create multi-screen UI After using multiple fragments in a


without using fragment in an single activity, we can create a multi-
activity, screen UI.

Activity can exist without a Fragment cannot be used without an


Fragment Activity.
Android basic Question

Activity Fragment

While Using fragments in the project,


Creating a project using only
the project structure will be good and
Activity then it’s difficult to manage
we can handle it easily.

Lifecycle methods are hosted by the


Lifecycle methods in fragments are
OS. The activity has its own life
hosted by hosting the activity.
cycle.

Activity is not light weight. The fragment is the lite weight.

23. What’s Context in Android?


The context in Android can be understood as something which gives us the
context of the current state of our application. We can break the context and its
use into three major points:
 It allows us to access resources.
 It allows us to interact with other Android components by sending messages.
 It gives you information about your app environment.
There are mainly two types of context available in Android.
1. Application Context and
2. Activity Context

24. Top Image Loading Libraries in Android.


 Picasso
 Glide
 Fresco
 COIL (Coroutine Image Loader)
 UIL (Universal Image Loader)
Android basic Question

25. What is View in Android?


The view is a class that represents the basic building block for UI components. A
View occupies a rectangular area on the screen and is responsible for drawing
and event handling. It is a superclass for all the UI components. The most
common UI components are:
 TextView
 EditText
 ImageView
 Button
 ProgressBar
 CheckBox, etc.

26. Difference Between View and ViewGroup in Android

View ViewGroup

View is a simple rectangle box that ViewGroup is the invisible container. It


responds to the user’s actions. holds View and ViewGroup

View is the SuperClass of All ViewGroup is a collection of


component like TextView, Views(TextView, EditText, ListView,
EditText, ListView, etc etc..), somewhat like a container.

A View object is a component of


A ViewGroup object is a layout, that is, a
the user interface (UI) like a button
container of other ViewGroup objects
or a text box, and it’s also called a
(layouts) and View objects (widgets)
widget.

For example, LinearLayout is the


Examples are EditText, Button,
ViewGroup that contains Button(View),
CheckBox, etc.
and other Layouts also.

View refers to the ViewGroup refers to the


android.view.View class android.view.ViewGroup class
Android basic Question

View ViewGroup

android.view.View which is the


ViewGroup is the base class for Layouts.
base class of all UI classes.

27. What is Kotlin Coroutine on Android?


The Kotlin team defines coroutines as “lightweight threads”. They are sort of
tasks that the actual threads can execute. Kotlin coroutines introduce a new style
of concurrency that can be used on Android to simplify async code. The official
documentation says that coroutines are lightweight threads. By
lightweight, it means that creating coroutines doesn’t allocate new threads.
Instead, they use predefined thread pools and smart scheduling for the
purpose of which task to execute next and which tasks later.

28. How Garbage Collector Works in Android?


Garbage Collector in Android has no compacting. This means the address of
objects in the heap never changed after their creation. So garbage collection can
be triggered when an allocation fails when an
 OutOfMemoryError is about to be triggered,
 When the size of the heap hits some soft limit, and
 When a GC was explicitly requested.

29. Describe the architecture of your last app.


When developers work on a real mobile application whose nature is dynamic and
will expand its features according to the user’s need, then it is not possible to
write core logic in activities or fragments. To structure the project’s code and to
give it a modular design(separated code parts), architecture patterns are applied
to separate the concerns. The most popular android architectures used by
developers are the following:
 MVC (Model — View — Controller)
 MVP (Model — View — Presenter)
 MVVM (Model — View — ViewModel)
So you have to tell the architecture of the last app you have developed during the
college time project or in a real industry project.
Android basic Question

30. MVC vs MVP vs MVVM architecture and which one we should choose?
MVVM(MODEL
MVC(MODEL VIEW MVP(MODEL VIEW VIEW
CONTROLLER) PRESENTER) VIEWMODEL)

Developed as the second


Industry-recognized
One of the oldest iteration of software
architecture pattern
software architecture architecture which is
for applications.
advanced from MVC.

This architecture
pattern is more
It resolves the problem of
event-driven as it
UI(View) and data- having a
uses data binding
access dependent View by
and thus makes
mechanism(Model) are using Presenter as a
easy separation
tightly coupled. communication channel
of core business
between Model and View.
logic from
the View.

Multiple View can


Controller and View e
A one-to-one relationship be mapped with a
xist with the one-to-
exists single ViewModel
many relationship. One
between Presenter and Vie and thus, the one-
Controller can select a
w as one Presenter class to-many
different view based
manages one View at a relationship exists
upon the required
time. between View and
operation.
ViewModel.

Which one should we choose?


 MVC: Ideal for small-scale projects only.
 MVP: Ideal for simple and complex applications.
 MVVM: Ideal for big-scale projects. But not ideal for small-scale projects.
Android basic Question

31. How to Reduce APK size in android?


 Remove unused sources
 Use of Vector Drawables
 Reuse your code
 Compress PNG and JPEG files
 Use of Lint
 Use images in WebP file format
 Use of proguard
 Use of ShrinkResources
 Limit the usage of external libraries
 Use the Android Size Analyzer tool
 Generate App Bundles instead of APK
 Use of Resconfigs

32. What’s the Android jetpack and its Key Benefits?


Jetpack is nothing but a set of software components, libraries, tools, and
guidance to help in developing great Android apps. Google launched Android
Jetpack in 2018. Key Benefits of Android Jetpack
 Forms a recommended way for app architecture through its components
 Eliminate boilerplate code
 Simplify complex task
 Provide backward compatibility as libraries like support are unbundled from
Android API and are re-packaged to androidx.* package
 Inbuilt productivity feature of the Kotlin Integration

33. What are the different software components of Android Jetpack?


The software components of Android Jetpack has been divided into 4 categories:
 Foundation Components: AppCompat, Android KTX, Test, Multidex
 Architecture Components: Room, WorkManager, Lifecycle, ViewModel,
Paging, Navigation
 Behavior Components: DownloadManager, Permissions, Sharing, Slices
 UI Components: Animation & Transition, Auto, Fragment, Palette, Layout

34. What’s Jetpack Compose and its Benefits?


Jetpack Compose is a modern UI toolkit recently launched by Google which is
used for building native Android UI. It simplifies and accelerates the UI
development with less code, Kotlin APIs, and powerful tools.
 Declarative
 Compatible
 Increase development speed
Android basic Question

 Concise and Idiomatic Kotlin


 Easy to maintain
 Written in Kotlin

35. What are the Architecture Components of Android?


Architecture Components could be classified as follows:
 Room
 WorkManager
 Lifecycle
 ViewModel
 LiveData
 Navigation
 Paging
 Data Binding

36. How to Improve RecyclerView Scrolling Performance in Android?


 Set a specific width and height to ImageView in RecyclerView items
 Avoid using NestedView
 Use the setHasFixedsize method
 Use the image loading library for loading images
 Do less work in the OnBindViewHolder method
 Use the NotifyItem method for your RecyclerView

37. Volley Library in Android


Volley is an HTTP library that makes networking very easy and fast, for
Android apps. It was developed by Google and introduced during Google I/O
2013. It was developed because there is an absence in Android SDK, of a
networking class capable of working without interfering with the user
experience. Although Volley is a part of the Android Open Source
Project(AOSP), Google announced in January 2017 that Volley will move to a
standalone library. It manages the processing and caching of network requests,
and it saves developers valuable time from writing the same network call/cache
code again and again.

38. What’s Retrofit in Android?


Retrofit is a type-safe REST client built by square for Android and Java which
intends to make it simpler to expand RESTful web services. Retrofit uses OkHttp
as the system’s administration layer and is based on it. Retrofit naturally
serializes the JSON reaction utilizing a POJO (PlainOldJavaObject) which must
be characterized as cutting edge for the JSON Structure. To serialize JSON we
Android basic Question

require a converter to change it into Gson first. Retrofit is much simpler than
other libraries; we don’t have to parse our JSON. It directly returns objects but
there is one disadvantage: it doesn’t provide support to load images from the
server, but we can use Picasso for the same.

39. Describe MVVM


Model — View — ViewModel (MVVM) is the industry-recognized software
architecture pattern that overcomes all drawbacks of MVP and MVC design
patterns. MVVM suggests separating the data presentation logic(Views or UI)
from the core business logic part of the application.
The separate code layers of MVVM are:
 Model: This layer is responsible for the abstraction of the data sources.
Model and ViewModel work together to get and save the data.
 View: The purpose of this layer is to inform the ViewModel about the user’s
action. This layer observes the ViewModel and does not contain any kind of
application logic.
 ViewModel: It exposes those data streams which are relevant to the View.
Moreover, it serves as a link between the Model and the View.

40. What are the reasons your android app is legging?


 You are doing too much on the main thread
 Your asset files are huge
 You are using an outdated SDK version
 You are using bad libraries
 The speed of the network
 Chatty conversations
 Your code is inefficient

41. What is AIDL?


On Android what happens with the processors is one process can’t normally
access the memory of another process. So in order to interact they need to
decompose their objects into primitives that the OS can understand and gather
the objects across that boundary. The code to do that gathering is very complex
to write, so Android handles it with AIDL. So generally AIDL is similar to the
other IDLs and it allows to define the programming interface that both the client
and service agree upon in order to interact with each other using interprocess
communication (IPC).
Android basic Question

42. What is ANR and How can it be Prevented in Android?


ANR stands for Application Not Responding. An ANR will occur if you’re
running a process on the UI thread which takes an extended time, usually
around 5 seconds. During this point, the GUI (Graphical User Interface) will
lock up which can end in anything the user presses won’t be actioned. After the 5
seconds approx. has occurred, if the thread still hasn’t recovered then an ANR
dialogue box is shown informing the user that the appliance isn’t responding and
can give the user the choice to either wait, in the hope that the app will
eventually recover, or to force close the app.
Stop doing heavy tasks on the main thread. Instead, use worker threads such as
IntentService, AsyncTask Handler, or another Thread simply. Detecting where
ANRs happen is straightforward if it’s a permanent block (deadlock
acquiring some locks for instance), but harder if it’s just a short-lived delay.
First, re-evaluate your code and appearance for vulnerable spots and long-
running operations.

43. What is Android NDK and why is it useful?


The NDK (Native Development Kit) is a tool that allows you to program in
C/C++ for Android devices. It provides platform libraries one can use to manage
native activities and access physical device components, such as sensors and
touch input. NDK can be useful for cases in which you need to do one or more of
the following:
 Squeeze extra performance out of a device to achieve low latency or run
computationally intensive applications, such as games or physics
simulations.
 Reuse your own or other developers’ C or C++ libraries.

44. Explain the JUnit test in brief.


JUnit is a “Unit Testing” framework for Java Applications which is already
included by default in android studio. It is an automation framework for Unit as
well as UI Testing. It contains annotations such as @Test, @Before, @After,
etc. Here we will be using only @Test annotation to keep the article easy to
understand.

45. What’s Dagger and When to use Dagger?


Dagger is a Dependency Injection framework that will generate a lot of
boilerplate code for you to achieve the goal of Dependency injection in Android
Android basic Question

development. Not that one must have a good understanding of Dependency


Injection before answering this question.
When to use a dagger?

Project Size Small Medium Large

Tool to use Manual DI Service Locator Dagger Dagger Dagger

46. What’s LiveData in Android Architecture Component and its


Advantages?
LiveData component is an observable data holder class i.e, the contained value
can be observed. LiveData is a lifecycle-aware component and thus it performs
its functions according to the lifecycle state of other application components.
Further, if the observer’s lifecycle state is active i.e., either STARTED or
RESUMED, only then LiveData updates the app component. LiveData always
checks the observer’s state before making any update to ensure that the observer
must be active to receive it. If the observer’s lifecycle state is destroyed,
LiveData is capable of removing it, and thus it avoids memory leaks. It makes
the task of data synchronization easier.

Advantages of LiveData component:


 UI is updated as per the appropriate change in the data
 It removes the stopped or destroyed activities which reduce the chance of app
crash
 No memory leaks as LiveData is a lifecycle-aware component.
Android basic Question

47. What’s Data Binding in Android?


Data Binding library is a support library that provides the feature of binding UI
components in an activity/fragment to the data sources of the application. The
library carries out this binding task in a declarative format and not in a
programmatic way. Below is an example to understand the working of this
library accurately:
To find a TextView widget and bind it to the userName property of the
ViewModel variable, the findViewById() method is called:
TextView textView = findViewById(R.id.sample_text);
textView.setText(viewModel.getUserName());
After using the Data Binding library, the above code changes by using the
assignment expression as follows:
<TextView
android:text=”@{viewmodel.userName}” />
Advantages of Data Binding Component:
 Make code simpler and easy to maintain by removing UI frameworks called
in the activity.
 Allows classes and methods to observe changes in data
 Allows to make objects and fill which works as collection observables.

48. Room in Android Architecture Component.


The requirement of a database in Android is fulfilled by SQLite from the very
beginning. However, it comes with some severe drawbacks like not checking the
queries at compile-time, it does not save plain-old-Java Objects(commonly
referred to as POJOs). Developers also need to write a lot of boilerplate code to
make the SQLite database work in the Android OS environment. The Room
component comes into the picture as an SQLite Object Mapping
Library which overcomes all the mentioned challenges. Room converts queries
directly into objects, checks errors in queries at the compile-time, and is also
capable of persisting the Java POJOs.
Moreover, it produces LiveData results/observables from the given query result.
Because of this versatile nature of the Room component, Google officially
supports and recommends developers to use it. The Room consists of the
following sub-components:
1. Entity: It is the annotated class for which the Room creates a table within
the database. The field of the class represents columns in the table.
2. DAO(Data Access Object): It is responsible for defining the methods to
access the database and to perform operations.
Android basic Question

3. Database: It is an abstract class that extends RoomDatabase class and it


serves as the main access point to the underlying app’s relational data.

49. ViewModel in Android.


ViewModel is one of the most critical classes of the Android Jetpack
Architecture Component that support data for UI components. Its purpose is to
hold and manage the UI-related data. Moreover, its main function is to maintain
the integrity and allows data to be serviced during configuration changes like
screen rotations. Any kind of configuration change in Android devices tends to
recreate the whole activity of the application. It means the data will be lost if it
has not been saved and restored properly from the activity which was destroyed.
To avoid these issues, it is recommended to store all UI data in the ViewModel
instead of an activity.
Android basic Question

50. What’s Android KTX?


KTX library is the only one among the foundation components which was
introduced for the first time with the release of the Jetpack. Android KTX is a
collection of Kotlin extensions that are designed to facilitate developers to
remove boilerplate code as well as to write concise code while developing
android applications with Kotlin language. Here KTX in the name stands
for Kotlin Extensions. Below is an example of a piece of code without using
and after using the Android KTX library:
Code snippet of SQLite without using KTX library:
db.beginTransaction()
try {
// insert data
db.setTransactionSuccessful()
}
finally {
db.endTransaction()
}
Above code after using KTX library:
db.transaction {
// insert data
}

You might also like