0% found this document useful (0 votes)
10 views4 pages

Mobile Programming

Mobile programming note

Uploaded by

Demon Gang
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)
10 views4 pages

Mobile Programming

Mobile programming note

Uploaded by

Demon Gang
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

1. What do you mean by sqlite? Explain its features. 5. Define JSON. Explain JSON as a tool for creating 8.

eating 8. Explain the concept of AndroidManifest.xml and its


SQLite is a powerful yet lightweight database solution that API with example. importance in Android development.
is widely used in applications requiring minimal JSON (JavaScript Object Notation) is a lightweight data The AndroidManifest.xml is a crucial configuration file
configuration, fast performance, and reliability. It is interchange format that is easy for humans to read and in every Android app that defines essential information
particularly useful in mobile apps, web browsers, write, and easy for machines to parse and generate. It is about the app to the Android system. It acts like an "ID
embedded systems, and small-scale applications. Its commonly used to exchange data between a client (like an card" for your application, declaring components,
Features: Android app) and a server over the internet. permissions, hardware requirements, and other metadata.
1. ServerlessArchitecture: JSON is widely used in RESTful APIs to send and receive Its important:
SQLite does not require a separate database server to data. When a client sends a request to a server, the server
1. Declares App Components - It registers all essential app
function. Unlike client-server databases (e.g., MySQL), responds with data in JSON format. This makes parts like Activities, Services, Broadcast Receivers and
where an application communicates with a remote database communication between applications simple and efficient. Content Providers that make up the application.
server, SQLite runs directly within the application Example: 2. Defines App Permissions - The file specifies what
process. This eliminates the need for network Request URL: https://example.com/api/user/1 system access the app needs, such as camera or location
configuration, making it ideal for standalone and offline Response (JSON): permissions, for proper functionality.
applications. { 3. Sets Minimum Android Version - It declares the oldest
2. ZeroConfiguration: "id": 1, Android version that can run the app through the
SQLite requires no installation or administration. The "name": "Ram Bahadur", minSdkVersion setting.
entire database is stored in a single cross-platform "email": "[email protected]" 4. Configures App Icon & Name - The manifest
file (e.g., .db or .sqlite), which can be easily copied, } This JSON response contains user data that can be determines how the app appears to users by defining its
backed up, or transferred. easily used by mobile or web applications. display name and launcher icon.
3. Cross-Platform&Portable: 6.Explain the advantage of json over xml. 5. Declares Hardware/Software Features - It lists required
SQLite is compatible with Android, iOS, Windows, Linux, 1. Simpler and Easier to Read: device capabilities like Bluetooth or NFC that the app
macOS, and embedded systems. Since the database is JSON has a clean and human-readable syntax. It is easier depends on to work.
stored in a single file, it can be seamlessly moved between to understand and write compared to XML’s complex6. 9.What is the difference between
different operating systems without compatibility issues. structure. android:layout_gravity and android:gravity in linear
4. ACID-CompliantTransactions: 2. Lightweight and Faster: layout?
SQLite follows ACID (Atomicity, Consistency, Isolation, JSON uses fewer characters, which makes the data 7. android:gravity → Controls the alignment of content
Durability) principles, ensuring data integrity even in smaller in size. This results in faster transmission and inside a View (e.g., centering text in a TextView).
case of crashes or power failures. Every transaction is parsing. 8. android:layout_gravity → Controls the alignment of
treated as a single unit. 3. Better Integration with JavaScript: the View itself within its parent layout (e.g., pushing a
2. Explain advantages and disadvantages of using Since JSON is based on JavaScript syntax, it works more button to the right side of a LinearLayout).
sqlite. efficiently in web and mobile applications, especially 9.in 10. Create an Android app that converts kilometers to
Advantages of SQLite JavaScript-based environments. meters using TableLayout.
1. No Server Needed – Runs directly in your app without 4. Less Overhead: XML (activity_main.xml):
requiring a separate database server. JSON uses key-value pairs without the need for opening 10. <TableLayout
2. Easy Setup – Works immediately with no complex and closing tags, reducing unnecessary code. xmlns:android="http://schemas.android.com/apk/res/andr
configuration or installation. 5. Easier Data Mapping: oid"
3. Single-File Storage – Stores all data in one portable file JSON data can be easily mapped to objects in most
that's easy to manage. programming languages, making it simpler to work with
android:layout_width="match_parent"
4. Fast & Lightweight – Uses minimal resources, making it in development.
android:layout_height="match_parent"
ideal for mobile devices. 7. How do your communication your application with
android:padding="16dp">
5. Reliable Data Safety – Protects data even during crashes remote server? Explain with the help of suitable
with ACID-compliant transactions. example.
6. Disadvantages of SQLite Communication with Remote Server: <TableRow>
1. Single-User Only – Not designed for multiple apps In Android, applications communicate with remote servers <TextView android:text="Kilometers:" />
accessing it simultaneously. using HTTP protocols. This is done by sending requests <EditText android:id="@+id/kmInput"
2. Small-Scale Use – Slows down with very large databases (like GET or POST) and receiving responses, usually in android:inputType="numberDecimal" />
(over 1GB). JSON format. Common libraries used for this are Retrofit, </TableRow>
3. Local Storage Only – Cannot be accessed over a network Volley, or HttpURLConnection.
like server databases. Steps to Communicate with Server: <TableRow>
4. Missing Advanced Features – Lacks stored procedures, i. Create API endpoint on the server. <Button
user roles, and built-in encryption. ii.Use HTTP methods (GET, POST, etc.) to send or
android:id="@+id/convertBtn"
5. Manual Backups Needed – Requires copying the receive data.
android:text="Convert to Meters"
database file yourself for backups. iii.Parse the server response in the app. android:layout_span="2" />
6. 3. How can you establish connection using sqlite in iv. Update the UI based on the response.
</TableRow>
android? Explain with the help of suitable example. Example using Retrofit (GET request):
7. SQLITEOPENER.JAVA public interface ApiService {
public class MyDatabaseHelper extends @GET("users") <TableRow>
SQLiteOpenHelper { Call<List<User>> getUsers(); <TextView android:text="Result (Meters):" />
public MyDatabaseHelper(Context context) { 7. Explain the procedure for publishing signed apk in <TextView android:id="@+id/resultTv" />
super(context, "MyDB", null, 1); play store. </TableRow>
} 1. Create a Developer Account: </TableLayout>
@Override Go to https://play.google.com/console and register for a
public void onCreate(SQLiteDatabase db) { Google Play Developer account by paying a one-time fee. Java(MainActivity.Java)
db.execSQL("CREATE TABLE users(id INTEGER 2. Prepare Signed APK or AAB:
PRIMARY KEY, name TEXT)"); Use Android Studio to build a signed APK or AAB by public class MainActivity extends AppCompatActivity {
} going to Build > Generate Signed Bundle/APK. Use
@Override your keystore credentials to sign the app. @Override
public void onUpgrade(SQLiteDatabase db, int 3. Create a New App: protected void onCreate(Bundle savedInstanceState) {
oldVersion, int newVersion) { In the Play Console, click “Create app” and provide super.onCreate(savedInstanceState);
db.execSQL("DROP TABLE IF EXISTS users"); details such as app name, default language, and app type. setContentView(R.layout.activity_main);
onCreate(db); 4. Fill in App Details:
}} Enter all required information including: Button convertBtn = findViewById(R.id.convertBtn)
4. Explain the process of creating database and tables  App description ;
using sqlite in android.
Extending SQLiteOpenHelper class
 Screenshots EditText kmInput = findViewById(R.id.kmInput);
TextView resultTv = findViewById(R.id.resultTv);
Implementing onCreate() method to create tables  App icon
Implementing onUpgrading() method for schema  Privacy policy URL convertBtn.setOnClickListener(v -> {
changes and using the helper class in your activities.  Category and content rating double km = Double.parseDouble(kmInput.getTex
DatabaseHelper dbHelper = new DatabaseHelper(this); t().toString());
SQLiteDatabase db = dbHelper.getWritableDatabase(); 5. Upload APK/AAB: double meters = km * 1000;
db.execSQL("CREATE TABLE IF NOT EXISTS Go to the Release > Production section, click “Create resultTv.setText(String.valueOf(meters));
products (" +"id INTEGER PRIMARY KEY new release”, and upload your signed APK or AAB file. });
AUTOINCREMENT," + 6. Review and Submit: }
"name TEXT," + After uploading, review all details. then, click on }
"price REAL)"); “Publish” to submit your app for review.
db.close();
11. What is an event? How many ways to handle 14. Difference between Activity and Fragment
events in Android?

An event in Android refers to any action or interaction Feature Activity Fragment


10. What are important attributes in AbsoluteLayout?
that occurs during the lifecycle of an application which
Create a calculator app for multiplication and Independent Dependent on Activity
can trigger a response in the app. Lifecycle
division.
Important Attributes in AbsoluteLayout:  Ways to Handle Events:
lifecycle lifecycle

 android:layout_x → Exact X-coordinate position.


1. setOnClickListener (Anonymous Class)
java Reusable in multiple
Reusability Not reusable
 android:layout_y → Exact Y-coordinate position. button.setOnClickListener(new View.OnClickListener() { activities
Calculator App Example: @Override
XML (activity_main.xml): public void onClick(View v) { Manages full
xml UI Manages part of UI
// Handle click screen UI
<AbsoluteLayout xmlns:android="http://schemas.android. }
com/apk/res/android" }); Needs getActivity() for
android:layout_width="match_parent" 2. Lambda Expression (Java 8+) Context Extends Context
context
android:layout_height="match_parent"> button.setOnClickListener(v -> { /* Handle click */ });
3. Implementing View.OnClickListener in Activity Less flexible UI More flexible (used in
<EditText java Flexibility
android:id="@+id/num1" design ViewPager etc.)
public class MainActivity extends AppCompatActivity im
android:layout_x="50dp" plements View.OnClickListener {
android:layout_y="50dp" 15. What is a menu? Create a popup menu with Edit,
@Override
android:inputType="numberDecimal" /> Copy, Paste, Undo, Redo.
public void onClick(View v) {
A menu in Android is a UI element that provides user
if (v.getId() == R.id.button) { /* Handle click */ }
<EditText options like settings or actions.
}
android:id="@+id/num2" PopupMenu Example:
}
android:layout_x="200dp" XML Menu (res/menu/popup_menu.xml):
4. XML android:onClick Attribute
android:layout_y="50dp" <menu
<Button android:onClick="onButtonClick" />
android:inputType="numberDecimal" /> xmlns:android="http://schemas.android.com/apk/res/andr
java
oid">
public void onButtonClick(View v) { /* Handle click */ }
<Button <item android:id="@+id/edit" android:title="Edit"/>
12.. How do you handle user input and form
android:id="@+id/multiplyBtn" <item android:id="@+id/copy" android:title="Copy"/>
validation in Android?
android:text="Multiply" <item android:id="@+id/paste" android:title="Paste"/>
1. Get Input from Views:
android:layout_x="50dp" <item android:id="@+id/undo" android:title="Undo"/>
java
android:layout_y="150dp" /> <item android:id="@+id/redo" android:title="Redo"/>
EditText email = findViewById(R.id.emailInput);
</menu>
String userEmail = email.getText().toString();
<Button Java Code:
2. Basic Validation (Empty Check, Email Format, etc.):
android:id="@+id/divideBtn" Button btn = findViewById(R.id.btnMenu);
java
android:text="Divide" btn.setOnClickListener(v -> {
if (userEmail.isEmpty()) {
android:layout_x="200dp" PopupMenu popup = new
email.setError("Email cannot be empty!");
android:layout_y="150dp" /> PopupMenu(MainActivity.this, btn);
} else if (!Patterns.EMAIL_ADDRESS.matcher(userEmai
popup.getMenuInflater().inflate(R.menu.popup_menu,
l).matches()) {
<TextView popup.getMenu());
email.setError("Invalid email format!");
android:id="@+id/resultTv" popup.setOnMenuItemClickListener(item -> {
}
android:layout_x="50dp" Toast.makeText(this, item.getTitle() + " clicked",
3. Advanced Validation (Using TextInputLayout):
android:layout_y="250dp" /> Toast.LENGTH_SHORT).show();
xml
</AbsoluteLayout> return true;
<com.google.android.material.textfield.TextInputLayout
Java (MainActivity.java): });
android:id="@+id/emailLayout"
popup.show();
app:errorEnabled="true">
public class MainActivity extends AppCompatActivity { });
<EditText android:id="@+id/emailInput" />
@Override 16. What is Toast? Create an app to input a number
</com.google.android.material.textfield.TextInputLayout
protected void onCreate(Bundle savedInstanceState) { and show factorial result in Toast.
>
super.onCreate(savedInstanceState); A Toast is a small popup notification that provides
TextInputLayout emailLayout = findViewById(R.id.emai
setContentView(R.layout.activity_main); simple, unobtrusive feedback to the user. It briefly shows
lLayout);
a message at the bottom of the screen, and automatically
emailLayout.setError("Invalid email!");
EditText num1 = findViewById(R.id.num1); 4. disappears after a few seconds.
Show Validation Errors:
EditText num2 = findViewById(R.id.num2); o Java Code (inside button click):
Use setError() on EditText or TextInputLayout. EditText input = findViewById(R.id.inputNumber);
Button multiplyBtn = findViewById(R.id.multiplyBt
o Display Toast for general errors:
n); Button btn = findViewById(R.id.btnFactorial);
Toast.makeText(this, "Please fill all fields!",
Button divideBtn = findViewById(R.id.divideBtn); Toast.LENGTH_SHORT).show();
TextView resultTv = findViewById(R.id.resultTv); btn.setOnClickListener(v -> {
13. Why are fragments needed in Android? How can a int num = Integer.parseInt(input.getText().toString());
fragment be added to an activity? long fact = 1;
multiplyBtn.setOnClickListener(v -> { Fragments are reusable portions of UI that can be
double n1 = Double.parseDouble(num1.getText(). for (int i = 1; i <= num; i++) fact *= i;
embedded within activities. Toast.makeText(this, "Factorial: " + fact,
toString()); They are useful because:
double n2 = Double.parseDouble(num2.getText(). Toast.LENGTH_LONG).show();
They support modular UI design (like Master-Detail });
toString()); layout in tablets).
resultTv.setText("Result: " + (n1 * n2)); 17. What dialog boxes can be used in Android apps?
Allow for flexible UI, especially for multi-pane layouts.
}); They can be reused across multiple activities.
Adding a Fragment: Types of dialog boxes in Android:
divideBtn.setOnClickListener(v -> { FragmentManager fragmentManager =
double n1 = Double.parseDouble(num1.getText(). getSupportFragmentManager();
toString()); FragmentTransaction fragmentTransaction =  AlertDialog – for alert messages,
double n2 = Double.parseDouble(num2.getText(). fragmentManager.beginTransaction(); confirmation.
toString()); MyFragment fragment = new MyFragment();  DatePickerDialog – for selecting a date.
resultTv.setText("Result: " + (n1 / n2));
});
fragmentTransaction.add(R.id.fragment_container,  TimePickerDialog – for selecting time.
}
fragment);  Custom Dialog – user-designed layout.
fragmentTransaction.commit();
} XML layout for activity:  ProgressDialog (deprecated) – for showing
<FrameLayout progress.
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
18. Create an app with context menu: Red, Yellow, 20. Create app using SQLite (Hospital DB, Doctor 3. MainActivity.java
Green, Black, Blue. Table, filter by experience). public class MainActivity extends AppCompatActivity {
Steps:
1.Register a view for context menu: DBHelper dbHelper;
1. Create SQLite Helper Class
registerForContextMenu(textView); EditText etExperience;
2. Create menu in onCreateContextMenu(): Button btnFilter;
@Override public class DBHelper extends SQLiteOpenHelper { ListView listDoctors;
public void onCreateContextMenu(ContextMenu menu,
View v, ContextMenu.ContextMenuInfo menuInfo) { public static final String DB_NAME = "HospitalDB"; @Override
super.onCreateContextMenu(menu, v, menuInfo); public static final int DB_VERSION = 1; protected void onCreate(Bundle savedInstanceState) {
menu.setHeaderTitle("Choose Color"); super.onCreate(savedInstanceState);
menu.add(0, v.getId(), 0, "Red"); public DBHelper(Context context) { setContentView(R.layout.activity_main);
menu.add(0, v.getId(), 0, "Yellow"); super(context, DB_NAME, null, DB_VERSION);
menu.add(0, v.getId(), 0, "Green"); } dbHelper = new DBHelper(this);
menu.add(0, v.getId(), 0, "Black");
menu.add(0, v.getId(), 0, "Blue"); @Override etExperience = findViewById(R.id.etExperience);
} public void onCreate(SQLiteDatabase db) { btnFilter = findViewById(R.id.btnFilter);
3. Handle menu selection: String createTable = "CREATE TABLE Doctor (" + listDoctors = findViewById(R.id.listDoctors);
@Override "id INTEGER PRIMARY KEY
public boolean onContextItemSelected(MenuItem item) { AUTOINCREMENT," + btnFilter.setOnClickListener(v -> {
switch (item.getTitle().toString()) { "name TEXT," + String exp = etExperience.getText().toString();
case "Red": textView.setTextColor(Color.RED); "specialization TEXT," + if (!expStr.isEmpty()) {
break; "experience INTEGER)"; int exp = Integer.parseInt(expStr);
case "Yellow": db.execSQL(createTable); showDoctors(exp);
textView.setTextColor(Color.YELLOW); break; } else {
case "Green": // Insert sample data Toast.makeText(this, "Please enter experience",
textView.setTextColor(Color.GREEN); break; db.execSQL("INSERT INTO Doctor (name, Toast.LENGTH_SHORT).show();
case "Black": specialization, experience) VALUES ('Dr. Smith', }
textView.setTextColor(Color.BLACK); break; 'Cardiology', 10)"); }); }
case "Blue": textView.setTextColor(Color.BLUE); db.execSQL("INSERT INTO Doctor (name, private void showDoctors(int minExp) {
break; specialization, experience) VALUES ('Dr. Meera', Cursor cursor =
} 'Neurology', 5)"); dbHelper.getDoctorsByExperience(minExp);
return true; db.execSQL("INSERT INTO Doctor (name, ArrayList<String> list = new ArrayList<>();
} specialization, experience) VALUES ('Dr. Rahul', if (cursor.moveToFirst()) {
19. Create an app to calculate simple interest using a 'Orthopedics', 7)"); do {
custom dialog box. db.execSQL("INSERT INTO Doctor (name, String name =
Custom Dialog Layout (res/layout/dialog_si.xml): specialization, experience) VALUES ('Dr. Asha', cursor.getString(cursor.getColumnIndex("name"));
'Dermatology', 3)"); String spec =
} cursor.getString(cursor.getColumnIndex("specialization")
<LinearLayout ... >
);
<EditText android:id="@+id/principal" ... />
@Override int exp =
<EditText android:id="@+id/rate" ... />
public void onUpgrade(SQLiteDatabase db, int cursor.getInt(cursor.getColumnIndex("experience"));
<EditText android:id="@+id/time" ... />
oldVersion, int newVersion) { list.add(name + " - " + spec + " (" + exp + "
<Button android:id="@+id/calculateBtn"
db.execSQL("DROP TABLE IF EXISTS Doctor"); yrs)");
android:text="Calculate"/>
onCreate(db); } while (cursor.moveToNext());
</LinearLayout>
} } else {
Show Dialog in Activity:
list.add("No doctors found with that experience.");
public Cursor getDoctorsByExperience(int }
Button btn = findViewById(R.id.btnDialog); minExperience) {
btn.setOnClickListener(v -> { SQLiteDatabase db = this.getReadableDatabase(); ArrayAdapter<String> adapter = new
Dialog dialog = new Dialog(this); return db.rawQuery("SELECT * FROM Doctor ArrayAdapter<>(this,
dialog.setContentView(R.layout.dialog_si); WHERE experience >= ?", new android.R.layout.simple_list_item_1, list);
String[]{String.valueOf(minExperience)}); listDoctors.setAdapter(adapter);
EditText p = dialog.findViewById(R.id.principal); } }}
EditText r = dialog.findViewById(R.id.rate); } 22. Explain Asynchronous Tasks (AsyncTask) and
EditText t = dialog.findViewById(R.id.time); 2. activity_main.xml when to use them
Button calc = dialog.findViewById(R.id.calculateBtn); AsyncTask is a class in Android used to perform
background operations (like downloading data or
<LinearLayout accessing a database) without freezing the user interface
calc.setOnClickListener(view -> {
xmlns:android="http://schemas.android.com/apk/res/andr
double principal = (UI). It helps you run time-consuming tasks in the
oid" background and update the UI after the task finishes.Use
Double.parseDouble(p.getText().toString());
android:orientation="vertical" AsyncTask when:
double rate =
android:padding="16dp"
Double.parseDouble(r.getText().toString());
android:layout_width="match_parent"  You need to do a short background task (like
double time = downloading a file, accessing a remote server,
android:layout_height="match_parent">
Double.parseDouble(t.getText().toString()); or a heavy calculation).
double si = (principal * rate * time) / 100;
Toast.makeText(this, "Simple Interest: " + si,
<EditText  You want to update the UI after the task
android:id="@+id/etExperience" completes.
Toast.LENGTH_LONG).show();
dialog.dismiss();
android:hint="Enter minimum experience"  You don’t need complex background threading
android:inputType="number" or parallel execution.
});
android:layout_width="match_parent" 23. What is data persistence in Android, what are
android:layout_height="wrap_content"/> debugging techniques in Android Studio, and what are
dialog.show();
}); Broadcast Receivers and Content Providers?
<Button
21. Explain how to retrieve content from a remote
android:id="@+id/btnFilter"
server. Data persistence in Android refers to saving data
android:text="Filter Doctors"
To retrieve content from a remote server in Android, you permanently using tools like SharedPreferences for key-
android:layout_width="wrap_content"
need to connect your app to the internet and make a value pairs, internal storage for private files, and external
android:layout_height="wrap_content"/>
network request to a server (like an API). First, you add the storage for shared files, ensuring data remains even after
Internet permission in your AndroidManifest.xml. Then, the app is closed. Debugging in Android Studio involves
<ListView
using libraries like Retrofit, Volley, or using Logcat, breakpoints, and the debugger tool to
android:id="@+id/listDoctors"
HttpURLConnection, you send a request (usually a GET identify and fix errors during app development. Broadcast
android:layout_width="match_parent"
or POST) to the server’s URL. The server responds with Receivers listen for system-wide events like battery low or
android:layout_height="wrap_content"/>
data, often in JSON format. You then parse this data and SMS received, while Content Providers allow apps to
</LinearLayout>
display it in your app, like in a TextView or ListView. This securely share and access data such as contacts or media
process must run in the background so it doesn't freeze files.
the app. Libraries like Retrofit make this process easier .
24. Write a Swift program to find largest/smallest of 3 26. Display 8 programming languages in ListView. 30.Develop an Android Studio app to pass name,
numbers using ternary operator. 1. Layout File (activity_main.xml): address, and personal info from Child Activity to
import Foundation <?xml version="1.0" encoding="utf-8"?> Parent Activity.
let a = 25 <LinearLayout 1. ParentActivity.java
let b = 40 xmlns:android="http://schemas.android.com/apk/res/andr public class ParentActivity extends AppCompatActivity {
let c = 15 oid"
android:orientation="vertical" TextView resultText;
// Find Largest android:layout_width="match_parent" ActivityResultLauncher<Intent> launcher;
let largest = (a > b) ? (a > c ? a : c) : (b > c ? b : c) android:layout_height="match_parent">
@Override
// Find Smallest <ListView protected void onCreate(Bundle savedInstanceState) {
let smallest = (a < b) ? (a < c ? a : c) : (b < c ? b : c) android:id="@+id/listView" super.onCreate(savedInstanceState);
android:layout_width="match_parent" setContentView(R.layout.activity_parent);
print("Largest number is: \(largest)") android:layout_height="match_parent"/>
print("Smallest number is: \(smallest)") </LinearLayout> resultText = findViewById(R.id.resultText);
Output: 2. MainActivity.java:
Largest number is: 40 package com.example.listviewapp; launcher = registerForActivityResult(
Smallest number is: 15 new
25. What is view hierarchy in iOS? Write Swift function import android.os.Bundle; ActivityResultContracts.StartActivityForResult(),
to: o Find sum of all elements in 1-D array. o Calculate import android.widget.ArrayAdapter; result -> {
factorial of a number. import android.widget.ListView; if (result.getResultCode() == RESULT_OK) {
In iOS, the view hierarchy refers to the structure of import androidx.appcompat.app.AppCompatActivity; Intent data = result.getData();
UIViews arranged in a tree-like format. Each screen is public class MainActivity extends AppCompatActivity { String name = data.getStringExtra("name");
made up of views (like labels, buttons, images), and these String[] languages = { String address =
views can contain other views (called subviews). The "C", "C++", "Java", "Python", data.getStringExtra("address");
root view is at the top, and all other views are children "JavaScript", "Swift", "Kotlin", "Go" String info = data.getStringExtra("info");
(subviews) under it. Managing the view hierarchy is }; resultText.setText("Name: " + name +
essential for layout, rendering, and handling user "\nAddress: " + address + "\nInfo: " + info);
interaction. @Override }
Swift Function to Find Sum of All Elements in 1-D protected void onCreate(Bundle savedInstanceState) { });
Array super.onCreate(savedInstanceState); findViewById(R.id.openChildBtn).setOnClickListener(v
func sumOfArray(_ numbers: [Int]) -> Int { setContentView(R.layout.activity_main); -> {
return numbers.reduce(0, +) Intent intent = new Intent(this,
} ListView listView = findViewById(R.id.listView); ChildActivity.class);
let nums = [10, 20, 30, 40] launcher.launch(intent);
print("Sum: \(sumOfArray(nums))") // Output: Sum: 100 ArrayAdapter<String> adapter = new });}}
ArrayAdapter<>( 2. ChildActivity.java
Swift Function to Calculate Factorial of a Number this, public class ChildActivity extends AppCompatActivity {
android.R.layout.simple_list_item_1,
languages EditText nameField, addressField, infoField;
func factorial(_ n: Int) -> Int {
);
return n <= 1 ? 1 : n * factorial(n - 1)
@Override
}
listView.setAdapter(adapter); protected void onCreate(Bundle savedInstanceState) {
print("Factorial of 5: \(factorial(5))") // Output: 120
25. Explain MVC pattern }} super.onCreate(savedInstanceState);
28. Develop an ios application to calculate simple setContentView(R.layout.activity_child);
Model: The Model represents the application's data and
business logic. It manages the data, performs data interest.
import UIKit nameField = findViewById(R.id.nameField);
operations, and provides a way to access and modify the
addressField = findViewById(R.id.addressField);
data, independently from how it's presented to the user.
class ViewController: UIViewController { infoField = findViewById(R.id.infoField);
View: The View is responsible for displaying the data to findViewById(R.id.sendBackBtn).setOnClickListener(v -
the user and handling user interactions. It receives data @IBOutlet weak var principalField: UITextField! >{
from the Model (often through the Controller) and presents @IBOutlet weak var timeField: UITextField! String name = nameField.getText().toString();
it in a user-friendly format. Views also handle user input @IBOutlet weak var rateField: UITextField! String address = addressField.getText().toString();
like button taps or text input. @IBOutlet weak var resultLabel: UILabel! String info = infoField.getText().toString();

Controller: The Controller acts as the intermediary @IBAction func calculateInterest(_ sender: UIButton) Intent resultIntent = new Intent();
between the Model and the View. It receives user input { resultIntent.putExtra("name", name);
from the View, updates the Model based on that input, and guard let p = Double(principalField.text ?? ""), resultIntent.putExtra("address", address);
then updates the View to reflect the changes. Essentially, let t = Double(timeField.text ?? ""), resultIntent.putExtra("info", info);
the Controller manages the flow of data and logic between let r = Double(rateField.text ?? "") else { setResult(RESULT_OK, resultIntent);
the Model and the View. resultLabel.text = "Invalid input" finish(); // close child
return });}}
27. compare linear layout with relative layout with } 3. Layout Files (Simplified):
suitable example activity_parent.xml
let si = (p * t * r) / 100 <Button android:id="@+id/openChildBtn"
resultLabel.text = "Simple Interest: \(si)" android:text="Open Child"/>
LinearLayout and RelativeLayout are two commonly <TextView android:id="@+id/resultText"/>
used layout types in Android. LinearLayout arranges UI }
} activity_child.xml
components in a single direction — either vertically or <EditText android:id="@+id/nameField"
horizontally, based on the orientation attribute. It is 29. Explain android architecture.
Android Architecture is a layered stack that provides a android:hint="Name"/>
simple to use but can become inefficient for complex <EditText android:id="@+id/addressField"
designs. For example, if you place a TextView, EditText, structured framework for building Android applications. It android:hint="Address"/>
and Button inside a vertical LinearLayout, they will has four main layers, each serving a different purpose in
the Android operating system. <EditText android:id="@+id/infoField"
appear one below the other in a straight column. android:hint="Personal Info"/>
<Button android:id="@+id/sendBackBtn"
On the other hand, RelativeLayout allows components to android:text="Send Back"/>
be placed relative to each other or to the parent layout. It
offers more flexibility, such as placing one view below
another or aligning a button to the right of a text box. For
example, you can place a TextView at the top of the
screen, and position an EditText just below it, and align a
Button to the right side of the screen using relative rules.

You might also like