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

Final Mobile Programming

The document covers mobile programming concepts, including definitions of mobile devices, mobile programming approaches (Native, Hybrid, PWA), Android architecture, and development environment setup. It also includes practical coding questions related to UI development, data handling, and application features. Additionally, it discusses the purpose of the res directory, string resources, and differences between Dalvik VM and Android Runtime.

Uploaded by

aimakeryt99
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 views35 pages

Final Mobile Programming

The document covers mobile programming concepts, including definitions of mobile devices, mobile programming approaches (Native, Hybrid, PWA), Android architecture, and development environment setup. It also includes practical coding questions related to UI development, data handling, and application features. Additionally, it discusses the purpose of the res directory, string resources, and differences between Dalvik VM and Android Runtime.

Uploaded by

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

Theory Questions : Mobile Programming [ Page No: 1-18 ]

1.​ What is a mobile device? Explain its main features and categories. List at least
four different mobile platforms.
2.​ What is mobile programming? Explain the three primary approaches: Native,
Hybrid, and Progressive Web App (PWA) development, with three advantages
for each.
3.​ Explain the Android Platform by drawing and describing the layers of the
Android Architecture.
4.​ Describe the process of setting up an Android development environment. How
do you create and run an Android project on an Emulator (AVD)?
5.​ What is the purpose of the res directory? Explain how to create and use string
resources from the res/values/strings.xml file.
6.​ Differentiate between the Dalvik Virtual Machine (DVM) and the Android
Runtime (ART).
7.​ List and differentiate between five major Android layout types (Linear,
Relative, Constraint, Table, Frame).
8.​ What is the difference between android:gravity and android:layout_gravity
attributes? Provide a simple example using a LinearLayout.
9.​ What is event handling? Explain three different methods for implementing an
onClick listener for a Button widget.
10.​ Draw the Activity Lifecycle diagram. Briefly explain the purpose of the
onCreate(), onResume(), onPause(), and onDestroy() methods.
11.​ What is an Intent? Differentiate between an explicit intent and an implicit
intent.
12.​ How do you declare a new activity in the AndroidManifest.xml file?
Explain the purpose of an <intent-filter>.
13.​ What is a Fragment? List four key differences between an Activity and a
Fragment. Also, draw and explain the Fragment Lifecycle in detail.
14.​ Differentiate between a Toast and a Snackbar. In which scenario would
you prefer to use a Snackbar?
15.​ Differentiate between a ListView and a RecyclerView. Explain why
RecyclerView is preferred for displaying large or dynamic data sets,
referencing the ViewHolder pattern.
16.​ What is a web API and what is JSON? Explain the general process of
retrieving contents from a remote server and parsing the JSON response.
17.​ What is the procedure for publishing an application on the Google Play
Store? Explain the importance of generating a signed APK.
18.​ Explain the high-level steps required to implement Google Maps in an
Android application, including how to obtain an API key and display a marker.
19.​ What is a Storyboard in iOS development? Explain the roles of View
Controllers and the View Hierarchy.
20.​ Draw and explain the directory structure of a standard Android application
1
Practical & Code Questions : Mobile Programming [ Page No: 19-33 ]

1.​ Develop a simple UI that includes an EditText, a Spinner, a CheckBox, and a


RadioButton group. Explain the purpose of each widget.
2.​ Provide the specific Java/Kotlin code to demonstrate how to pass data (e.g., a
string) from one activity to another using an Intent.
3.​ Develop a simple application to demonstrate the implementation of a Popup
Menu with at least three menu items.
4.​ Write the code to create and show an AlertDialog with a title, a message, and
two buttons ("OK" and "Cancel").
5.​ Develop an application to display a simple list of 10 programming languages in
a ListView using an ArrayAdapter.
6.​ Develop an application to display a gallery of 9 images in a GridView or a
RecyclerView with a GridLayoutManager.
7.​ Write the code for a basic SQLiteOpenHelper class to create a "Student" table
with id, name, and address columns.
8.​ Write the specific Java/Kotlin code required to perform INSERT and DELETE
operations on a "Student" table in an SQLite database.
9.​ Develop an Android application that functions as a simple calculator. The UI
should have two EditText fields for numbers and four Buttons for addition,
subtraction, multiplication, and division. The result should be displayed in a
TextView.
10.​ Write a simple Swift function that accepts a string as a parameter and
returns the number of vowels in that string.
11.​ Develop an application that fetches data from a remote API and displays it
in a RecyclerView.
12.​ Develop an application demonstrating communication between two
Fragments within the same Activity.
13.​ Write the code to fetch data from an SQLite database and display it in a
ListView using a SimpleCursorAdapter.
14.​ Develop an application to demonstrate the use of a ContextMenu.

For more join telegram group

https://t.me/bcanepalitgroup

2
1. What is a mobile device? Explain its main features and categories. List and
explain at least six different mobile platforms.

A mobile device is a portable, handheld computing device designed for mobile use.
It is small enough to be held and operated in the hand.
Main Features:
●​ Portability: Small, lightweight, and easy to carry.
●​ Connectivity: Can connect to the internet and other devices using Wi-Fi,
Cellular data (4G/5G), and Bluetooth.
●​ Touchscreen Interface: The primary method of user interaction is through a
touch-sensitive screen.
●​ Sensors: Equipped with various sensors like GPS (for location),
accelerometer (for motion), and proximity sensors.
●​ Battery Powered: Operates on a rechargeable battery, allowing for use
without being plugged in.
●​ Applications (Apps): Can run specialized software applications downloaded
from an app store.

Main Categories:
●​ Mobile Phones: Those devices which have cell and SMS support and don't
have web browsers or connectivity.
●​ Smartphones: A mobile phone with advanced computing capability and
connectivity. It's the most common category.
●​ Non-phone devices: Those devices which don't contain call and SMS feature
falls into this category. Example: Apple’s iPod touch and iPad.
●​ Tablets: Larger than smartphones but with similar functionality, designed for
media consumption and light productivity (e.g., iPad, Samsung Galaxy Tab).
●​ Smartwatches: Wearable devices that offer notifications, health tracking, and
other app functions (e.g., Apple Watch, Samsung Galaxy Watch).
●​ E-Readers: Specialized for reading digital books, with screens designed for
low eye strain (e.g., Amazon Kindle).

Six Mobile Platforms:


