Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>Flutter FormatterNew to Visual Studio Code? Get it now.
Flutter Formatter

Flutter Formatter

Binod

|
11 installs
| (0) | Free
A simple extension to convert text to uppercase
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Assignment 17: Flutter REST API Program

Objective

Create employee data (empid, empname, salary, dept) and display it in a ListView using REST API.


PART 1: Project Setup

Step 1: Add HTTP Dependency`

Change View in Android Studio

  1. In Android Studio, change view from Android to Project
  2. This allows you to see all project files

Modify pubspec.yaml

  1. Open pubspec.yaml file
  2. Locate the dependencies: section
  3. Add the following dependency:
dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0
  1. Save the file
  2. Run command in terminal:
flutter pub get

Description: The http package enables making HTTP requests to REST APIs


PART 2: Creating Mock API

Step 2: Generate JSON Data

Create Employee JSON Array

[
  {
    "empid": 101,
    "empname": "John Doe",
    "salary": 50000,
    "dept": "IT"
  },
  {
    "empid": 102,
    "empname": "Jane Smith",
    "salary": 60000,
    "dept": "HR"
  },
  {
    "empid": 103,
    "empname": "Mike Johnson",
    "salary": 55000,
    "dept": "Finance"
  },
  {
    "empid": 104,
    "empname": "Sarah Williams",
    "salary": 65000,
    "dept": "IT"
  }
]

Description: JSON array containing employee records with 4 fields


Step 3: Create Free API Endpoint on Mock.io

Process:

  1. Go to https://mocki.io/
  2. Click "Create Mock API"
  3. Paste your JSON data
  4. Click "Generate Mock Endpoint"
  5. Copy the generated URL (e.g., https://mocki.io/v1/1eabf0c9-fff1-4656-af13-9c957251aa7f)
  6. Save this URL for use in your app

Description: Mock.io provides free hosted JSON endpoints for testing


Step 4: Generate Model Class

Use QuickType.io

  1. Go to https://app.quicktype.io/
  2. Paste your JSON data in left panel
  3. Select Dart as output language
  4. Copy the generated Dart model class
  5. Use this as template for Employee.dart

Description: QuickType automatically generates type-safe model classes from JSON


PART 3: Creating the Flutter Application

Step 5: Create Employee Model (Employee.dart)

Create file: lib/Employee.dart

import 'dart:convert';

// Function to parse JSON array string into List of Employee objects
List<Employee> employeeFromJson(String str) =>
    List<Employee>.from(json.decode(str).map((x) => Employee.fromJson(x)));

// Function to convert List of Employee objects to JSON string
String employeeToJson(List<Employee> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Employee {
  int empid;
  String empname;
  int salary;
  String dept;

  // Constructor with required parameters
  Employee({
    required this.empid,
    required this.empname,
    required this.salary,
    required this.dept,
  });

  // Factory constructor to create Employee from JSON map
  factory Employee.fromJson(Map<String, dynamic> json) => Employee(
        empid: json["empid"],
        empname: json["empname"],
        salary: json["salary"],
        dept: json["dept"],
      );

  // Method to convert Employee object to JSON map
  Map<String, dynamic> toJson() => {
        "empid": empid,
        "empname": empname,
        "salary": salary,
        "dept": dept,
      };
}

Key Components:

  • employeeFromJson(): Converts JSON string to List of Employee objects
  • employeeToJson(): Converts List of Employee objects to JSON string
  • fromJson(): Factory constructor for creating Employee from JSON map
  • toJson(): Converts Employee object to JSON map

Step 6: Create Remote Service (Remote_Services.dart)

Create file: lib/Remote_Services.dart

import 'package:http/http.dart' as http;
import 'Employee.dart';

class RemoteService {
  // Async function to fetch employees from API
  Future<List<Employee>?> getEmployees() async {
    var client = http.Client();
    
    // Parse the API endpoint URL
    var uri = Uri.parse("https://mocki.io/v1/1eabf0c9-fff1-4656-af13-9c957251aa7f");
    
    // Make GET request to the API
    var response = await client.get(uri);
    
    // Check if request was successful (status code 200)
    if (response.statusCode == 200) {
      var json = response.body;
      return employeeFromJson(json);
    }
    
    // Return null if request failed
    return null;
  }
}

Key Components:

  • http.Client(): Creates HTTP client for making requests
  • Uri.parse(): Parses string URL into Uri object
  • client.get(): Makes GET request to API
  • response.statusCode: HTTP status code (200 = success)
  • response.body: Response data as string
  • employeeFromJson(): Converts JSON response to List of Employee objects

Step 7: Create Main Application (main.dart)

Create/modify file: lib/main.dart

import 'package:flutter/material.dart';
import 'Remote_Services.dart';
import 'Employee.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Flutter REST API'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Employee> employees = [];
  var isLoaded = false;

  @override
  void initState() {
    super.initState();
    getData();
  }

  getData() async {
    try {
      final result = await RemoteService().getEmployees();
      if (result != null) {
        setState(() {
          employees = result;
          isLoaded = true;
        });
      }
    } catch (e) {
      print("Error Fetching Employees: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Visibility(
        visible: isLoaded,
        replacement: const Center(child: CircularProgressIndicator()),
        child: ListView.builder(
          itemCount: employees.length,
          itemBuilder: (context, index) {
            return Card(
              margin: const EdgeInsets.all(8.0),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('EMPID: ${employees[index].empid}'),
                    Text('Name: ${employees[index].empname}'),
                    Text('Salary: ${employees[index].salary}'),
                    Text('Dept: ${employees[index].dept}'),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

Key Components Explained:

State Variables

  • employees: List to store fetched employee data
  • isLoaded: Boolean flag to track loading state

initState()

  • Called when widget is first created
  • Calls getData() to fetch employees immediately

getData()

  • async: Function runs asynchronously
  • try-catch: Error handling for API failures
  • await: Waits for API response
  • setState(): Updates UI with fetched data

UI Components

  • Scaffold: Basic app structure
  • AppBar: Top bar with title
  • Visibility: Shows loading or data based on isLoaded
  • CircularProgressIndicator: Loading spinner
  • ListView.builder: Efficiently builds list items
  • Card: Material design card for each employee
  • Column: Vertical layout for employee details

PART 4: Running the Application

Step 8: Run the App

Using Android Studio:

  1. Connect Android device or start emulator
  2. Click the green "Run" button
  3. Select target device
  4. Wait for app to build and launch

Using Command Line:

flutter run

Using Chrome (Web):

flutter run -d chrome

Description: Builds and launches the Flutter application


PART 5: Understanding the Data Flow

Complete Data Flow Diagram

1. App Starts
   ↓
2. initState() called
   ↓
3. getData() executed
   ↓
4. RemoteService.getEmployees() called
   ↓
5. HTTP GET request to Mock.io API
   ↓
6. API returns JSON response
   ↓
7. employeeFromJson() parses JSON
   ↓
8. List<Employee> created
   ↓
9. setState() updates UI
   ↓
10. ListView.builder displays employee cards

Assignment 16: Flutter Database Program (SQFlite)

Objective

Create 2 fields (name, age) and perform CRUD operations: create, insert 5 rows, delete record (by id), update record (by id), and show all records.


Step 1: Add Dependencies

Change view in Android Studio from Android to Project

Open pubspec.yaml and add:

dependencies:
  flutter:
    sdk: flutter
  sqflite: ^2.3.0
  path_provider: ^2.1.1

Save and run:

flutter pub get

Step 2: Create Database Helper (database_helper.dart)

Create file: lib/database_helper.dart

import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static final _dbName = 'student.db';
  static final _dbVersion = 1;
  static final _tableName = 'student';
  static final columnId = '_id';
  static final columnName = 'name';
  static final columnAge = 'age';

  // Singleton pattern
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  static Database? _database;

  Future<Database?> get database async {
    _database ??= await _initiateDatabase();
    return _database;
  }

  _initiateDatabase() async {
    Directory dir = await getApplicationDocumentsDirectory();
    String path = join(dir.path, _dbName);
    return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
  }

  Future _onCreate(Database db, int version) async {
    db.execute(
      "CREATE TABLE $_tableName($columnId INTEGER PRIMARY KEY, $columnName TEXT NOT NULL, $columnAge INTEGER NOT NULL)"
    );
  }

  // INSERT
  Future<int> insert(Map<String, dynamic> row) async {
    Database? db = await instance.database;
    return await db!.insert(_tableName, row);
  }

  // SELECT ALL
  Future<List<Map<String, dynamic>>> showAll() async {
    Database? db = await instance.database;
    return await db!.query(_tableName);
  }

  // UPDATE
  Future<int> update(Map<String, dynamic> row) async {
    Database? db = await instance.database;
    int id = row[columnId];
    return await db!.update(_tableName, row, where: '$columnId=?', whereArgs: [id]);
  }

  // DELETE
  Future<int> delete(int id) async {
    Database? db = await instance.database;
    return await db!.delete(_tableName, where: '$columnId=?', whereArgs: [id]);
  }
}

Step 3: Create Main Application (main.dart)

Create/modify file: lib/main.dart

import 'package:flutter/material.dart';
import 'database_helper.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Database Program',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'SQFlite Program'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _name = TextEditingController();
  final TextEditingController _age = TextEditingController();
  final TextEditingController _id = TextEditingController();

  List<Map<String, dynamic>> _records = [];

  @override
  void initState() {
    super.initState();
    // Uncomment if you want auto-fetch on start
    // _fetchRecords();
  }

  void _clearInputs() {
    _name.clear();
    _age.clear();
  }

  // ADD RECORD
  Future<void> _addRecord() async {
    String name = _name.text.trim();
    int? age = int.tryParse(_age.text.trim());

    if (name.isEmpty || age == null) return;

    int insertedId = await DatabaseHelper.instance.insert({
      DatabaseHelper.columnName: name,
      DatabaseHelper.columnAge: age,
    });

    print("Inserted ID: $insertedId");
    _clearInputs();
    _fetchRecords(); // Uncomment if you don't want auto-refresh
  }

  // UPDATE RECORD
  Future<void> _updateRecord() async {
    int? id = int.tryParse(_id.text.trim());
    String name = _name.text.trim();
    int? age = int.tryParse(_age.text.trim());

    if (id == null || name.isEmpty || age == null) return;

    int updated = await DatabaseHelper.instance.update({
      DatabaseHelper.columnId: id,
      DatabaseHelper.columnName: name,
      DatabaseHelper.columnAge: age,
    });

    print("Updated $updated row(s)");
    _clearInputs();
    _fetchRecords(); // Uncomment if you don't want auto-refresh
  }

  // DELETE RECORD
  Future<void> _deleteRecord() async {
    int? id = int.tryParse(_id.text.trim());
    if (id == null) return;

    int deleted = await DatabaseHelper.instance.delete(id);
    print("Deleted $deleted row(s)");
    _clearInputs();
    _fetchRecords(); // Uncomment if you don't want auto-refresh
  }

  // FETCH ALL RECORDS
  Future<void> _fetchRecords() async {
    List<Map<String, dynamic>> rows = await DatabaseHelper.instance.showAll();
    setState(() {
      _records = rows;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(12.0),
        child: ListView(
          children: [
            TextField(
              controller: _name,
              decoration: const InputDecoration(
                labelText: "Enter Name:",
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _age,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: "Enter Age:",
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _id,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: "ID (for Update/Delete)",
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            ElevatedButton(
              onPressed: _addRecord,
              child: const Text("Add Record"),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _updateRecord,
              child: const Text("Update Record"),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _deleteRecord,
              child: const Text("Delete Record"),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _fetchRecords,
              child: const Text("Show Records"),
            ),
            const SizedBox(height: 20),
            const Text(
              "All Records:",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            ..._records.map((r) => ListTile(
              title: Text("ID: ${r['_id']} Name: ${r['name']} Age: ${r['age']}"),
            )),
          ],
        ),
      ),
    );
  }
}

Step 4: Run the Application

flutter run

Operations Guide

Insert 5 Records:

  1. Enter name and age
  2. Click "Add Record"
  3. Repeat 5 times

Update Record:

  1. Enter ID in "ID" field
  2. Enter new name and age
  3. Click "Update Record"

Delete Record:

  1. Enter ID in "ID" field
  2. Click "Delete Record"

Show All Records:

  • Click "Show Records" button
  • All records display below buttons

Project Structure

lib/
├── main.dart              # Main UI
└── database_helper.dart   # Database operations

Assignment 15: Flutter Registration Form

Objective

Create a registration form that collects user data on the first page and displays it on the second page when submit button is clicked.

Form Components:

  • TextField: Name input
  • Radio buttons: Gender selection
  • Dropdown: City selection
  • Checkboxes: Language selection
  • Switch: Background color toggle

Step 1: Create Main Application (main.dart)

Create/modify file: lib/main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Registration Form'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // State variables
  String? _gender;
  bool _langEng = false;
  bool _langMar = false;
  bool _langHin = false;
  List<String> langs = [];
  String? _selectedCity;
  final List<String> cities = ["Chennai", "Mumbai", "Delhi", "Kolkata", "Bangalore"];
  final TextEditingController _namecon = TextEditingController();
  bool _darkbkgrd = false;

  // Submit form and navigate to result page
  void submitForm() {
    String name = _namecon.text;
    langs.clear();
    if (_langEng) langs.add("English");
    if (_langMar) langs.add("Marathi");
    if (_langHin) langs.add("Hindi");

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ResultPage(
          name: name,
          gender: _gender ?? "Not Selected",
          languages: langs,
          city: _selectedCity ?? "Not Selected",
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Container(
        color: _darkbkgrd ? Colors.lightBlueAccent : Colors.white,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              // TextField for Name
              TextField(
                controller: _namecon,
                decoration: const InputDecoration(
                  labelText: "Enter your Name:",
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 20),

              // Radio buttons for Gender
              const Text("Select Gender:"),
              RadioListTile<String>(
                title: const Text("Male"),
                value: "Male",
                groupValue: _gender,
                onChanged: (newval) {
                  setState(() {
                    _gender = newval;
                  });
                },
              ),
              RadioListTile<String>(
                title: const Text("Female"),
                value: "Female",
                groupValue: _gender,
                onChanged: (newval) {
                  setState(() {
                    _gender = newval;
                  });
                },
              ),

              // Checkboxes for Languages
              const Text("Languages known:"),
              CheckboxListTile(
                title: const Text("English"),
                value: _langEng,
                onChanged: (newval) {
                  setState(() {
                    _langEng = newval ?? false;
                  });
                },
              ),
              CheckboxListTile(
                title: const Text("Hindi"),
                value: _langHin,
                onChanged: (newval) {
                  setState(() {
                    _langHin = newval ?? false;
                  });
                },
              ),
              CheckboxListTile(
                title: const Text("Marathi"),
                value: _langMar,
                onChanged: (newval) {
                  setState(() {
                    _langMar = newval ?? false;
                  });
                },
              ),

              const SizedBox(height: 20),

              // Dropdown for City
              const Text("Select City"),
              DropdownButton<String>(
                value: _selectedCity,
                hint: const Text("Select a City"),
                items: cities
                    .map((city) => DropdownMenuItem(
                          value: city,
                          child: Text(city),
                        ))
                    .toList(),
                onChanged: (newval) {
                  setState(() {
                    _selectedCity = newval;
                  });
                },
              ),

              const SizedBox(height: 20),

              // Submit Button
              ElevatedButton(
                onPressed: submitForm,
                child: const Text("Submit Form"),
              ),

              const SizedBox(height: 20),

              // Switch for Background Color
              SwitchListTile(
                title: const Text("Dark Background"),
                value: _darkbkgrd,
                onChanged: (newval) {
                  setState(() {
                    _darkbkgrd = newval;
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// Result Page to display submitted data
class ResultPage extends StatelessWidget {
  final String name;
  final String gender;
  final List<String> languages;
  final String city;

  const ResultPage({
    super.key,
    required this.name,
    required this.gender,
    required this.languages,
    required this.city,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Result")),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("Name: $name", style: const TextStyle(fontSize: 20)),
            Text("Gender: $gender", style: const TextStyle(fontSize: 20)),
            Text(
              "Languages: ${languages.isEmpty ? "None" : languages.join(", ")}",
              style: const TextStyle(fontSize: 20),
            ),
            Text("City: $city", style: const TextStyle(fontSize: 20)),
          ],
        ),
      ),
    );
  }
}

Step 2: Run the Application

flutter run

Assignment 14: Flutter BMI Calculator

Objective

Create a BMI calculator with two text fields (weight, height), a calculate button, and display the result with BMI category.


Step 1: Create Main Application (main.dart)

Create/modify file: lib/main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Body Mass Index Calculator'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var textwcon = TextEditingController();
  var texthcon = TextEditingController();
  String s = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // Weight TextField
            TextField(
              controller: textwcon,
              decoration: const InputDecoration(
                labelText: "Enter Weight in Kgs",
              ),
              keyboardType: TextInputType.number,
              style: const TextStyle(
                fontSize: 22,
              ),
            ),

            // Height TextField
            TextField(
              controller: texthcon,
              decoration: const InputDecoration(
                labelText: "Enter Height in Meters",
              ),
              keyboardType: TextInputType.number,
              style: const TextStyle(
                fontSize: 22,
              ),
            ),

            // Calculate Button
            ElevatedButton(
              onPressed: () {
                setState(() {
                  double wei = double.parse(textwcon.text);
                  double hei = double.parse(texthcon.text);
                  double bmi = wei / (hei * hei);
                  
                  print("Calculated BMI: $bmi");
                  
                  String category;
                  if (bmi < 18.5) {
                    category = "Underweight";
                  } else if (bmi >= 18.5 && bmi < 24.9) {
                    category = "Normal Weight";
                  } else if (bmi >= 25 && bmi < 29.9) {
                    category = "Overweight";
                  } else {
                    category = "Obese";
                  }
                  
                  s = "${bmi.toStringAsFixed(2)} $category";
                });
              },
              child: const Text("Calculate"),
            ),

            const SizedBox(height: 20),

            // Result Display
            Text(
              "BMI: $s",
              style: const TextStyle(
                color: Colors.blue,
                fontSize: 24,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Step 2: Run the Application

flutter run

How to Use

  1. Enter weight in kilograms (e.g., 70)
  2. Enter height in meters (e.g., 1.75)
  3. Click "Calculate" button
  4. View BMI result with category

BMI Formula

BMI = Weight (kg) / (Height (m))²

BMI Categories

BMI Range Category
< 18.5 Underweight
18.5 - 24.9 Normal Weight
25.0 - 29.9 Overweight
≥ 30.0 Obese

Example Calculations

Example 1:

  • Weight: 70 kg
  • Height: 1.75 m
  • BMI: 70 / (1.75 × 1.75) = 22.86
  • Category: Normal Weight

Example 2:

  • Weight: 85 kg
  • Height: 1.70 m
  • BMI: 85 / (1.70 × 1.70) = 29.41
  • Category: Overweight

Below is a clean, neat, ready-to-copy Notepad format for your Assignment 13 – Fetching Data using REST API (Volley, OkHttp, Retrofit) with:

✔ Steps ✔ JSON creation ✔ Permissions ✔ build.gradle dependencies ✔ activity_main.xml ✔ Full code for all 3 approaches ✔ Output sections (blank – since you add screenshot)

No emojis.


Assignment 13 – Fetching Data Using REST API (Android)


Create JSON Data (Employee)

Fields: eno, ename, dept, salary

Example JSON (JSONArray):

[
  {
    "eno": 1,
    "ename": "John",
    "dept": "IT",
    "salary": 40000
  },
  {
    "eno": 2,
    "ename": "Sneha",
    "dept": "HR",
    "salary": 45000
  }
]

Use any mock API service: https://mocki.io


A. Using Volley Library

Step 1: Add Internet Permission

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Step 2: Add Volley Dependency (build.gradle.kts)

implementation("com.android.volley:volley:1.2.1")

Step 3: 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="20dp">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch Data" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="10dp" />
</LinearLayout>

Step 4: MainActivity.java

package com.alonex.volleyeg;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    Button btnfetch;
    TextView tv;
    String url = "https://mocki.io/v1/9dc2d9d3-18fa-42ef-8e1a-8f9b7c881f0f";
    JsonArrayRequest jsonArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.tv);
        btnfetch = findViewById(R.id.button);

        btnfetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchData();
            }
        });
    }

    private void fetchData() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringBuffer buffer = new StringBuffer();

        jsonArray = new JsonArrayRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        JSONObject obj = null;
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                obj = response.getJSONObject(i);

                                buffer.append("Employee Number: " + obj.getString("eno")).append("\n");
                                buffer.append("Name: " + obj.getString("ename")).append("\n");
                                buffer.append("Department: " + obj.getString("dept")).append("\n");
                                buffer.append("Salary: " + obj.getString("salary")).append("\n\n");

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        tv.setText(buffer.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        tv.setText("Volley Error: " + error.getMessage());
                    }
                });

        queue.add(jsonArray);
    }
}

Output:

(Attach screenshot)


B. Using OkHttp Library

Step 1: Create JSON Object (JSONObject format)

{
  "employees": [
    {
      "eno": 26,
      "ename": "Thomas",
      "dept": "HR",
      "salary": 40000
    }
  ]
}

Step 2: Add Internet Permission

<uses-permission android:name="android.permission.INTERNET"/>

Step 3: Add OkHttp Dependency

implementation("com.squareup.okhttp3:okhttp:4.11.0")

Step 4: activity_main.xml

(Same as previous)

Step 5: MainActivity.java

package com.alonex.okhttp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    Button btnfetch;
    TextView tv;
    String url = "https://mocki.io/v1/a19b6146-e4c0-4009-a295-fe9d7c774d8a";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.tv);
        btnfetch = findViewById(R.id.button);

        btnfetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    okhttpfetch();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void okhttpfetch() throws IOException {

        OkHttpClient client = new OkHttpClient();
        Request req = new Request.Builder().url(url).build();

        client.newCall(req).enqueue(new Callback() {

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                call.cancel();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                String str = response.body().string();
                StringBuffer buffer = new StringBuffer();

                try {
                    JSONObject obj = new JSONObject(str);
                    JSONArray arr = obj.optJSONArray("employees");

                    for (int i = 0; i < arr.length(); i++) {
                        JSONObject emp = arr.getJSONObject(i);

                        buffer.append("E.No.: " + emp.getString("eno")).append("\n");
                        buffer.append("Name: " + emp.getString("ename")).append("\n");
                        buffer.append("Department: " + emp.getString("dept")).append("\n");
                        buffer.append("Salary: " + emp.getString("salary")).append("\n\n");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                tv.setText(buffer.toString());
            }
        });
    }
}

Output:

(Attach screenshot)


C. Using Retrofit Library

Step 1: Add Internet Permission

<uses-permission android:name="android.permission.INTERNET"/>

Step 2: Add Retrofit Dependencies

implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.7.2")

Step 3: JSON Endpoint (JSONArray)

Example from mocki.io

Step 4: Api.java

package com.alonex.retrofit;

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {
    String BASE_URL = "https://mocki.io/v1/";

    @GET("4c36c134-bf06-4960-86dc-32ca7265e58d")
    Call<List<employee>> getemployee();
}

Step 5: employee.java

package com.alonex.retrofit;

public class employee {

    private int eno, salary;
    private String ename, dept;

    public employee(int eno, int salary, String ename, String dept) {
        this.eno = eno;
        this.salary = salary;
        this.ename = ename;
        this.dept = dept;
    }

    public int getEno() {
        return eno;
    }

    public int getSalary() {
        return salary;
    }

    public String getEname() {
        return ename;
    }

    public String getDept() {
        return dept;
    }
}

Step 6: 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="20dp">

    <Button
        android:id="@+id/btn"
        android:text="Fetch Data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="10dp" />
</LinearLayout>

Step 7: MainActivity.java

package com.alonex.retrofit;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    TextView tv;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.textView);
        btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchData();
            }
        });
    }

    private void fetchData() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = retrofit.create(Api.class);

        Call<List<employee>> call = api.getemployee();

        call.enqueue(new Callback<List<employee>>() {
            @Override
            public void onResponse(Call<List<employee>> call, Response<List<employee>> response) {

                List<employee> emp = response.body();
                StringBuffer buff = new StringBuffer();

                for (employee e : emp) {

                    buff.append("\n\n Employee No.: " + e.getEno());
                    buff.append("\n Employee Name: " + e.getEname());
                    buff.append("\n Department: " + e.getDept());
                    buff.append("\n Salary: " + e.getSalary());
                }

                tv.setText(buff);
            }

            @Override
            public void onFailure(Call<List<employee>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_LONG).show();
            }
        });
    }
}

Output:

(Attach screenshot)


If you want, I can also prepare this as a PDF or DOCX for printing/submission.


Below is a clean, neat, ready-to-copy Notepad format for your Assignment 13 – Fetching Data using REST API (Volley, OkHttp, Retrofit) with:

✔ Steps ✔ JSON creation ✔ Permissions ✔ build.gradle dependencies ✔ activity_main.xml ✔ Full code for all 3 approaches ✔ Output sections (blank – since you add screenshot)

No emojis.


Assignment 13 – Fetching Data Using REST API (Android)


Create JSON Data (Employee)

Fields: eno, ename, dept, salary

Example JSON (JSONArray):

[
  {
    "eno": 1,
    "ename": "John",
    "dept": "IT",
    "salary": 40000
  },
  {
    "eno": 2,
    "ename": "Sneha",
    "dept": "HR",
    "salary": 45000
  }
]

Use any mock API service: https://mocki.io


A. Using Volley Library

Step 1: Add Internet Permission

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Step 2: Add Volley Dependency (build.gradle.kts)

implementation("com.android.volley:volley:1.2.1")

Step 3: 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="20dp">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fetch Data" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="10dp" />
</LinearLayout>

Step 4: MainActivity.java

package com.alonex.volleyeg;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    Button btnfetch;
    TextView tv;
    String url = "https://mocki.io/v1/9dc2d9d3-18fa-42ef-8e1a-8f9b7c881f0f";
    JsonArrayRequest jsonArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.tv);
        btnfetch = findViewById(R.id.button);

        btnfetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchData();
            }
        });
    }

    private void fetchData() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringBuffer buffer = new StringBuffer();

        jsonArray = new JsonArrayRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        JSONObject obj = null;
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                obj = response.getJSONObject(i);

                                buffer.append("Employee Number: " + obj.getString("eno")).append("\n");
                                buffer.append("Name: " + obj.getString("ename")).append("\n");
                                buffer.append("Department: " + obj.getString("dept")).append("\n");
                                buffer.append("Salary: " + obj.getString("salary")).append("\n\n");

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        tv.setText(buffer.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        tv.setText("Volley Error: " + error.getMessage());
                    }
                });

        queue.add(jsonArray);
    }
}

Output:

(Attach screenshot)


B. Using OkHttp Library

Step 1: Create JSON Object (JSONObject format)

{
  "employees": [
    {
      "eno": 26,
      "ename": "Thomas",
      "dept": "HR",
      "salary": 40000
    }
  ]
}

Step 2: Add Internet Permission

<uses-permission android:name="android.permission.INTERNET"/>

Step 3: Add OkHttp Dependency

implementation("com.squareup.okhttp3:okhttp:4.11.0")

Step 4: activity_main.xml

(Same as previous)

Step 5: MainActivity.java

package com.alonex.okhttp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    Button btnfetch;
    TextView tv;
    String url = "https://mocki.io/v1/a19b6146-e4c0-4009-a295-fe9d7c774d8a";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.tv);
        btnfetch = findViewById(R.id.button);

        btnfetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    okhttpfetch();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void okhttpfetch() throws IOException {

        OkHttpClient client = new OkHttpClient();
        Request req = new Request.Builder().url(url).build();

        client.newCall(req).enqueue(new Callback() {

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                call.cancel();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                String str = response.body().string();
                StringBuffer buffer = new StringBuffer();

                try {
                    JSONObject obj = new JSONObject(str);
                    JSONArray arr = obj.optJSONArray("employees");

                    for (int i = 0; i < arr.length(); i++) {
                        JSONObject emp = arr.getJSONObject(i);

                        buffer.append("E.No.: " + emp.getString("eno")).append("\n");
                        buffer.append("Name: " + emp.getString("ename")).append("\n");
                        buffer.append("Department: " + emp.getString("dept")).append("\n");
                        buffer.append("Salary: " + emp.getString("salary")).append("\n\n");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                tv.setText(buffer.toString());
            }
        });
    }
}

Output:

(Attach screenshot)


C. Using Retrofit Library

Step 1: Add Internet Permission

<uses-permission android:name="android.permission.INTERNET"/>

Step 2: Add Retrofit Dependencies

implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.7.2")

Step 3: JSON Endpoint (JSONArray)

Example from mocki.io

Step 4: Api.java

package com.alonex.retrofit;

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {
    String BASE_URL = "https://mocki.io/v1/";

    @GET("4c36c134-bf06-4960-86dc-32ca7265e58d")
    Call<List<employee>> getemployee();
}

Step 5: employee.java

package com.alonex.retrofit;

public class employee {

    private int eno, salary;
    private String ename, dept;

    public employee(int eno, int salary, String ename, String dept) {
        this.eno = eno;
        this.salary = salary;
        this.ename = ename;
        this.dept = dept;
    }

    public int getEno() {
        return eno;
    }

    public int getSalary() {
        return salary;
    }

    public String getEname() {
        return ename;
    }

    public String getDept() {
        return dept;
    }
}

Step 6: 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="20dp">

    <Button
        android:id="@+id/btn"
        android:text="Fetch Data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="10dp" />
</LinearLayout>

Step 7: MainActivity.java

package com.alonex.retrofit;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    TextView tv;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.textView);
        btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchData();
            }
        });
    }

    private void fetchData() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = retrofit.create(Api.class);

        Call<List<employee>> call = api.getemployee();

        call.enqueue(new Callback<List<employee>>() {
            @Override
            public void onResponse(Call<List<employee>> call, Response<List<employee>> response) {

                List<employee> emp = response.body();
                StringBuffer buff = new StringBuffer();

                for (employee e : emp) {

                    buff.append("\n\n Employee No.: " + e.getEno());
                    buff.append("\n Employee Name: " + e.getEname());
                    buff.append("\n Department: " + e.getDept());
                    buff.append("\n Salary: " + e.getSalary());
                }

                tv.setText(buff);
            }

            @Override
            public void onFailure(Call<List<employee>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_LONG).show();
            }
        });
    }
}

Below is your Assignment 12 – GPS Location in clean step-by-step guide format, ready to copy into Notepad.


Assignment 12 – GPS Location

Write an Android program to show the current location.


Step 1: Add Permissions in AndroidManifest.xml

(Add inside the <manifest> tag)

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>

Step 2: 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="20dp">

    <Button
        android:id="@+id/btntrack"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Track Location" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textSize="18sp" />

</LinearLayout>

Step 3: MainActivity.java

package com.alonex.gpslocation;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends AppCompatActivity implements LocationListener {

    TextView tv;
    Button btnt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.textView);
        btnt = findViewById(R.id.btntrack);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        }

        btnt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocation();
            }
        });
    }

    private void getLocation() {
        LocationManager manager = (LocationManager)
                getApplicationContext().getSystemService(LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }

        manager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                5000,
                5,
                MainActivity.this
        );
    }

    @Override
    public void onLocationChanged(@NonNull Location location) {
        try {
            Geocoder geo = new Geocoder(this);
            double lat = location.getLatitude();
            double lon = location.getLongitude();

            List<Address> addressList = geo.getFromLocation(lat, lon, 1);
            String address = addressList.get(0).getAddressLine(0);

            tv.setText("Latitude: " + lat + "\n"
                    + "Longitude: " + lon + "\n"
                    + "Address: " + address);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

(Add screenshot here)


If you want, I can prepare Assignment 13 again in this same clean format.


Below is Assignment 11 – Audio Video Program in your required clean guide format (steps + XML + code, no explanation, no output screenshot).


Assignment 11 – Audio Video Program

Write an Android program to play audio and video.


Step 1: Add Media Files to res/raw/ Folder

Create a folder:

app/src/main/res/raw/

Add:

sample.mp3      (for audio)
samplev.mp4     (for video)

Step 2: 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="20dp">

    <Button
        android:id="@+id/btnplay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play Audio" />

    <Button
        android:id="@+id/btnpause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pause Audio" />

    <Button
        android:id="@+id/btnstop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Audio" />

    <VideoView
        android:id="@+id/vv"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_marginTop="20dp" />

    <Button
        android:id="@+id/btnplayv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Play Video" />

</LinearLayout>

Step 3: MainActivity.java

package com.alonex.audiovideo;

import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    VideoView vv;
    Button aplay, apause, astop, vplay;
    MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        vv = findViewById(R.id.vv);
        aplay = findViewById(R.id.btnplay);
        apause = findViewById(R.id.btnpause);
        astop = findViewById(R.id.btnstop);
        vplay = findViewById(R.id.btnplayv);

        aplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playAudio();
            }
        });

        apause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mp != null) {
                    mp.pause();
                    Toast.makeText(getApplicationContext(), "Audio Paused", Toast.LENGTH_LONG).show();
                }
            }
        });

        astop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mp != null) {
                    mp.stop();
                    mp = null;
                    Toast.makeText(getApplicationContext(), "Audio Stopped", Toast.LENGTH_LONG).show();
                }
            }
        });

        vplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playVideo();
            }
        });
    }

    private void playVideo() {
        String path = "android.resource://" + getPackageName() + "/" + R.raw.samplev;
        Uri uri = Uri.parse(path);
        vv.setVideoURI(uri);

        MediaController mc = new MediaController(this);
        vv.setMediaController(mc);
        vv.start();
        mc.setAnchorView(vv);

        Toast.makeText(getApplicationContext(), "Video played", Toast.LENGTH_LONG).show();
    }

    private void playAudio() {
        if (mp == null) {
            mp = MediaPlayer.create(getApplicationContext(), R.raw.sample);

            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
        }

        mp.start();
        Toast.makeText(getApplicationContext(), "Audio Played", Toast.LENGTH_LONG).show();
    }
}

Below is Assignment 10 – Image Animation & Processing in your clean copy-paste guide format.


Assignment 10 – Image Animation & Processing

Write an Android program to perform simple image animations (translate, rotate, scale, fade), invert image, and monochrome image.


Step 1: Add Image in Drawable Folder

Place an image named:

pixels.png  (or .jpg)

Location:

app/src/main/res/drawable/pixels.png

Step 2: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="20dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="250dp"
            android:layout_height="250dp"
            android:layout_gravity="center"
            android:src="@drawable/pixels" />

        <Button
            android:id="@+id/btntranslate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Translate" />

        <Button
            android:id="@+id/btnrotat"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Rotate" />

        <Button
            android:id="@+id/btnfade"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Fade" />

        <Button
            android:id="@+id/btnsca"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Scale" />

        <Button
            android:id="@+id/btninv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Invert Image" />

        <Button
            android:id="@+id/monobtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Monochrome" />

        <Button
            android:id="@+id/btnreset"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Reset" />

    </LinearLayout>
</ScrollView>

Step 3: MainActivity.java

package com.alonex.animationeg;

import androidx.appcompat.app.AppCompatActivity;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    Button btntrans, btnrot, btnfade, btnsc, btninv, btnmono, btnres;
    ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btntrans = findViewById(R.id.btntranslate);
        btnrot = findViewById(R.id.btnrotat);
        btnfade = findViewById(R.id.btnfade);
        btnsc = findViewById(R.id.btnsca);
        img = findViewById(R.id.imageView);
        btninv = findViewById(R.id.btninv);
        btnmono = findViewById(R.id.monobtn);
        btnres = findViewById(R.id.btnreset);

        btnres.setOnClickListener(v -> resetImage());

        btnmono.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Drawable d2 = getResources().getDrawable(R.drawable.pixels, getTheme());
                Bitmap bitimg = ((BitmapDrawable) d2).getBitmap();
                Bitmap newimg = toGrayscale(bitimg);
                img.setImageBitmap(newimg);
            }
        });

        btntrans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                translate(v);
            }
        });

        btnsc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scale(v);
            }
        });

        btnrot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rotate();
            }
        });

        btnfade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fade(v);
            }
        });

        btninv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Drawable d2 = getResources().getDrawable(R.drawable.pixels, getTheme());
                Bitmap bitimg = ((BitmapDrawable) d2).getBitmap();
                Bitmap newimg = invertImage(bitimg);
                img.setImageBitmap(newimg);
            }
        });
    }

    private void resetImage() {
        img.setAlpha(1f);
        img.setRotation(0f);
        img.setScaleX(1f);
        img.setScaleY(1f);
        img.setX(0f);
        img.setY(0f);
        img.setImageResource(R.drawable.pixels);
    }

    private Bitmap invertImage(Bitmap bitimg) {
        Bitmap finalimg = Bitmap.createBitmap(bitimg.getWidth(), bitimg.getHeight(), bitimg.getConfig());
        int A, R, G, B;
        int pixelcolor;
        int h = bitimg.getHeight();
        int w = bitimg.getWidth();

        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                pixelcolor = bitimg.getPixel(x, y);
                A = Color.alpha(pixelcolor);
                R = 255 - Color.red(pixelcolor);
                G = 255 - Color.green(pixelcolor);
                B = 255 - Color.blue(pixelcolor);
                finalimg.setPixel(x, y, Color.argb(A, R, G, B));
            }
        }
        return finalimg;
    }

    private void fade(View v) {
        ObjectAnimator alphani = ObjectAnimator.ofFloat(img, View.ALPHA, 1.0f, 0.5f);
        alphani.setDuration(500);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(alphani);
        set.start();
    }

    private void rotate() {
        ObjectAnimator r = ObjectAnimator.ofFloat(img, "rotation", 0f, 270f);
        r.setDuration(500);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(r);
        set.start();
    }

    private void scale(View v) {
        ObjectAnimator scalex = ObjectAnimator.ofFloat(img, "scaleX", 2f);
        ObjectAnimator scaley = ObjectAnimator.ofFloat(img, "scaleY", 2f);
        scalex.setDuration(500);
        scaley.setDuration(500);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(scalex, scaley);
        set.start();
    }

    private void translate(View v) {
        ObjectAnimator anix = ObjectAnimator.ofFloat(img, "x", 500);
        ObjectAnimator aniy = ObjectAnimator.ofFloat(img, "y", 100);
        anix.setDuration(500);
        aniy.setDuration(500);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(anix, aniy);
        set.start();
    }

    private Bitmap toGrayscale(Bitmap bitimg) {
        Bitmap finalimg = Bitmap.createBitmap(bitimg.getWidth(), bitimg.getHeight(), bitimg.getConfig());

        int A, R, G, B;
        int pixelcolor;
        int h = bitimg.getHeight();
        int w = bitimg.getWidth();

        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                pixelcolor = bitimg.getPixel(x, y);
                A = Color.alpha(pixelcolor);
                R = Color.red(pixelcolor);
                G = Color.green(pixelcolor);
                B = Color.blue(pixelcolor);

                int gray = (int) (0.299 * R + 0.587 * G + 0.114 * B);
                finalimg.setPixel(x, y, Color.argb(A, gray, gray, gray));
            }
        }
        return finalimg;
    }
}

Output:

  1. Translate
  2. Rotate
  3. Fade
  4. Scale
  5. Invert
  6. Monochrome

Below is Assignment 9 – Firebase Realtime Database in your clean step-by-step guide format.


Assignment 9 – Firebase Realtime Database

Create Employee table with fields: eno, ename, salary, dept Perform: Insert, Show, Delete, Update


Step 1: Setting up Firebase in Android Studio

1. Open:

Tools → Firebase

2. Select:

Realtime Database → Get started with Realtime Database (Java)

3. Click:

Connect to Firebase

4. Create Firebase project by entering a project name.

5. After connection, click:

Add the Realtime Database SDK to your app → Accept Changes


Step 2: Create Firebase Realtime Database

1. Go to Firebase Console → Realtime Database

2. Click Create Database

3. Choose region

4. Select Start in Test Mode

5. Make sure test rules allow read/write:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Step 3: 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="20dp">

    <EditText
        android:id="@+id/edtno"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Employee No" />

    <EditText
        android:id="@+id/edtname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Employee Name" />

    <EditText
        android:id="@+id/edtsal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Salary" />

    <Spinner
        android:id="@+id/deptspin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/addbtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Record" />

    <Button
        android:id="@+id/displaybtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Records" />

    <Button
        android:id="@+id/deletebtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete Record" />

    <Button
        android:id="@+id/updatebtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Update Record" />

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Step 4: Employee.java

package com.alonex.firebaseeg;

public class Employee {

    private String id;
    private int eno, salary;
    private String ename, department;

    public Employee() {
    }

    public Employee(String id, int eno, String ename, int salary, String department) {
        this.id = id;
        this.eno = eno;
        this.ename = ename;
        this.salary = salary;
        this.department = department;
    }

    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }

    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public int getEno() {
        return eno;
    }
    public void setEno(int eno) {
        this.eno = eno;
    }

    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
}

Step 5: MainActivity.java

package com.alonex.firebaseeg;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    EditText eno, ename, salary;
    Spinner dept;
    Button add, display, delete, update;
    ListView lv;
    List<Employee> employeeList = new ArrayList<>();

    DatabaseReference dbRef;
    String selectedId = "";
    String selectedDept = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        eno = findViewById(R.id.edtno);
        ename = findViewById(R.id.edtname);
        salary = findViewById(R.id.edtsal);

        add = findViewById(R.id.addbtn);
        display = findViewById(R.id.displaybtn);
        delete = findViewById(R.id.deletebtn);
        update = findViewById(R.id.updatebtn);

        String[] dpts = {"Administration", "IT", "Marketing", "Sales", "Finance"};

        dept = findViewById(R.id.deptspin);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, dpts);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dept.setAdapter(adapter);

        dept.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedDept = parent.getItemAtPosition(position).toString();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        lv = findViewById(R.id.lv);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                Employee e = employeeList.get(i);
                ename.setText(e.getEname());
                eno.setText(String.valueOf(e.getEno()));
                selectedId = e.getId();
            }
        });

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        dbRef = database.getReference("employee");

        add.setOnClickListener(v -> addRecord());
        display.setOnClickListener(v -> showAll());
        delete.setOnClickListener(v -> deleteRecord());
        update.setOnClickListener(v -> updateRecord());
    }

    private void addRecord() {
        String name = ename.getText().toString();
        int no = Integer.parseInt(eno.getText().toString());
        int sal = Integer.parseInt(salary.getText().toString());
        String id = dbRef.push().getKey();

        Employee emp = new Employee(id, no, name, sal, selectedDept);
        dbRef.child(id).setValue(emp);

        Toast.makeText(getApplicationContext(), "Record Added", Toast.LENGTH_LONG).show();
    }

    private void showAll() {
        dbRef.addListenerForSingleValueEvent(new ValueEventListener() {

            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                employeeList.clear();

                for (DataSnapshot snp : snapshot.getChildren()) {
                    Employee emp = snp.getValue(Employee.class);
                    employeeList.add(emp);
                }

                List<String> disp = new ArrayList<>();

                for (Employee e : employeeList) {
                    disp.add("Emp No: " + e.getEno() +
                            "\n Name: " + e.getEname() +
                            "\n Salary: " + e.getSalary() +
                            "\n Department: " + e.getDepartment());
                }

                ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(),
                        android.R.layout.simple_list_item_1, disp);

                lv.setAdapter(adapter);

                if (disp.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "No records found",
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {}
        });
    }

    private void deleteRecord() {
        if (!selectedId.isEmpty()) {
            dbRef.child(selectedId).removeValue();
            Toast.makeText(getApplicationContext(), "Record Deleted", Toast.LENGTH_LONG).show();
            showAll();
        } else {
            Toast.makeText(getApplicationContext(), "Please select a Record to Delete",
                    Toast.LENGTH_LONG).show();
        }
    }

    private void updateRecord() {
        if (!selectedId.isEmpty()) {
            String s = ename.getText().toString();
            int sal = Integer.parseInt(salary.getText().toString());
            int i = Integer.parseInt(eno.getText().toString());

            Employee e1 = new Employee(selectedId, i, s, sal, selectedDept);
            dbRef.child(selectedId).setValue(e1);

            Toast.makeText(getApplicationContext(), "Record Updated",
                    Toast.LENGTH_LONG).show();

        } else {
            Toast.makeText(getApplicationContext(),
                    "Please select a Record to Update", Toast.LENGTH_LONG).show();
        }
    }
}

Output:

  1. Insert a Record
  2. Display Records
  3. Delete a Record
  4. Update a Record

Below is Assignment 8 – SQLite Database rewritten in your clean “exam-ready / practical file” format — step-by-step guide + all code, same style as Assignment 9. Just copy–paste to your Notepad.


Assignment 8 – SQLite Database

Create Student table with fields:

rno, name, gender, score1, score2 Perform: Create, Insert, Show All, Search, Delete, Update


mainActivity.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/edtrno"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Roll No"
        android:inputType="number"
        android:layout_marginBottom="8dp" />

    <EditText
        android:id="@+id/edtname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Name"
        android:layout_marginBottom="8dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Gender"
        android:layout_marginBottom="4dp" />

    <RadioGroup
        android:id="@+id/genderrg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="8dp">

        <RadioButton
            android:id="@+id/malerb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Male" />

        <RadioButton
            android:id="@+id/femalerb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Female"
            android:layout_marginStart="16dp" />
    </RadioGroup>

    <EditText
        android:id="@+id/edtscore1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Score 1"
        android:inputType="number"
        android:layout_marginBottom="8dp" />

    <EditText
        android:id="@+id/edtscore2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Score 2"
        android:inputType="number"
        android:layout_marginBottom="12dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="3"
        android:layout_marginBottom="8dp">

        <Button
            android:id="@+id/btnadd"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Add" />

        <Button
            android:id="@+id/btnview"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Show All" />

        <Button
            android:id="@+id/btnsearch"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Search" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2"
        android:layout_marginBottom="8dp">

        <Button
            android:id="@+id/btndelete"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Delete" />

        <Button
            android:id="@+id/btnupdate"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Update" />
    </LinearLayout>

    <TextView
        android:id="@+id/tv2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Result will appear here"
        android:padding="8dp"
        android:background="#EEEEEE" />

</LinearLayout>

** mainActivity2 **

<TextView
    android:id="@+id/textViewRecords"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="All Records will appear here"
    android:textSize="16sp" />

**Step 1: Creating SQLite Database

using SQLiteOpenHelper**

dbHandler.java

package com.alone_x.sqlitedb;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;

public class dbHandler extends SQLiteOpenHelper {

    static String DB_NAME = "student.db";
    static String TAB_NAME = "student";

    public dbHandler(@Nullable Context context){
        super(context,DB_NAME,null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TAB_NAME +
                " (rno integer primary key, name text, gender text, score1 integer, score2 integer)";
        db.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    }

    public boolean saveData(int roll, String name, String gender, int score1, int score2){
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("rno", roll);
        cv.put("name", name);
        cv.put("gender", gender);
        cv.put("score1", score1);
        cv.put("score2", score2);
        long insert = db.insert(TAB_NAME, null, cv);
        return insert != -1;
    }

    public Cursor readData(){
        SQLiteDatabase db = this.getReadableDatabase();
        return db.rawQuery("SELECT * FROM " + TAB_NAME, null);
    }

    public Cursor searchData(int rno){
        SQLiteDatabase db = this.getReadableDatabase();
        return db.rawQuery("SELECT * FROM " + TAB_NAME + " WHERE rno=" + rno, null);
    }

    public int deleteRecord(String name){
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TAB_NAME, "name=?", new String[]{name});
    }

    public boolean updateRecord(int rno, String name, String gender, int score1, int score2){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("rno", rno);
        
        if(name != null && !name.isEmpty()) cv.put("name", name);
        if(gender != null && !gender.isEmpty()) cv.put("gender", gender);
        if(score1 != -1) cv.put("score1", score1);
        if(score2 != -1) cv.put("score2", score2);

        int update = db.update(TAB_NAME, cv, "rno=?", new String[]{String.valueOf(rno)});
        return update > 0;
    }
}

Step 2: MainActivity.java (UI + CRUD Operations)

package com.alone_x.sqlitedb;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
    EditText rno, name, score1, score2;
    RadioGroup genderrg;
    RadioButton malerb, femalerb;
    Button btnadd, btnview, btndel, btnupd, btnsrch;
    TextView tv;

    dbHandler connection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        rno = findViewById(R.id.edtrno);
        name = findViewById(R.id.edtname);
        score1 = findViewById(R.id.edtscore1);
        score2 = findViewById(R.id.edtscore2);
        genderrg = findViewById(R.id.genderrg);
        malerb = findViewById(R.id.malerb);
        femalerb = findViewById(R.id.femalerb);
        btnadd = findViewById(R.id.btnadd);
        btnview = findViewById(R.id.btnview);
        btndel = findViewById(R.id.btndelete);
        btnupd = findViewById(R.id.btnupdate);
        btnsrch = findViewById(R.id.btnsearch);
        tv = findViewById(R.id.tv2);

        malerb.setChecked(true);
        connection = new dbHandler(this);
        connection.getWritableDatabase();

        btnadd.setOnClickListener(v -> {
            int no = Integer.parseInt(rno.getText().toString());
            String sname = name.getText().toString();

            int selectedId = genderrg.getCheckedRadioButtonId();
            RadioButton selectedRB = findViewById(selectedId);
            String gender = selectedRB.getText().toString();

            int scoreone = Integer.parseInt(score1.getText().toString());
            int scoretwo = Integer.parseInt(score2.getText().toString());

            boolean b = connection.saveData(no, sname, gender, scoreone, scoretwo);
            Toast.makeText(getApplicationContext(), b ? "Record Created" : "Record Not Created", Toast.LENGTH_LONG).show();
        });

        btnview.setOnClickListener(v -> {
            Cursor c = connection.readData();
            if(c.getCount() == 0){
                Toast.makeText(getApplicationContext(), "No Records", Toast.LENGTH_LONG).show();
            } else {
                StringBuilder records = new StringBuilder();
                while(c.moveToNext()){
                    records.append("R.No.: ").append(c.getInt(c.getColumnIndexOrThrow("rno"))).append("\n");
                    records.append("Name: ").append(c.getString(c.getColumnIndexOrThrow("name"))).append("\n");
                    records.append("Gender: ").append(c.getString(c.getColumnIndexOrThrow("gender"))).append("\n");
                    records.append("Score1: ").append(c.getInt(c.getColumnIndexOrThrow("score1"))).append("\n");
                    records.append("Score2: ").append(c.getInt(c.getColumnIndexOrThrow("score2"))).append("\n");
                    records.append("--------------------\n");
                }
                c.close();
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                intent.putExtra("records", records.toString());
                startActivity(intent);
            }
        });

        btndel.setOnClickListener(v -> {
            String sname = name.getText().toString();
            if(sname.isEmpty()){
                Toast.makeText(getApplicationContext(), "Enter Name", Toast.LENGTH_SHORT).show();
                return;
            }
            int deleted = connection.deleteRecord(sname);
            if(deleted > 0){
                rno.setText("");
                name.setText("");
                score1.setText("");
                score2.setText("");
                Toast.makeText(getApplicationContext(), "Record Deleted", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "No Record found", Toast.LENGTH_LONG).show();
            }
        });

        btnsrch.setOnClickListener(v -> {
            String rollStr = rno.getText().toString();
            if(rollStr.isEmpty()){
                Toast.makeText(getApplicationContext(), "Enter R.No", Toast.LENGTH_SHORT).show();
                return;
            }
            int roll = Integer.parseInt(rollStr);
            Cursor c = connection.searchData(roll);

            if(c.getCount() == 0){
                Toast.makeText(getApplicationContext(), "No Records", Toast.LENGTH_LONG).show();
            } else if(c.moveToFirst()){
                String sname = c.getString(c.getColumnIndexOrThrow("name"));
                String gender = c.getString(c.getColumnIndexOrThrow("gender"));
                int s1 = c.getInt(c.getColumnIndexOrThrow("score1"));
                int s2 = c.getInt(c.getColumnIndexOrThrow("score2"));

                name.setText(sname);
                score1.setText(String.valueOf(s1));
                score2.setText(String.valueOf(s2));
                if(gender.equalsIgnoreCase("Male"))
                    malerb.setChecked(true);
                else
                    femalerb.setChecked(true);

                tv.setText("Name: " + sname +
                        "\nGender: " + gender +
                        "\nScore1: " + s1 +
                        "\nScore2: " + s2);
            }
            c.close();
        });

        btnupd.setOnClickListener(v -> {
            String roll = rno.getText().toString();
            if(roll.isEmpty()){
                Toast.makeText(getApplicationContext(), "Enter R.NO.", Toast.LENGTH_LONG).show();
                return;
            }

            int rollno = Integer.parseInt(roll);
            String sname = name.getText().toString();
            int selectedId = genderrg.getCheckedRadioButtonId();
            RadioButton selectedRB = findViewById(selectedId);
            String gender = selectedRB.getText().toString();

            String scoreone = score1.getText().toString();
            String scoretwo = score2.getText().toString();

            int sc1 = scoreone.isEmpty() ? -1 : Integer.parseInt(scoreone);
            int sc2 = scoretwo.isEmpty() ? -1 : Integer.parseInt(scoretwo);

            boolean b = connection.updateRecord(rollno, sname, gender, sc1, sc2);

            Toast.makeText(getApplicationContext(),
                    b ? "Record Updated" : "Record Not Updated",
                    Toast.LENGTH_LONG).show();
        });
    }
}

Step 3: MainActivity2.java (Display Page)

package com.alone_x.sqlitedb;

import android.os.Bundle;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main2);

        TextView textView = findViewById(R.id.textViewRecords);
        String records = getIntent().getStringExtra("records");

        if(records != null && !records.isEmpty()){
            textView.setText(records);
        } else {
            textView.setText("No Records to display");
        }
    }
}

OUTPUT Operations

1. Creating / Inserting Records
2. Showing All Records (Next Activity)
3. Searching for a Record (By rno)
4. Deleting a Record (By name)
5. Updating a Record

SQLite Database File Location (Android Emulator Path)

/data/data/<your-package-name>/databases/student.db

If you want, I can also format Assignment 7 or 6 in the same style.


Below is Assignment 7 – File Storage (Internal & External) rewritten in your clean practical-file format (steps + code, no explanation). Just copy–paste to Notepad.


Assignment 7 – File Storage (Internal & External Storage)

Perform the following operations: ✔ Save to Internal Storage ✔ Retrieve from Internal Storage ✔ Save to External Storage ✔ Retrieve from External Storage


** mainActivity.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- File Name -->
    <EditText
        android:id="@+id/editTextText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter File Name"
        android:layout_marginBottom="10dp" />

    <!-- Content to Store -->
    <EditText
        android:id="@+id/editTextMultiLine"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:gravity="start|top"
        android:hint="Enter content here"
        android:inputType="textMultiLine"
        android:background="@android:color/darker_gray"
        android:padding="10dp"
        android:layout_marginBottom="20dp" />

    <!-- Internal Storage Buttons -->
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save to Internal Storage"
        android:layout_marginBottom="10dp" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Retrieve from Internal Storage"
        android:layout_marginBottom="25dp" />

    <!-- External Storage Buttons -->
    <Button
        android:id="@+id/buttonextstr"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save to External Storage"
        android:layout_marginBottom="10dp" />

    <Button
        android:id="@+id/buttonextret"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Retrieve from External Storage" />

</LinearLayout>

** mainActivity2.xml **

<!-- File Name -->
<TextView
    android:id="@+id/textView2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="File Name"
    android:textStyle="bold"
    android:textSize="18sp"
    android:layout_marginBottom="10dp" />

<!-- File Content -->
<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="File Content"
    android:textSize="16sp"
    android:padding="10dp"
    android:background="#DDDDDD"
    android:minHeight="200dp"
    android:gravity="top"
    android:layout_marginBottom="20dp" />

<!-- Go Back Button -->
<Button
    android:id="@+id/button3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Go Back" />

Step 1: MainActivity.java

package com.alonex.filestorage;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {

    EditText edt, fname;
    File myFile;
    Button strbtn, retrievebtn, btnextstr, btnextret;
    String dirname = "pixels";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edt = findViewById(R.id.editTextMultiLine);
        fname = findViewById(R.id.editTextText);
        strbtn = findViewById(R.id.button);
        retrievebtn = findViewById(R.id.button2);
        btnextstr = findViewById(R.id.buttonextstr);
        btnextret = findViewById(R.id.buttonextret);

        Intent go = new Intent(this, MainActivity2.class);

        strbtn.setOnClickListener(v ->
                saveToInternal(fname.getText().toString(), edt.getText().toString()));

        retrievebtn.setOnClickListener(v -> {
            String fcon = readFromInternal(fname.getText().toString());
            go.putExtra("fname", fname.getText().toString());
            go.putExtra("content", fcon);
            startActivity(go);
        });

        btnextstr.setOnClickListener(v ->
                saveToExternal(fname.getText().toString(), edt.getText().toString()));

        btnextret.setOnClickListener(v -> {
            String fcon = readFromExternal(fname.getText().toString());
            go.putExtra("fname", fname.getText().toString());
            go.putExtra("content", fcon);
            startActivity(go);
        });
    }

    private String readFromExternal(String fname) {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)
                & !Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            myFile = new File(getExternalFilesDir(dirname), fname);
        }

        String content = "";
        try {
            FileInputStream fis = new FileInputStream(myFile);
            DataInputStream dis = new DataInputStream(fis);
            BufferedReader buffer = new BufferedReader(new InputStreamReader(dis));
            String line;
            while ((line = buffer.readLine()) != null) {
                content += "\n" + line;
            }
            dis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    private void saveToExternal(String fname, String content) {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)
                & !Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            myFile = new File(getExternalFilesDir(dirname), fname);
        }

        try {
            FileOutputStream fos = new FileOutputStream(myFile);
            fos.write(content.getBytes());
            fos.close();
            Toast.makeText(getApplicationContext(), "Content Saved Successfully",
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String readFromInternal(String fname) {
        String fcontent = "";
        try {
            FileInputStream fis = openFileInput(fname);
            InputStreamReader reader = new InputStreamReader(fis);
            char buffer[] = new char[256];
            int charRead;

            while ((charRead = reader.read(buffer)) > 0) {
                String rs = String.copyValueOf(buffer, 0, charRead);
                fcontent += rs;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return fcontent;
    }

    private void saveToInternal(String fname, String content) {
        try {
            FileOutputStream fos = openFileOutput(fname, MODE_PRIVATE);
            OutputStreamWriter writer = new OutputStreamWriter(fos);
            writer.write(content);
            writer.close();
            Toast.makeText(getApplicationContext(), "Content Saved",
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Step 2: MainActivity2.java

package com.alonex.filestorage;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        Intent intent = getIntent();
        String text = intent.getStringExtra("content");
        String filename = intent.getStringExtra("fname");

        TextView tv = findViewById(R.id.textView);
        TextView fname = findViewById(R.id.textView2);

        fname.setText(filename);
        tv.setText(text);

        Intent back = new Intent(this, MainActivity.class);
        Button goback = findViewById(R.id.button3);

        goback.setOnClickListener(v -> startActivity(back));
    }
}

OUTPUT Paths

Internal Storage File Path:
 /data/data/com.<packagename>/files/<filename>

External Storage File Path:
 /sdcard/Android/data/com.<packagename>/files/pixels/<filename>

Below is Assignment 6 – Notification rewritten in the same clean practical-file format (steps + code, no explanation).


Assignment 6 – Notification

Write an Android program to display a notification.


Step 1: Add Permission in AndroidManifest.xml

(Add this inside <manifest> tag)

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

Step 2: MainActivity.java

package com.alonex.notification;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    NotificationManager nm;

    private void notifyy() {
        NotificationCompat.Builder b =
                new NotificationCompat.Builder(this, "CHANNEL1");

        b.setSmallIcon(R.drawable.baseline_notifications_none_24);
        b.setContentTitle("Website");
        b.setContentText("Show me the Webpage");
        b.setAutoCancel(true);
        b.setPriority(NotificationManager.IMPORTANCE_HIGH);

        Intent notify_intent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("https://pixelstechfest.in"));
        notify_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pndIN = PendingIntent.getActivity(
                this, 0, notify_intent, PendingIntent.FLAG_IMMUTABLE
        );

        b.setContentIntent(pndIN);

        nm.notify(0, b.build());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = findViewById(R.id.button);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel ch =
                    new NotificationChannel("CHANNEL1",
                            "Pixels",
                            NotificationManager.IMPORTANCE_HIGH);

            ch.setDescription("Channel 1");

            nm = (NotificationManager)
                    getSystemService(Context.NOTIFICATION_SERVICE);

            nm.createNotificationChannel(ch);
        }

        btn.setOnClickListener(v -> notifyy());
    }
}

Step 3: 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:gravity="center"
    android:orientation="vertical"
    android:padding="20dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Notification" />

</LinearLayout>

OUTPUT

When the button is clicked, a notification appears. On clicking the notification, it opens: https://pixelstechfest.in


Shared Prefs View->Tool Windows->Device Explorer->data->data->package name

package com.example.sharedpref;

import android.os.Bundle;

import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat;

import androidx.appcompat.app.AppCompatActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AlertDialog;

public class MainActivity extends AppCompatActivity { private EditText etUsername, etPassword; private Button btnSignIn; private CheckBox cbRememberMe; private int wrongAttempts = 0; private static final int MAX_ATTEMPTS = 3; private static final String PASSWORD = "admin123";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etUsername = findViewById(R.id.etUsername);
    etPassword = findViewById(R.id.etPassword);
    btnSignIn = findViewById(R.id.btnSignIn);
    cbRememberMe = findViewById(R.id.cbRememberMe);

    loadSavedCredentials();

    btnSignIn.setOnClickListener(v -> attemptLogin());

    if (wrongAttempts >= MAX_ATTEMPTS) {
        btnSignIn.setEnabled(false);
        showMaxAttemptsDialog();
    }
}

private void loadSavedCredentials() {
    SharedPreferences prefs = getSharedPreferences("login_prefs", MODE_PRIVATE);
    boolean rememberMe = prefs.getBoolean("remember_me", false);

    if (rememberMe) {
        String username = prefs.getString("username", "");
        etUsername.setText(username);
        cbRememberMe.setChecked(true);
    }
}

private void attemptLogin() {
    String password = etPassword.getText().toString();

    if (password.equals(PASSWORD)) {
        showSuccessDialog();

        if (cbRememberMe.isChecked()) {
            SharedPreferences prefs = getSharedPreferences("login_prefs", MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("username", etUsername.getText().toString());
            editor.putBoolean("remember_me", true);
            editor.apply();
        }
    } else {
        wrongAttempts++;
        showRemainingAttempts();

        if (wrongAttempts >= MAX_ATTEMPTS) {
            btnSignIn.setEnabled(false);
            showMaxAttemptsDialog();
        }
    }
}

private void showRemainingAttempts() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Wrong Password");
    builder.setMessage(String.format(
            "Incorrect password.\nRemaining attempts: %d",
            MAX_ATTEMPTS - wrongAttempts
    ));
    builder.setPositiveButton("OK", null);
    builder.show();
}

private void showMaxAttemptsDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Maximum Attempts Reached");
    builder.setMessage("You have exceeded the maximum number of login attempts.");
    builder.setPositiveButton("OK", null);
    builder.show();
}

private void showSuccessDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Login Successful");
    builder.setMessage("Welcome!");
    builder.setPositiveButton("OK", (dialog, which) -> {
        Toast.makeText(MainActivity.this, "Login successful!", Toast.LENGTH_SHORT).show();
    });
    builder.show();
}

}

activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

<EditText
    android:id="@+id/etUsername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="text"
    android:hint="Username"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintVertical_bias="0.3"/>

<EditText
    android:id="@+id/etPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPassword"
    android:hint="Password"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/etUsername"
    android:layout_marginTop="16dp"/>

<CheckBox
    android:id="@+id/cbRememberMe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Remember Me"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/etPassword"
    android:layout_marginTop="16dp"/>

<Button
    android:id="@+id/btnSignIn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sign In"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/cbRememberMe"
    android:layout_marginTop="16dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>


ImplicitIntent

  1. Sender APP(implicit intent) package com.example.implicitintent;

import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText;

import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

EditText url,text,phone,send;
Button urlBtn,textBtn,phoneBtn,sendBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EdgeToEdge.enable(this);
    setContentView(R.layout.activity_main);

    url=findViewById(R.id.url);
    text=findViewById(R.id.text);
    phone=findViewById(R.id.phone);
    send=findViewById(R.id.send);

    urlBtn=findViewById(R.id.urlBtn);
    textBtn=findViewById(R.id.textBtn);
    phoneBtn=findViewById(R.id.phoneBtn);
    sendBtn=findViewById(R.id.sendBtn);

    urlBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String urlStr = url.getText().toString();
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(urlStr));
            startActivity(i);
        }
    });

    textBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String textStr = text.getText().toString();
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_TEXT,textStr);
            startActivity(Intent.createChooser(i,"send text using"));
        }
    });

    phoneBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String num = phone.getText().toString();
            Intent i = new Intent(Intent.ACTION_DIAL);
            i.setData(Uri.parse("tel:"+ num));
            startActivity(i);
        }
    });

    sendBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String text = send.getText().toString();
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_TEXT, text);
            startActivity(Intent.createChooser(i, "Send using"));

        }
    });

}

}

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

<TextView
    android:id="@+id/textView2"
    android:layout_width="72dp"
    android:layout_height="28dp"
    android:text="websiteUrl"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.054" />

<EditText
    android:id="@+id/url"
    android:layout_width="187dp"
    android:layout_height="40dp"
    android:ems="10"
    android:hint="www.google.com"
    android:inputType="text"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.358"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.055" />

<Button
    android:id="@+id/urlBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Open Website"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.055" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text To send"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.182" />

<EditText
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="hello "
    android:inputType="text"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.398"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.189" />

<Button
    android:id="@+id/textBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="send Text"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.19" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Phone Number"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.352" />

<EditText
    android:id="@+id/phone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Enter Phone Number"
    android:inputType="text"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.365" />

<Button
    android:id="@+id/phoneBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Dial Num"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.367" />

<TextView
    android:id="@+id/textView5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="enter a text"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.005"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/sendBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="send"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.959"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.499" />

<EditText
    android:id="@+id/send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="enter a text here it will be show in the another activity"
    android:inputType="text"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

and its xml in mainfest

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  1. Reciever App

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

<TextView
android:id="@+id/revTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

package com.example.receiver;

import android.content.Intent; import android.os.Bundle; import android.widget.TextView;

import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity { TextView revTv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EdgeToEdge.enable(this);
    setContentView(R.layout.activity_main);

    revTv=findViewById(R.id.revTv);

    String message = getIntent().getStringExtra(Intent.EXTRA_TEXT);
    if(message!=null){
        revTv.setText(message);
    }

}

}

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.SEND"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:mimeType="text/plain"/>
        </intent-filter>
    </activity>

Explicit Intent:

MainActivity1

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

<EditText
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="text"
    android:text="Name"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.452"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.049" />

<EditText
    android:id="@+id/gmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="text"
    android:text="gmail"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.452"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.161" />

<RadioGroup
    android:id="@+id/gender"
    android:layout_width="325dp"
    android:layout_height="65dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.372">

    <RadioButton
        android:id="@+id/male"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="male" />

    <RadioButton
        android:id="@+id/female"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="female" />
</RadioGroup>

<CheckBox
    android:id="@+id/english"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="English"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.136"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.553" />

<CheckBox
    android:id="@+id/hindi"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hindi"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.561"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.553" />

<Spinner
    android:id="@+id/spinner"
    android:layout_width="409dp"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.66" />

<RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.762" />

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="274dp"
    android:layout_height="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.854" />

<Button
    android:id="@+id/submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="submit"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.96" />

</androidx.constraintlayout.widget.ConstraintLayout>

package com.example.explicitintent;

import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RatingBar; import android.widget.SeekBar; import android.widget.Spinner;

import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

EditText name, email;
RadioGroup genderGroup;
CheckBox english, hindi;
Spinner spinner;
RatingBar ratingBar;
SeekBar seekBar;
Button submit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EdgeToEdge.enable(this);
    setContentView(R.layout.activity_main);

    name=findViewById(R.id.name);
    email=findViewById(R.id.gmail);
    genderGroup=findViewById(R.id.gender);
    english=findViewById(R.id.english);
    hindi=findViewById(R.id.hindi);
    spinner = findViewById(R.id.spinner);
    ratingBar = findViewById(R.id.ratingBar);
    seekBar = findViewById(R.id.seekBar);
    submit = findViewById(R.id.submit);

    String langs[]={"java","Python","C++","C"};
    ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_list_item_1, langs);
    spinner.setAdapter(aa);

    submit.setOnClickListener(v->{
        String n = name.getText().toString();
        String e = email.getText().toString();
        int id = genderGroup.getCheckedRadioButtonId();
        RadioButton rb = findViewById(id);
        String gender = rb.getText().toString();

        String langKnown="";
        if(english.isChecked()) langKnown+="English";
        if(hindi.isChecked()) langKnown+="Hindi";

        String prog = spinner.getSelectedItem().toString();
        float rating = ratingBar.getRating();
        int conf = seekBar.getProgress();

        Intent i = new Intent(MainActivity.this, MainActivity2.class);
        i.putExtra("name", n);
        i.putExtra("email", e);
        i.putExtra("gender", gender);
        i.putExtra("klang", langKnown);
        i.putExtra("prog", prog);
        i.putExtra("rating", rating);
        i.putExtra("conf", conf);

        startActivity(i);

    });

}

}

MainActivity2.java

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity2">

<TextView
    android:id="@+id/out"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    tools:layout_editor_absoluteY="5dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

package com.example.explicitintent;

import android.os.Bundle; import android.widget.TextView;

import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat;

public class MainActivity2 extends AppCompatActivity {

TextView out;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    out = findViewById(R.id.out);

    String result =
            "Name: " + getIntent().getStringExtra("name") +
                    "\nEmail: " + getIntent().getStringExtra("email") +
                    "\nGender: " + getIntent().getStringExtra("gender") +
                    "\nLanguages Known: " + getIntent().getStringExtra("klang") +
                    "\nProgramming Language: " + getIntent().getStringExtra("prog") +
                    "\nRating: " + getIntent().getFloatExtra("rating",0) +
                    "\nConfidence: " + getIntent().getIntExtra("conf",0);

    out.setText(result);
}

}


Calculator Java

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

<EditText
    android:id="@+id/num1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="text"
    android:text="Enter num 1"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.557"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.04" />

<EditText
    android:id="@+id/num2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="text"
    android:text="enter num 2 "
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.557"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.151" />

<TextView
    android:id="@+id/result"
    android:layout_width="310dp"
    android:layout_height="37dp"
    android:text="the result will appear here"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.292" />

<Button
    android:id="@+id/addBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="add"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.348"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.499" />

<Button
    android:id="@+id/subBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="sub"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.7"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.499" />

<Button
    android:id="@+id/mulBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="mul"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.348"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.612" />

<Button
    android:id="@+id/divBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="div"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.722"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.612" />

</androidx.constraintlayout.widget.ConstraintLayout>

package com.example.calculator;

import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;

import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity { EditText num1 , num2; TextView result; Button addBtn,subBtn,divBtn,mulBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main);

    num1 = findViewById(R.id.num1);
    num2 = findViewById(R.id.num2);
    result=findViewById(R.id.result);

    addBtn =findViewById(R.id.addBtn);
    subBtn =findViewById(R.id.subBtn);
    mulBtn =findViewById(R.id.mulBtn);
    divBtn =findViewById(R.id.divBtn);

    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            double a = Double.parseDouble((num1.getText().toString()));
            double b = Double.parseDouble((num2.getText().toString()));

            result.setText("Result: "+(a+b));
        }
    });

    subBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           double a= Double.parseDouble((num1.getText().toString()));
           double b= Double.parseDouble((num2.getText().toString()));

           result.setText("Result: "+(a-b));
        }
    });

    mulBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            double a= Double.parseDouble((num1.getText().toString()));
            double b= Double.parseDouble((num2.getText().toString()));

            result.setText("Result: "+ (a*b));
        }
    });

    divBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            double a = Double.parseDouble((num1.getText().toString()));
            double b = Double.parseDouble((num2.getText().toString()));

            if(b==0){
                result.setText("Num cannot divided by 0");
            }else{
                result.setText("Result: "+(a/b));
            }
        }
    });
}

}


Assignment 2 – Currency Converter

Step 1: Create a new Android Project

  • Name: CurrencyConverter
  • Package: com.alone_x.currencyconverter
  • Minimum SDK: API 21 (Lollipop)
  • Empty Activity

Step 2: Design activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Currency Converter"
        android:textSize="24sp"
        android:textStyle="bold"
        android:layout_gravity="center_horizontal"
        android:paddingBottom="16dp"/>

    <Spinner
        android:id="@+id/fromCurrency"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Spinner
        android:id="@+id/toCurrency"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"/>

    <EditText
        android:id="@+id/amountInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter amount"
        android:inputType="numberDecimal"
        android:layout_marginTop="8dp"/>

    <Button
        android:id="@+id/convertBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Convert"
        android:layout_marginTop="8dp"/>

    <TextView
        android:id="@+id/resultView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Result will appear here"
        android:textSize="18sp"
        android:paddingTop="16dp"/>
</LinearLayout>

Step 3: Write MainActivity.java

package com.alone_x.currencyconverter;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
    String[] currencies = {"INR", "USD", "EUR", "JPY", "GBP"};
    double[][] conversionRates = {
            {1,     0.012, 0.011, 1.75, 0.0095}, // INR to all
            {83.3,  1,     0.91,  145.0, 0.79},  // USD to all
            {91.4,  1.10,  1,     158.5, 0.87},  // EUR to all
            {0.57,  0.0069,0.0063,1,     0.0055},// JPY to all
            {105.3, 1.27,  1.15,  181.2, 1}      // GBP to all
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Spinner fromSpinner = findViewById(R.id.fromCurrency);
        Spinner toSpinner = findViewById(R.id.toCurrency);
        EditText amountInput = findViewById(R.id.amountInput);
        Button convertBtn = findViewById(R.id.convertBtn);
        TextView resultView = findViewById(R.id.resultView);

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, currencies);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        fromSpinner.setAdapter(adapter);
        toSpinner.setAdapter(adapter);

        convertBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String amountStr = amountInput.getText().toString().trim();
                if (amountStr.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Enter an amount", Toast.LENGTH_SHORT).show();
                    return;
                }

                double amount = Double.parseDouble(amountStr);
                int fromIndex = fromSpinner.getSelectedItemPosition();
                int toIndex = toSpinner.getSelectedItemPosition();

                double rate = conversionRates[fromIndex][toIndex];
                double converted = amount * rate;

                resultView.setText(String.format("%.2f %s = %.2f %s",
                        amount,
                        currencies[fromIndex],
                        converted,
                        currencies[toIndex]));
            }
        });
    }
}

Step 4: Run the app

  • Select currencies, enter amount, click Convert
  • Result displayed in TextView

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2025 Microsoft