Final Mobile Programming
Final Mobile Programming
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 ]
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).
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.
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
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.
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.
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.
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.
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.
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));
}
}
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
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();
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();
}
}
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();
}
}
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;
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);
}
33