1.​ Android (Google): An open-source mobile operating system developed by
Google. Most widely used globally. Used by brands like Samsung, Xiaomi,
Oppo, etc.
2.​ iOS (Apple: A closed-source operating system developed by Apple. Only runs
on Apple devices like iPhones and iPads. Known for security and smooth
performance.
3.​ HarmonyOS (Huawei: Developed by Huawei after US trade restrictions.
Designed for smartphones, tablets, TVs, and IoT devices. Mainly used in
China.
4.​ watchOS (Apple): Apple’s OS for smartwatches (Apple Watch). Integrated
closely with iOS for fitness, health, and notifications.
5.​ BlackBerry OS: Once popular for business and secure communication. Now
discontinued and largely obsolete. Known for its physical keyboard and BBM.
6.​ Windows Phone: Created by Microsoft for smartphones. Known for tile-based
UI and Microsoft service integration. Discontinued due to low app support and
market share.

1
2. What is mobile programming? Explain the three primary approaches:
Native, Hybrid, and Progressive Web App (PWA) development, with one
advantage for each.
Mobile programming is the process of writing software for mobile devices like
smartphones and tablets. It involves designing, developing, and testing applications
that are optimized for smaller screens and mobile hardware.
Approach Explanation Key Advantage
Native The application is written in Best Performance & Full Hardware
App the platform-specific Access: Native apps are compiled
programming language. For into the device's native code, offering
Android, this is Java or the fastest performance and complete
Kotlin. For iOS, it is Swift or access to all device features (camera,
Objective-C. GPS, etc.).

Hybrid The application is built using Code Reusability: You can write a
App standard web technologies single codebase that runs on both
(HTML, CSS, JavaScript) and Android and iOS, saving significant
is then wrapped inside a development time and cost.
native "container".
Frameworks like React
Native or Flutter are used.
Progressi A PWA is a modern web No App Store Required: Users can
ve Web application that uses access and install a PWA directly from
App advanced browser features to the web, bypassing the need for an
(PWA) provide an app-like app store submission and approval
experience. It runs in the process.
browser but can be "installed"
on the home screen, work
offline, and send push
notifications.

3. Explain the Android Platform by drawing and describing the layers of the
Android Architecture.
The Android Platform is a software stack for mobile devices. It includes an
operating system, middleware, and key applications. The architecture is organized
into a series of layers.

2
Description of Layers:
1.​ Linux Kernel (Bottom Layer): This is the foundation of the Android
architecture. It manages all the core system services such as memory
management, process management, security, and hardware drivers (for the
display, camera, Wi-Fi, etc.).
2.​ Hardware Abstraction Layer (HAL): The HAL provides standard interfaces
that expose device hardware capabilities to the higher-level Java API
framework. It allows Android to be agnostic about lower-level driver
implementations. For example, it provides a standard API for the camera,
even if different devices have different camera hardware.
3.​ Android Runtime (ART) & Native Libraries:
○​ Android Runtime (ART): The environment where Android app code is
executed. ART uses Ahead-Of-Time (AOT) compilation to compile app
bytecode into native machine code upon installation, which results in
faster app launch times and improved performance.
○​ Native C/C++ Libraries: Many core Android system components and
services are built from native code that require native libraries written in
C and C++. Examples include SQLite (for databases), WebKit (for
browser rendering), and OpenGL ES (for 3D graphics).
4.​ Java API Framework: This layer provides the high-level services that
developers use to build applications. It includes a rich set of APIs for building
UIs, managing activities, accessing content providers, and more. Key
components include the Activity Manager, Notification Manager, and View
System.
5.​ Applications (Top Layer): This is the layer where all applications reside, both
the pre-installed system apps (like Phone, Contacts, Browser) and the
applications installed by the user.

4. Describe the process of setting up an Android development environment.


How do you create and run an Android project on an Emulator (AVD)?
Setting up the Development Environment:​
The standard development environment for Android consists of three main
components, which are now conveniently bundled within Android Studio.
1.​ Java Development Kit (JDK): Android applications are primarily written in
Java or Kotlin, both of which run on the Java Virtual Machine (JVM). The JDK
is required to compile this code.
2.​ Android Studio: This is the official Integrated Development Environment
(IDE) for Android. It includes a powerful code editor, debugger, performance
tools, and an emulator.
3.​ Android SDK (Software Development Kit): The SDK includes all the
necessary libraries, tools, and system images required to build, test, and
debug Android applications. Key components include the SDK Platform-Tools
(like adb) and Android system images for different API levels.
The setup process is now very simple: download and install Android Studio, and it
will guide you through the process of downloading the necessary JDK and the latest
Android SDK.
Creating and Running a Project on an Emulator (AVD):​
An Android Virtual Device (AVD) is an emulator that lets you test your application on
a simulated device.
1.​ Create an AVD:
○​ In Android Studio, go to Tools -> AVD Manager.
3
○​ Click + Create Virtual Device....
○​ Select Hardware: Choose a device definition (e.g., Pixel 6).
○​ Select a System Image: Choose the version of the Android OS you
want to run (e.g., API 33). If the image is not downloaded, Android
Studio will prompt you to download it.
○​ Verify Configuration: Give the AVD a name and adjust any settings if
needed. Click Finish.
2.​ Run the Project:
○​ Once the AVD is created, it will appear in the list of available devices in
the Studio toolbar.
○​ Select your newly created AVD from the dropdown menu.
○​ Click the green 'Run' button (a triangle icon) or press Shift + F10.
○​ Android Studio will build your project, start the emulator, and install and
launch your application on the AVD.

5. What is the purpose of the res directory? Explain how to create and use
string resources from the res/values/strings.xml file.
The res directory is a fundamental part of an Android project that is used to store
all the application's non-code resources.
Purpose: The primary purpose is to separate the application's static content
from its source code. This has several key advantages:
●​ Maintainability: It is easier to manage layouts, images, and text without
modifying the source code.
●​ Localization: You can provide alternative resources for different languages.
For example, you can have a values-fr directory for French strings.
●​ Device Compatibility: You can provide different layouts or images for
different screen sizes and densities (e.g., layout-land for landscape mode).
●​ Efficiency: The Android build system can optimize these resources and
provide easy access to them at runtime.
Creating and Using String Resources:​
String resources are defined in XML files within the res/values directory, typically in
res/values/strings.xml.
Step 1: Create the String Resource: Open the res/values/strings.xml file and
define a string using the <string> tag. Each string needs a unique name attribute,
which will be its ID. Generated xml:
<resources>
<string name="app_name">My Awesome App</string>
<string name="welcome_message">Hello, welcome to our app!</string>
</resources>
Step 2: Use the String Resource: You can access this string in two main ways:In
an XML Layout file: Use the @string/ syntax. Generated xml:
<TextView
android:id="@+id/greetingTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome_message" />
In Java/Kotlin Code: Use the R class to get the resource ID and then fetch the
string.Generated java:
TextView greetingTextView = findViewById(R.id.greetingTextView);
String message = getString(R.string.welcome_message);
greetingTextView.setText(message);
4
6. Differentiate between the Dalvik Virtual Machine (DVM) and the Android
Runtime (ART).
Feature Dalvik Virtual Machine (DVM) Android Runtime (ART)
Compilation Just-In-Time (JIT) Ahead-Of-Time (AOT)
Compilation: Code is compiled Compilation: Code is compiled into
from bytecode into native native machine code when the app is
machine code while the app is installed.
running.
App Install Faster. Since no compilation is Slower. The AOT compilation
Time done at install time, the process makes the initial app
installation process is quick. installation take longer.
App Launch Slower. The app has to be Faster. The app is already compiled,
Time compiled every time it is so it launches much more quickly.
launched, leading to a
noticeable startup delay.
Performanc Lower. JIT compilation Higher. Since the app is
e consumes CPU cycles while the pre-compiled, it runs more smoothly
app is running, which can impact with less CPU overhead.
performance.
Battery Life Worse. The constant JIT Better. Less CPU work is done while
compilation process uses more the app is running, leading to
CPU power, which in turn improved battery life.
consumes more battery.
Used In Older Android versions (up to Modern Android versions (from
Android 4.4 KitKat). Android 5.0 Lollipop onwards).

7. List and differentiate between five major Android layout types.


Android layouts are containers that define the structure for a user interface. Here are
five major types:
1.​ LinearLayout:
○​ Description: Arranges child views in a single direction, either vertically
or horizontally. It's simple and efficient for basic UIs.
○​ Use Case: Creating a simple form with labels and input fields stacked
vertically.
2.​ RelativeLayout:
○​ Description: Arranges child views relative to each other (e.g., "place
this button to the right of the text field") or relative to the parent layout
(e.g., "align this view to the bottom right of the screen").
○​ Use Case: Creating complex layouts where the position of one element
depends on another.
3.​ ConstraintLayout:
○​ Description: The most powerful and flexible layout. It allows you to
create complex UIs with a flat view hierarchy by defining constraints
(relationships) between views. It is similar to RelativeLayout but more
advanced and better for performance.
○​ Use Case: The recommended default layout for building complex,
responsive UIs in Android Studio's Layout Editor.
5
4.​ FrameLayout:
○​ Description: The simplest layout type. It stacks child views on top of
each other, with the last child added being on top. It is designed to hold a
single child view.
○​ Use Case: Commonly used as a container for Fragments or for creating
overlapping UI elements like a progress indicator over an image.
5.​ TableLayout:
○​ Description: Arranges child views into rows and columns, similar to an
HTML <table>. You use <TableRow> elements to define each row.
○​ Use Case: Displaying data in a tabular format, like a simple spreadsheet
or a settings screen with key-value pairs.

8. What is the difference between android:gravity and android:layout_gravity


attributes? Provide a simple example using a LinearLayout.
This is a common point of confusion. The key difference is what they control: the
content within a view versus the view itself.
●​ android:gravity:
○​ What it does: Controls the alignment of the content inside a View.
○​ Example: If you apply android:gravity="center" to a TextView, the text
inside the TextView will be centered. The TextView itself will not move.
●​ android:layout_gravity:
○​ What it does: Controls the alignment of the View itself within its
parent container.
○​ Example: If you apply android:layout_gravity="center_horizontal" to a
Button inside a vertical LinearLayout, the entire Button will be moved to
the center of the LinearLayout.
Example using LinearLayout:
Consider a vertical LinearLayout that fills the screen width, containing a Button.
Generated xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_gravity="center_horizontal"
android:gravity="end />
</LinearLayout>

9. What is event handling? Explain three different methods for implementing


an onClick listener for a Button widget.
Event handling is the mechanism for responding to user interactions (events) with
the UI components of an application. An event is an action that the user performs,
such as clicking a button, touching the screen, or typing on the keyboard. An event
listener is an interface that "listens" for these events and executes a piece of code
when the event occurs.
Here are three common methods for implementing an onClick listener for a Button:
6
1. Using the android:onClick XML Attribute:​
This is the simplest method. You declare a public method in your Activity/Fragment
and link it to the button directly in the XML layout file.
In activity_main.xml:​
​ <Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="onMyButtonClick" />
In MainActivity.java: The method must be public, return void, and take a View as a
parameter.​
public void onMyButtonClick(View view) {
Toast.makeText(this, "Button Clicked!", Toast.LENGTH_SHORT).show(); }
2. Using an Anonymous Inner Class:​
This is a very common and flexible approach where you define the listener's
behavior inline where it is set.
In MainActivity.java:​
​ ​ Button myButton = findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button Clicked!",
Toast.LENGTH_SHORT).show();
} });
3. Implementing the View.OnClickListener Interface:​
The Activity or Fragment itself implements the listener interface. This is useful when
you have multiple buttons and want to handle their clicks in a single, centralized
method.
In MainActivity.java:​
// 1. Implement the interface
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myButton1 = findViewById(R.id.myButton1);
Button myButton2 = findViewById(R.id.myButton2);
// 2. Set the listener for each button
myButton1.setOnClickListener(this);
myButton2.setOnClickListener(this);
}
// 3. Implement the single onClick method
@Override
public void onClick(View v) {
if (v.getId() == R.id.myButton1) {
Toast.makeText(this, "Button 1 Clicked!", Toast.LENGTH_SHORT).show();
} else if (v.getId() == R.id.myButton2) {
Toast.makeText(this, "Button 2 Clicked!", Toast.LENGTH_SHORT).show();
}}}

7
10. Draw the Activity Lifecycle diagram. Briefly explain the purpose of the
onCreate(), onResume(), onPause(), and onDestroy() methods.
The Activity Lifecycle is the set of states an Activity goes through from the time it is
created until it is destroyed. The Android OS manages these states, and you can
execute code at different points by overriding the lifecycle callback methods.

Purpose of Key Methods:


●​ onCreate(Bundle savedInstanceState):
○​ When it's called: This is the very first method called when the activity is
created. It is called only once in the activity's entire life.
○​ Purpose: This is where you should perform all your one-time
initializations, such as:
■​ Setting the content view (setContentView()).
■​ Initializing views (findViewById()).
■​ Setting up adapters or binding data to lists.
■​ Restoring the activity's state from the savedInstanceState bundle if
it's being recreated.
●​ onResume():
○​ When it's called: Called just before the activity starts interacting with the
user. The activity is at the top of the activity stack and has user focus.
○​ Purpose: This is the best place to start any animations, open
exclusive-access devices (like the camera), or refresh the UI. It is called
every time the activity comes to the foreground.
●​ onPause():
○​ When it's called: Called when the activity is about to lose focus but is
still partially visible (e.g., when a dialog or another semi-transparent
activity appears on top).
○​ Purpose: This is where you should stop any ongoing processes that
should not continue while paused (like animations or camera previews)
and save any unsaved user data. This method must execute very
quickly.
●​ onDestroy():
○​ When it's called: This is the final callback before the activity is
destroyed. It can be called either because the user finished the activity
(by calling finish() or pressing the back button) or because the system is
temporarily destroying it to save memory.
○​ Purpose: Perform any final cleanup of your activity's resources, such as
releasing database connections, stopping background threads, or
unregistering broadcast receivers.

8
11. What is an Intent? Differentiate between an explicit intent and an implicit
intent.
An Intent is a messaging object that you can use to request an action from another
app component. It is the glue that holds an Android application together, allowing
different components (like Activities, Services, and Broadcast Receivers) to
communicate with each other. You can use Intents for three main purposes:
1.​ Starting an Activity: Launching a new screen.
2.​ Starting a Service: Initiating a background operation.
3.​ Delivering a Broadcast: Sending a system-wide message.
Differentiation:
Feature Explicit Intent Implicit Intent
Target Specifies the exact Does not name a specific component.
component to start by name Instead, it declares a general action to
(e.g., MainActivity.class). perform (e.g., ACTION_VIEW,
The target is known at ACTION_DIAL).
compile time.
Use Used for communication Used to request an action from another
Case within your own application on the device that can
application, where you handle it.
know the exact class name
of the activity or service you
want to start.
How it The Android system delivers The Android system searches for an app
Works the intent directly to the component that has registered an Intent
specified component class. Filter matching the action and data of the
implicit intent. If multiple apps can handle
it, the user may be shown an app
chooser dialog.

Exampl java // Starts SecondActivity java // Asks the system to open a web
e Code explicitly Intent intent = new page Intent intent = new
Intent(this, Intent(Intent.ACTION_VIEW,
SecondActivity.class); Uri.parse("http://www.google.com"));
startActivity(intent); startActivity(intent);

12. How do you declare a new activity in the AndroidManifest.xml file? Explain
the purpose of an <intent-filter>.
The AndroidManifest.xml file is the central configuration file for an Android
application. Every component, including every Activity, must be declared in this file.
Declaring a New Activity:​
You declare a new activity inside the <application> tag using the <activity> element.
The only required attribute is android:name, which specifies the class name of the
activity.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
9
<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>
<activity android:name=".SecondActivity" />
<activity
android:name=".SettingsActivity"
android:label="App Settings" />
</application>
</manifest>
Purpose of <intent-filter>:​
An <intent-filter> is an element within an <activity>, <service>, or <receiver> tag
that specifies the types of implicit intents the component can respond to. It acts
like an advertisement, telling the Android system "I can handle this kind of action."
An <intent-filter> is defined by its sub-elements:
●​ <action>: Declares the intent action it accepts, like ACTION_VIEW (to display
data) or ACTION_SEND (to share data).
●​ <category>: Provides additional information about the action.
CATEGORY_DEFAULT is required for activities to receive implicit intents.
CATEGORY_LAUNCHER means the activity should be shown in the system's
app launcher.
●​ <data>: Declares the type of data the component can handle, specified by
MIME type (e.g., image/jpeg), URI scheme (e.g., http), or other attributes.
In the example above, the <intent-filter> for MainActivity tells the system that this
activity is the main entry point (ACTION_MAIN) for the application and should be
listed in the app launcher (CATEGORY_LAUNCHER).

13. What is a Fragment? List four key differences between an Activity and a
Fragment. Also, draw and explain the Fragment Lifecycle in detail.
A Fragment represents a reusable portion of an application's user interface. A
fragment must always be hosted within an Activity and its lifecycle is directly affected
by the host activity's lifecycle. Fragments are crucial for creating flexible and
adaptive UIs that work on different screen sizes (e.g., showing two fragments
side-by-side on a tablet but one at a time on a phone).
Four Key Differences between an Activity and a Fragment:
Feature Activity Fragment
Purpose Represents a single, focused Represents a modular and
screen in an application (e.g., reusable part of a screen's UI.
login screen, settings screen).
Hosting Is a top-level application Must be hosted inside an Activity.
component and does not need a A single activity can host multiple
host. fragments.
Lifecycle Has its own independent lifecycle Its lifecycle is dependent on and
managed by the Android OS. managed by its host Activity.
10
Manifest Must be declared in the Does not need to be declared in
Declaration AndroidManifest.xml file. the manifest file.

Explanation of Key Lifecycle Methods:


●​ onAttach(): Called when the fragment has been associated with its host
activity.
●​ onCreate(): Called to do initial creation of the fragment (non-UI initialization).
●​ onCreateView(): This is where you inflate the fragment's layout. This
method must return the root View of your fragment's UI.
●​ onViewCreated(): Called immediately after onCreateView() has returned. This
is a good place to set up your views (e.g., find views by ID and set listeners).
●​ onResume(): The fragment is visible and interactive.
●​ onPause(): The fragment is no longer interactive.
●​ onDestroyView(): Called when the view hierarchy associated with the
fragment is being removed. This is where you should clean up any resources
associated with the view.
●​ onDestroy(): Called to do final cleanup of the fragment's state.
●​ onDetach(): Called when the fragment is being disassociated from its host
activity.

14. Differentiate between a Toast and a Snackbar. In which scenario would you
prefer to use a Snackbar?
Toast and Snackbar are both used to show brief, temporary messages to the user
without interrupting their workflow. However, they have key differences in
functionality and appearance.
Feature Toast Snackbar
Action No action. It is a purely Can include an action button.
informational message. The You can add a button (e.g.,
user cannot interact with it. "UNDO", "RETRY") that the user
can tap to perform an action.
Position Can appear anywhere on the Is always anchored to the bottom
screen, but typically appears of the screen.
near the bottom.
11
Appearance A simple, floating grey box with Part of the app's UI layout, often
text. with a colored background. It
animates in from the bottom.
Dismissal Disappears automatically after a Disappears automatically after a
set duration (LENGTH_SHORT duration, but the user can also
or LENGTH_LONG). swipe it away to dismiss it.
When to prefer a Snackbar:​
You should prefer a Snackbar when you want to provide the user with an optional,
lightweight action related to the message you are showing.
Scenario:​
Imagine a user deletes an email in a mail app.
●​ A Toast could say: "Email deleted." This is purely informational.
●​ A Snackbar could say: "Email deleted." and have an "UNDO" button. This is
much more powerful because it gives the user a chance to reverse their action
immediately, which is a great user experience.

15. Differentiate between a ListView and a RecyclerView. Explain why


RecyclerView is preferred for displaying large or dynamic data sets,
referencing the ViewHolder pattern.
ListView is the older component for displaying a scrollable list of items, while
RecyclerView is its modern, more flexible, and more efficient successor.
Feature ListView RecyclerView
View Has a basic form of view Enforces the use of the ViewHolder
Recyclin recycling, but it is not enforced pattern, which makes view recycling
g and can be inefficient. extremely efficient.
Layout Only supports a single, vertical Is highly flexible. It uses a
Manager list layout. LayoutManager to support vertical
lists, horizontal lists, grids, and
staggered grids.
Item Does not have built-in support Has a powerful ItemAnimator system
Animato for item animations (like adding for easily animating item additions,
r or removing items). removals, and movements.
Adapter Uses simpler adapters like Requires a more complex but more
ArrayAdapter and powerful RecyclerView.Adapter.
SimpleCursorAdapter.

Why RecyclerView is Preferred (The ViewHolder Pattern):​


RecyclerView is significantly more performant, especially for large or dynamic lists,
because it strictly enforces the use of the ViewHolder pattern.
Explanation of the ViewHolder Pattern:
1.​ The Problem with ListView: When you scroll a ListView, it frequently calls
findViewById() to find the views (like TextView, ImageView) for each new row
that appears on screen. findViewById() is an expensive operation, and calling
it repeatedly while scrolling can cause lag and jerky movements.
2.​ The RecyclerView Solution: A ViewHolder is a simple object that holds direct
references to the views for a single item in the list.
12
○​ Creation: RecyclerView only creates a small, fixed number of
ViewHolder objects—just enough to fill the screen, plus a few extra for
smooth scrolling.
○​ Recycling: When a user scrolls and an item view moves off the screen,
RecyclerView does not destroy it. Instead, it keeps the ViewHolder in a
pool of "scrap" views.
○​ Rebinding: When a new item needs to be displayed on the screen,
RecyclerView takes an unused ViewHolder from the scrap pool and
simply rebinds it with the new data for that position. It does not need to
call findViewById() again.
This process of recycling views instead of creating new ones and avoiding
repeated findViewById() calls makes RecyclerView incredibly fast and
memory-efficient.

16. What is a web API and what is JSON? Explain the general process of
retrieving contents from a remote server and parsing the JSON response.
Web API (Application Programming Interface):​

A web API is a defined set of rules and protocols that allows different software
applications to communicate with each other over the internet. In the context of
mobile apps, it's typically a service running on a remote server that the mobile app
can send requests to (e.g., "get a list of products") and receive data from.

JSON (JavaScript Object Notation):​


JSON is a lightweight, human-readable data-interchange format. It is the standard
format for data sent and received by web APIs because it is easy for both humans to
read and machines to parse. It represents data in key-value pairs.
●​ JSON Object: { "name": "John", "age": 30 }
●​ JSON Array: [ { "city": "New York" }, { "city": "London" } ]
General Process of Retrieving and Parsing Data:
1.​ Make an HTTP Request: The Android application uses an HTTP client library
(like Retrofit, Volley, or OkHttp) to send a request to a specific API endpoint
(a URL). This is typically an HTTP GET request.
2.​ Receive the Response: The remote server processes the request and sends
back a response. If successful, the response body will contain the requested
data, usually in JSON format (as a string).
3.​ Parse the JSON Response: The raw JSON string is not directly usable. The
application uses a parsing library (like Gson or Moshi) to convert the JSON
string into native Java or Kotlin objects. For example, a JSON object { "name":
"Laptop", "price": 1200 } would be parsed into a Product object in the app.
4.​ Use the Data: Once the JSON is parsed into a list of objects, the application
can use this data to populate its UI, for example, by passing the list to a
RecyclerView adapter to display the products to the user.

13
17. What is the procedure for publishing an application on the Google Play
Store? Explain the importance of generating a signed APK.

Publishing an application on the Google Play Store is the process of making your
app available for download to users worldwide.

Procedure for Publishing:


1.​ Finalize the Application: Thoroughly test the app, ensure it follows Google
Play's policies, and prepare final resources like the app icon.
2.​ Create a Google Play Developer Account: Register for a developer account
on the Google Play Console. This involves paying a one-time registration fee.
3.​ Generate a Signed Release APK or AAB: Before uploading, you must
digitally sign your application with a release key. The modern, recommended
format is the Android App Bundle (AAB).
4.​ Create an App Listing in the Play Console:
○​ Go to the Google Play Console and click "Create app".
○​ Fill out all the required information in the "Store listing" section, including:
■​ App title, short description, and full description.
■​ High-quality screenshots, a feature graphic, and a high-resolution
app icon.
■​ Categorization (e.g., Productivity, Game).
■​ Contact details and a privacy policy.
5.​ Upload the App Bundle (AAB): In the "Production" track, upload your signed
AAB file. Google Play will use this bundle to generate and serve optimized
APKs for each user's device configuration.
6.​ Complete Content Rating: Fill out a questionnaire to determine the age
rating for your app.
7.​ Set Pricing & Distribution: Decide if the app will be free or paid. Select the
countries where you want your app to be available.
8.​ Review and Rollout: Review all the details and, when ready, click "Start
rollout to production". The app will be submitted to Google for review, which
can take from a few hours to several days. Once approved, it will become live
on the Play Store.

Importance of a Signed APK/AAB:​


Generating a signed release build is a critical security step.
●​ Authenticity: The digital signature acts as a verifiable fingerprint that proves
you are the authentic author of the application.
●​ Integrity: It guarantees that the application's code has not been tampered
with or modified since it was signed.
●​ Updates: Android uses the signature to verify updates. An update to an app
will only be installed if it is signed with the exact same key as the original
installation. If you lose your key, you can never update your app again.

14
18. Explain the high-level steps required to implement Google Maps in an
Android application, including how to obtain an API key and display a marker.
Implementing Google Maps allows you to display maps, user locations, and points
of interest within your app.
High-Level Steps:
1. Obtain an API Key:
●​ Go to the Google Cloud Platform (GCP) Console.
●​ Create a new project or select an existing one.
●​ In the navigation menu, go to APIs & Services -> Library.
●​ Search for and enable the "Maps SDK for Android".
●​ Go to APIs & Services -> Credentials.
●​ Click Create Credentials -> API key.
●​ Important: Restrict the API key to prevent unauthorized use. For Android, you
should restrict it by your app's Package Name and SHA-1 certificate
fingerprint.
2. Configure the Android Project:
Add the necessary Google Play services dependency for maps to your app's
build.gradle file.​
Generated groovy​
implementation 'com.google.android.gms:play-services-maps:18.1.0'
Add the API key to your AndroidManifest.xml file inside the <application> tag.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY" />
Also, add the required permissions for internet and location access in the manifest if
needed.
3. Add a Map to the UI:
The easiest way is to add a <fragment> element to your XML layout file, specifying it
as a SupportMapFragment
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
4. Get the Map Object and Display a Marker:
●​ In your Activity or Fragment, you need to get a reference to the GoogleMap
object. This is done asynchronously.
●​ Make your Activity implement the OnMapReadyCallback interface.
●​ In onCreate(), get the fragment and call getMapAsync(this).
●​ The onMapReady(GoogleMap googleMap) callback method will be executed
when the map is loaded and ready. This is where you interact with the map.
Generated java:-
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
15
mapFragment.getMapAsync(this); }
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// 1. Define the location for the marker
LatLng sydney = new LatLng(-34, 151);
// 2. Add a marker at that location
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in
Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}

19. What is a Storyboard in iOS development? Explain the roles of View


Controllers and the View Hierarchy.
Storyboard:​
A Storyboard in iOS development is a visual representation of the user interface of
an application. It is a file (with a .storyboard extension) that you edit in Xcode's
Interface Builder. It allows you to:
●​ Design and lay out individual screens (known as "scenes").
●​ Define the flow and transitions (called "segues") between different screens.
●​ Create prototype cells for table views and collection views.
●​ Visually connect UI elements to the code.
Essentially, it provides a "story" of how the different screens of your app connect and
interact.
Role of View Controllers (UIViewController):​
A View Controller is a fundamental object in iOS that manages a single screen or a
portion of the user interface. Its primary role is to act as the "brain" for a screen. Its
responsibilities include:
●​ Managing the View Hierarchy: It owns and manages the main view and all
its subviews for a screen.
●​ Handling User Events: It responds to user interactions with the views it
manages (e.g., button taps, text entry).
●​ Coordinating with Data (Model): It acts as the intermediary between the data
model (the app's data) and the views (what the user sees), updating the UI
when the data changes and vice versa. This is the "Controller" part of the
Model-View-Controller (MVC) design pattern.
The View Hierarchy:​
The View Hierarchy is the tree-like structure of all the UIView objects that make up
a screen's UI.
●​ At the top of the hierarchy for a screen is the View Controller's main view.
●​ This main view acts as a container for other views (called subviews), such as
UILabel, UIButton, UIImageView, etc.
●​ These subviews can, in turn, contain their own subviews, creating a nested
structure.
Example:​
A login screen's view hierarchy might look like this:
●​ UIView (The main view, managed by LoginViewController)
○​ UIImageView (for the app logo)
○​ UITextField (for the username)
○​ UITextField (for the password)
○​ UIButton (for the "Login" button)
16
20. Draw and explain the directory structure of a standard Android application

When you create a new Android project in Android Studio, it generates a specific
directory structure. This structure is essential for organizing code, resources, and
configuration files in a way that the Android build system can understand. The most
important files and folders are located within the app module.
Visual Diagram of the Key Directory Structure
Here is a simplified tree-view of the most important directories and files:
YourProjectName/
└── app/
├── build/ (Output of the build process)
├── libs/ (For private libraries)
└── src/
├── androidTest/ (Code for instrumentation tests)
├── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── yourproject/
│ │ └── MainActivity.java (or .kt)
│ ├── res/
│ │ ├── drawable/ (Images and shapes)
│ │ ├── layout/ (UI layout files - activity_main.xml)
│ │ ├── mipmap/ (App launcher icons)
│ │ └── values/ (Strings, colors, styles)
│ └── AndroidManifest.xml (The app's manifest file)
└── test/ (Code for local unit tests)
├── build.gradle (Module-level build script)
└── .gitignore
├── build.gradle (Project-level build script)
└── settings.gradle

Explanation of Key Directories and Files


1. app/ Directory​
This is the main module of your application. Most of your work will be done inside
this directory.
●​ app/src/: This is the source folder containing all the code and resource files.
○​ app/src/main/: This directory holds the main source set for your
application.
■​ java/com/example/yourproject/: This is where all your Java or
Kotlin source code files are located. This includes your activities,
fragments, adapters, and other logic classes. The package
structure com.example.yourproject is based on the package name
you chose when creating the project.
■​ res/: This directory contains all the non-code resources for your
application. It is crucial for separating your app's static content
from its logic.
■​ drawable/: For all your image assets (like .png, .jpg) and
custom XML shapes, gradients, and selectors.
■​ layout/: Contains the XML files that define your application's
user interfaces (e.g., activity_main.xml). Each layout file
typically corresponds to an activity or a fragment.
17
■​ mipmap/: Specifically for your application's launcher icons.
Android uses this folder to provide the best quality icon for
different device screen densities.
■​ values/: Contains various XML files that define simple
values.
■​ strings.xml: For all user-facing text (string resources).
■​ colors.xml: For defining the color palette of your app.
■​ styles.xml (or themes.xml): For defining UI themes and
styles.
■​ AndroidManifest.xml: This is the most important configuration file
for your app. It acts as the "table of contents" for the Android
system. It declares the app's components (activities, services),
permissions, hardware features, and other essential information.
○​ app/src/androidTest/: This directory is for your instrumentation tests.
These are tests that run on an actual Android device or emulator and are
used to test the UI and functionality of your app.
○​ app/src/test/: This directory is for your local unit tests. These are tests
that run on your computer's JVM (without needing an Android device)
and are used to test the logic of your classes in isolation.
●​ app/build.gradle (Module-level): This is the build script for the app module. It
is a very important file where you configure module-specific build settings,
such as:
○​ The applicationId.
○​ The minSdkVersion, targetSdkVersion, and compileSdkVersion.
○​ Dependencies for external libraries (e.g., Retrofit, Glide, RecyclerView).
2. Top-Level Project Files
●​ build.gradle (Project-level): This is the top-level build script for your entire
project. It defines the build configurations that apply to all modules in your
project, such as the repository locations (e.g., google(), mavenCentral()) and
the versions of the Android Gradle Plugin.
●​ settings.gradle: This file tells the Gradle build system which modules to
include in the project build. For a simple project, it will typically just include the
app module (include ':app').

18
1. Develop a simple UI that includes an EditText, a Spinner, a CheckBox, and a
RadioButton group. Explain the purpose of each widget.
This question asks for an XML layout and an explanation of the components.
UI Layout (activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<!-- EditText for user text input -->
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name" />
<!-- Spinner for selecting one item from a list -->
<Spinner
android:id="@+id/spinnerCity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp" />
<!-- CheckBox for a single on/off option -->
<CheckBox
android:id="@+id/checkboxTerms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="I agree to the terms and conditions" />
<!-- RadioGroup for selecting one option from a set -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Select your gender:" />
<RadioGroup
android:id="@+id/radioGroupGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
19
</RadioGroup>
</LinearLayout>
Explanation of Each Widget:
●​ EditText: A user interface element that allows the user to enter and edit text. It
is used for text input fields, such as usernames, passwords, or messages.
●​ Spinner: Purpose: A dropdown menu that allows the user to select one value
from a set of options. It is useful when you have a long list of items and want
to save screen space.
●​ CheckBox: A two-state button that can be either checked or unchecked. It is
used for options that are not mutually exclusive (the user can select multiple
checkboxes) or for a single on/off choice, like agreeing to terms.
●​ RadioGroup and RadioButton: RadioButtons are used to allow a user to
select only one option from a set. They must be placed inside a RadioGroup,
which ensures that only one RadioButton within that group can be selected at
a time. They are used for mutually exclusive choices, like selecting a gender
or a shipping method.

2. Provide the specific Java/Kotlin code to demonstrate how to pass data (e.g.,
a string) from one activity to another using an Intent.
This requires writing the code for two activities: a sender and a receiver.
FirstActivity.java (The Sender):
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
EditText editTextMessage = findViewById(R.id.editTextMessage);
Button sendButton = findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the text from the EditText
String message = editTextMessage.getText().toString();

// 1. Create an explicit Intent to start SecondActivity


Intent intent = new Intent(FirstActivity.this, SecondActivity.class);

// 2. Add the data to the Intent using a key-value pair


intent.putExtra("USER_MESSAGE", message);

// 3. Start the new activity


startActivity(intent);
}
});
}
}
20
SecondActivity.java (The Receiver):
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView receivedTextView = findViewById(R.id.receivedTextView);
// 1. Get the Intent that started this activity
Intent intent = getIntent();
// 2. Get the data from the Intent using the same key
// The second parameter is a default value if the key is not found
String receivedMessage = intent.getStringExtra("USER_MESSAGE");
// 3. Display the received data in the TextView
receivedTextView.setText(receivedMessage);
}
}

3. Develop a simple application to demonstrate the implementation of a Popup


Menu with at least three menu items.
This requires a menu resource file and the Activity code to show it.
Step 1: Create a Menu Resource File (res/menu/popup_menu.xml):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_edit"
android:title="Edit" />
<item
android:id="@+id/action_copy"
android:title="Copy" />
<item
android:id="@+id/action_delete"
android:title="Delete" />
</menu>
Step 2: Activity Code (MainActivity.java):
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
21
Button showMenuButton = findViewById(R.id.showMenuButton);
showMenuButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View anchorView) {
// 1. Create a PopupMenu instance
PopupMenu popup = new PopupMenu(MainActivity.this, anchorView);
// 2. Inflate the menu resource
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
// 3. Set a listener for menu item clicks
popup.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_edit) {
Toast.makeText(MainActivity.this, "Edit Clicked",
Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.action_copy) {
Toast.makeText(MainActivity.this, "Copy Clicked",
Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.action_delete) {
Toast.makeText(MainActivity.this, "Delete Clicked",
Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});

// 4. Show the popup menu


popup.show();
}
});
}
}

4. Write the code to create and show an AlertDialog with a title, a message,
and two buttons ("OK" and "Cancel").
This code snippet would typically be placed inside an onClick method in an Activity.
Code Snippet (MainActivity.java):
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// ... onCreate ...
22
public void showAlertDialog(View view) {
// 1. Create a builder for the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Set the properties of the dialog
builder.setTitle("Confirm Action");
builder.setMessage("Are you sure you want to proceed?");
// 3. Set the positive button and its click listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Code to execute when OK is clicked
Toast.makeText(MainActivity.this, "OK Clicked",
Toast.LENGTH_SHORT).show();
}
});
// 4. Set the negative button and its click listener
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Code to execute when Cancel is clicked
Toast.makeText(MainActivity.this, "Cancel Clicked",
Toast.LENGTH_SHORT).show();
dialog.dismiss(); // Dismiss the dialog
}
});
// 5. Create and show the dialog
AlertDialog dialog = builder.create();
dialog.show();
}
}

5. Develop an application to display a simple list of 10 programming


languages in a ListView using an ArrayAdapter.
This requires a layout file and the Activity code.
activity_main.xml:
<ListView
android:id="@+id/listViewLanguages"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.java:
Generated java
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {\
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. Get a reference to the ListView
23
ListView listViewLanguages = findViewById(R.id.listViewLanguages);
// 2. Create the data source (an array of strings)
String[] languages = {
"Java", "Kotlin", "Swift", "Python", "JavaScript",
"C++", "C#", "Ruby", "Go", "Rust"
};
// 3. Create an ArrayAdapter
// The last parameter is the data source
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1, // A built-in layout for a single line of text
languages
);
// 4. Set the adapter on the ListView
listViewLanguages.setAdapter(adapter);
}
}

6. Develop an application to display a gallery of 9 images in a GridView or a


RecyclerView with a GridLayoutManager.
This example uses RecyclerView as it is the modern standard. It requires a layout
for the grid, a layout for each item, and an adapter.
Step 1: activity_main.xml:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerViewGallery"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Step 2: grid_item_layout.xml (For each image):
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imageViewItem"
android:layout_width="120dp"
android:layout_height="120dp"
android:scaleType="centerCrop"
android:padding="4dp" />
(You would need to add 9 sample images to your res/drawable folder, e.g.,
image1.png, image2.png, etc.)
Step 3: MainActivity.java and ImageAdapter.java:
// MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerViewGallery);
// Set the layout manager for a grid with 3 columns
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
int[] images = {
R.drawable.image1, R.drawable.image2, R.drawable.image3,
R.drawable.image4, R.drawable.image5, R.drawable.image6,
R.drawable.image7, R.drawable.image8, R.drawable.image9
24
};
ImageAdapter adapter = new ImageAdapter(images);
recyclerView.setAdapter(adapter);
}
}
// ImageAdapter.java (Can be an inner class or a separate file)
class ImageAdapter extends
RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private int[] imageIds;
public ImageAdapter(int[] imageIds) {
this.imageIds = imageIds;
}
@NonNull
@Override
public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item_layout, parent,
false);
return new ImageViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
holder.imageView.setImageResource(imageIds[position]);
}
@Override
public int getItemCount() {
return imageIds.length;
}
public static class ImageViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ImageViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageViewItem);
}
}
}

7. Write the code for a basic SQLiteOpenHelper class to create a "Student"


table with id, name, and address columns.
This class manages database creation and version management.
DatabaseHelper.java:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Information
private static final String DATABASE_NAME = "School.db";
private static final int DATABASE_VERSION = 1;
// Table Name
public static final String TABLE_STUDENTS = "students";
25
// Table Columns
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ADDRESS = "address";
// SQL query to create the table
private static final String TABLE_CREATE =
"CREATE TABLE " + TABLE_STUDENTS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT NOT NULL, " +
COLUMN_ADDRESS + " TEXT NOT NULL" +
");";
// Constructor
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// This method is called only once, when the database is first created.
db.execSQL(TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This method is called when the database version is increased.
// For a simple app, we can just drop the old table and create a new one.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENTS);
onCreate(db);
}
}

8. Write the specific Java/Kotlin code required to perform INSERT and DELETE
operations on a "Student" table in an SQLite database.
This code would typically reside in a data access class or directly in an Activity,
assuming you have an instance of DatabaseHelper.
Code Snippet (MainActivity.java):
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DatabaseHelper(this);
// Get a writable database
database = dbHelper.getWritableDatabase();
// Example Usage
insertStudent("Alice", "123 Wonderland");
deleteStudent(1); // Delete student with ID 1
}
26
// Method to insert a student
public void insertStudent(String name, String address) {
// ContentValues is used to store a set of key-value pairs
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_NAME, name);
values.put(DatabaseHelper.COLUMN_ADDRESS, address);
// Insert the new row, returning the primary key value of the new row
long newRowId = database.insert(DatabaseHelper.TABLE_STUDENTS, null,
values);
}
// Method to delete a student by their ID
public void deleteStudent(long studentId) {
// Define the 'where' part of the query.
String selection = DatabaseHelper.COLUMN_ID + " = ?";
// Specify arguments in placeholder order.
String[] selectionArgs = { String.valueOf(studentId) };
// Issue SQL statement.
database.delete(DatabaseHelper.TABLE_STUDENTS, selection,
selectionArgs);
}
@Override
protected void onDestroy() {
// Close the database connection when the activity is destroyed
dbHelper.close();
super.onDestroy();
}
}

9. Develop an Android application that functions as a simple calculator. The UI


should have two EditText fields for numbers and four Buttons for addition,
subtraction, multiplication, and division. The result should be displayed in a
TextView.
This requires a layout file and the Activity logic.
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal" />
27
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button android:id="@+id/buttonAdd" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="+" />
<Button android:id="@+id/buttonSubtract"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="-" />
<Button android:id="@+id/buttonMultiply" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="*" />
<Button android:id="@+id/buttonDivide" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="/" />
</LinearLayout>
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="24dp"
android:text="Result: "
android:textSize="24sp" />
</LinearLayout>

MainActivity.java:
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
EditText etNum1, etNum2;
TextView tvResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etNum1 = findViewById(R.id.editTextNumber1);
etNum2 = findViewById(R.id.editTextNumber2);
tvResult = findViewById(R.id.textViewResult);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
}
@Override
public void onClick(View v) {
String num1Str = etNum1.getText().toString();
String num2Str = etNum2.getText().toString();
if (num1Str.isEmpty() || num2Str.isEmpty()) {
tvResult.setText("Result: Please enter both numbers");
return;
}
double num1 = Double.parseDouble(num1Str);
28
double num2 = Double.parseDouble(num2Str);
double result = 0;
int id = v.getId();
if (id == R.id.buttonAdd) {
result = num1 + num2;
} else if (id == R.id.buttonSubtract) {
result = num1 - num2;
} else if (id == R.id.buttonMultiply) {
result = num1 * num2;
} else if (id == R.id.buttonDivide) {
if (num2 == 0) {
tvResult.setText("Result: Cannot divide by zero");
return;
}
result = num1 / num2;
}
tvResult.setText("Result: " + result);
}
}

10. Write a simple Swift function that accepts a string as a parameter and
returns the number of vowels in that string.
This is a basic Swift programming question.
Swift Code:
func countVowels(in text: String) -> Int {
let vowels: [Character] = ["a", "e", "i", "o", "u"]
var vowelCount = 0
// Loop through each character in the input string, converted to lowercase
for character in text.lowercased() {
// Check if the character is in our vowels array
if vowels.contains(character) {
vowelCount += 1
}
}
return vowelCount
}
// --- Example Usage ---
let sampleString = "Hello, Swift Programming!"
let numberOfVowels = countVowels(in: sampleString)
print("The number of vowels is: \(numberOfVowels)") // Output: The number of
vowels is: 6
11. Develop an application that fetches data from a remote API and displays it
in a RecyclerView.
This tests your ability to handle asynchronous network operations and parse JSON,
a core modern development skill.
The Task: Develop an Android application that fetches a list of posts from the
JSONPlaceholder public API (https://jsonplaceholder.typicode.com/posts) and
displays their titles in a RecyclerView.
Key Concepts to Implement:
29
1.​ Add Dependencies: You need to add libraries for networking (like Retrofit)
and JSON parsing (like Gson) to your build.gradle file​
// For Retrofit (Networking)
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
// For Gson (JSON Parsing)
implementation 'com.google.code.gson:gson:2.9.0'
2.​ Add Internet Permission: Add <uses-permission
android:name="android.permission.INTERNET" /> to your
AndroidManifest.xml.
3.​ Create a Data Model Class: A simple Java/Kotlin class (Post.java) to match
the JSON structure​
public class Post {
private int userId;
private int id;
private String title;
private String body;
// Getters and Setters...
public String getTitle() { return title; }
}
4.​ Create a Retrofit API Interface: An interface that defines the API endpoints.​
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiService {


@GET("posts")
Call<List<Post>> getPosts();
}
5.​ Make the Network Call and Update the UI: In your MainActivity, create a
Retrofit instance, make the asynchronous call, and on success, update the
RecyclerView adapter.​
// In MainActivity.java's onCreate()
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<Post>> call = apiService.getPosts();
call.enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call,
Response<List<Post>> response) {
if (response.isSuccessful()) {
List<Post> posts = response.body();
// Create and set an adapter for the RecyclerView with the
fetched posts
// ...
}
30
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
// Handle failure
}
});

12. Develop an application demonstrating communication between two


Fragments within the same Activity.
This is a core pattern for modern, flexible UIs.
The Task: Create an application with a ListFragment and a DetailFragment. The
ListFragment shows a list of items (e.g., "Item 1", "Item 2"). When an item is clicked,
the DetailFragment is shown, displaying the text of the clicked item.
Key Concepts to Implement:
Define an Interface: Create an interface in the ListFragment to communicate back
to the hosting Activity.​
// Inside ListFragment.java
public interface OnItemSelectedListener {
void onItemSelected(String itemText);
}
private OnItemSelectedListener listener;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof OnItemSelectedListener) {
listener = (OnItemSelectedListener) context;
} else {
throw new ClassCastException(context.toString() + " must implement
OnItemSelectedListener");
}
}

Implement the Interface in the Activity: The MainActivity implements this


interface. When the callback is triggered, it passes the data to the DetailFragment.​
// In MainActivity.java
public class MainActivity extends AppCompatActivity implements
ListFragment.OnItemSelectedListener {
@Override
public void onItemSelected(String itemText) {
// Create the detail fragment and pass the data using a Bundle
DetailFragment detailFragment = new DetailFragment();
Bundle args = new Bundle();
args.putString("SELECTED_ITEM", itemText);
detailFragment.setArguments(args);

// Replace the current fragment with the detail fragment


getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, detailFragment)
31
.addToBackStack(null) // Allows user to press back to return to the list
.commit();
}
}
Receive Data in the DetailFragment: In the DetailFragment, retrieve the data from
the arguments Bundle.​
Generated java​
// Inside DetailFragment.java's onViewCreated()
if (getArguments() != null) {
String selectedItem = getArguments().getString("SELECTED_ITEM");
textViewDetail.setText(selectedItem);
}

13. Write the code to fetch data from an SQLite database and display it in a
ListView using a SimpleCursorAdapter.
This tests the direct link between a database query result (Cursor) and a UI list.
The Task: Assuming you have a DatabaseHelper class and a "Student" table, write
the code to fetch all students and display their names in a ListView.
Key Concepts to Implement:
Database Query: Write a method to query the database and return a Cursor. A
Cursor is a pointer to the result set of a database query.​
Generated java​
// In a data source class or Activity
public Cursor fetchAllStudents() {
String[] columns = new String[] { DatabaseHelper.COLUMN_ID,
DatabaseHelper.COLUMN_NAME };
return database.query(DatabaseHelper.TABLE_STUDENTS, columns, null, null,
null, null, null);
}
Use SimpleCursorAdapter: This adapter is specifically designed to map columns
from a Cursor to TextViews in a layout.​
// In MainActivity.java's onCreate()
ListView listView = findViewById(R.id.listView);
Cursor cursor = myDbDataSource.fetchAllStudents(); // Method from step 1
// The columns from the database you want to display
String[] fromColumns = { DatabaseHelper.COLUMN_NAME };
// The View IDs in your list item layout that you want to map the columns to
int[] toViews = { android.R.id.text1 }; // A built-in TextView ID
// Create the SimpleCursorAdapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1, // A simple built-in layout
cursor,
fromColumns,
toViews,
0
);
// Set the adapter on the ListView
listView.setAdapter(adapter);
32
14. Develop an application to demonstrate the use of a ContextMenu.
This tests another important menu type, usually triggered by a long-press.
The Task: Develop an application with a TextView. When the user long-presses the
TextView, a context menu appears with "Copy" and "Cut" options.
Key Concepts to Implement:
Create a Menu Resource File (res/menu/context_menu.xml):

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_copy_context" android:title="Copy" />
<item android:id="@+id/action_cut_context" android:title="Cut" />
</menu>

Register the View for the Context Menu: In your Activity's onCreate() method, tell
Android that a specific view should show a context menu.​

// In MainActivity.java's onCreate()
TextView contextTextView = findViewById(R.id.contextTextView);
registerForContextMenu(contextTextView);
Override onCreateContextMenu: This method is called when the context menu
needs to be built. Here, you inflate your menu resource.

// In MainActivity.java
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu);
}

Override onContextItemSelected: This method is called when a user selects an


item from the context menu.​

// In MainActivity.java
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_copy_context) {
Toast.makeText(this, "Copy selected", Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.action_cut_context) {
Toast.makeText(this, "Cut selected", Toast.LENGTH_SHORT).show();
return true;
}
return super.onContextItemSelected(item);
}

33

You might also like