====================================================================================================
                  ANDROID LAB & PROJECT PROGRAMS - MASTER COMBINED FILE                 
                             TOTAL PROGRAMS: 38 (01 TO 38)                              
====================================================================================================

TABLE OF CONTENTS:
----------------------------------------------------------------------------------------------------
  [01] 01_NameDisplay.txt             - Create an app that displays your name and email id.
  [02] 02_MarksCalculate.txt          - Create an app that takes marks of any three subjects from the user and displays its sum and average.
  [03] 03_AndroidLayouts.txt          - Create suitable apps to design the different layouts of the android studio.
  [04] 04_Calculator.txt              - Develop a simple calculator app.
  [05] 05_TextColorChange.txt         - Create an app that changes text color when a button is clicked.
  [06] 06_DateTimeLinear.txt          - Create an app that displays Date and Time in different formats using Linear Layout.
  [07] 07_ToastMessage.txt            - Create an app that displays a Toast on the launch of an activity.
  [08] 08_AlertBox.txt                - Create an app that creates an Alert Dialog Box.
  [09] 09_GreetingCard.txt            - Create a Greeting card app that displays an image.
  [10] 10_PlayAudioVideo.txt          - Create an app that plays audio when we click on the button "Play Music" and plays a video when we click on the button "Play Video".
  [11] 11_OnlineVideo.txt             - Create an app that plays video from the internet.
  [12] 12_OptionsMenu.txt             - Create an app to demonstrate Options Menu.
  [13] 13_ContextMenu.txt             - Create an app that changes the background color of an activity using Context Menu.
  [14] 14_CheckBoxRadioButton.txt     - Create an app to demonstrate how radiobuttons and checkboxes can be used in android.
  [15] 15_ButtonClickNewActivity.txt  - Create an app that launches a new activity on a button click.
  [16] 16_StudentActivity.txt         - Create an app that launches a new activity on a button click to display student details with checkbox and radio buttons.
  [17] 17_EmployeeActivity.txt        - Create an app that launches a new activity on a button click to calculate and display employee details and salary.
  [18] 18_CustomBroadcast.txt         - Create an app to broadcast a custom intent.
  [19] 19_AirplaneMode.txt            - Create an app to broadcast a system intent. (AIRPLANE MODE CHANGED).
  [20] 20_BatteryLow.txt              - Create an app to broadcast a system intent – Battery Low.
  [21] 21_AlarmClock.txt              - Create an alarm application.
  [22] 22_ContactDisplay.txt          - Create an app that displays a simple ListView. (Contacts list).
  [23] 23_FoodOrderApp.txt            - Develop an Android application in Java that enables customers to place a food order, view the order summary, and generate the final bill using three activities.
  [24] 24_ThreeActivityApp.txt        - Develop an Android application using Java consisting of three activities. The application must use Explicit Intents, Intent Extras, RadioButtons, CheckBoxes, Options Menu.
  [25] 25_StudentDatabase.txt         - Create an app to insert name and age with an add button with toast and a view details button to show all details from student table.
  [26] 26_LibraryManagement.txt       - Create an app for library management insert the following details to db: book_id, book_name, publisher, author, published_year, price, stock and a view button to view details of all books.
  [27] 27_ProductDatabase.txt         - Create an app to show product names using database and the following controls: ListView, GridView, TextBox, Button.
  [28] 28_CounterApp.txt              - Create an app to demonstrate counter.
  [29] 29_TextToSpeechApp.txt         - Create an app to convert text to speech.
  [30] 30_AsynchronousTask.txt        - Create an app to perform asynchronous task.
  [31] 31_LoginRegistration.txt       - Create an app for Registration and Login Activity using database.
  [32] 32_FlashLightApp.txt           - Create an app to turn on and off the flashlight.
  [33] 33_ShakeColorApp.txt           - Create an app to change the background color when the phone is shaked or tilted.
  [34] 34_CommunicationApp.txt        - Create an app to i) Send an SMS. ii) Send an email. iii) To make a call.
  [35] 35_SensorsApp.txt              - Create an Android application to demonstrate the use of light, pressure, and humidity sensors.
  [36] 36_HallBookingSystem.txt       - Hall Booking System (Campus Venue Requisition & Collision Detection Project).
  [37] 37_HospitalManagement.txt      - Hospital Management Multi-Activity Application (Patient Registration, Department Consultation, and Final Billing).
  [38] 38_StudentDatabase_CRUD.txt    - Student Database Management System (SQLite CRUD: Insert and View Records with Multi-Activity Navigation).
----------------------------------------------------------------------------------------------------


====================================================================================================
# FILE 01/38: 01_NameDisplay.txt
# TITLE: Create an app that displays your name and email id.
====================================================================================================

/*
========================================================================================
Filename: 01_NameDisplay.txt
Program 01: Create an app that displays your name and email id.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 EditText (TextBox):
     - etName (Hint: 'Enter your name')
     - etEmail (Hint: 'Enter your email')
   Add 1 Button:
     - Text: 'Display', onClick: 'displayDetails'
   Add 2 TextView:
     - tvTitle: 'Display Details'
     - tvDisplayResult: To show the formatted name and email output

2. Layout Configuration:
   - LinearLayout (vertical orientation, android:gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme (Theme.MaterialComponents.DayNight.DarkActionBar or similar). No modifications required.

5. AndroidManifest.xml:
   No special permissions required.
   Standard launcher activity declaration:
   <activity android:name=".MainActivity" android:exported="true">
       <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
   </activity>

6. Additional Files & Resources Required:
   - None (Single Activity app).
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.namedisplay;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void displayDetails(View view) {
        EditText etName = findViewById(R.id.etName);
        EditText etEmail = findViewById(R.id.etEmail);
        TextView tv = findViewById(R.id.tvDisplayResult);
        String name = etName.getText().toString().trim();
        String email = etEmail.getText().toString().trim();
        if (!name.isEmpty() && !email.isEmpty())
            tv.setText("Name : " + name + "\nEmail : " + email);
        else tv.setText("Please enter both name and email.");
    }
}


====================================================================================================
# FILE 02/38: 02_MarksCalculate.txt
# TITLE: Create an app that takes marks of any three subjects from the user and displays its sum and average.
====================================================================================================

/*
========================================================================================
Filename: 02_MarksCalculate.txt
Program 02: Create an app that takes marks of any three subjects from the user and displays its sum and average.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 3 EditText (TextBox):
     - etEnglishMarks (Hint: 'Enter the marks of English', inputType='number')
     - etMathMarks (Hint: 'Enter the marks of Mathematics', inputType='number')
     - etScienceMarks (Hint: 'Enter the marks of Science', inputType='number')
   Add 1 Button:
     - Text: 'Calculate', onClick: 'calculateMarks'
   Add 2 TextView:
     - tvTitle: 'Marks Calculator'
     - tvResult: To display Total marks and Average percentage

2. Layout Configuration:
   - LinearLayout (vertical orientation, android:gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   No special permissions required.
   Standard launcher activity declaration:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - None.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.markscalculate;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
    }

    public void calculateMarks(View v) {
        EditText a=findViewById(R.id.etEnglishMarks),m=findViewById(R.id.etMathMarks),s=findViewById(R.id.etScienceMarks);
        TextView r=findViewById(R.id.tvResult);
        String x=a.getText().toString().trim(),y=m.getText().toString().trim(),z=s.getText().toString().trim();
        if(!x.isEmpty()&&!y.isEmpty()&&!z.isEmpty()) {
            int total=Integer.parseInt(x)+Integer.parseInt(y)+Integer.parseInt(z);
            double avg=total/3.0;
            r.setText("Total Marks : "+total+"\nAverage Marks : "+avg);
        }

        else r.setText("Please enter the marks of all subjects.");
    }
}


====================================================================================================
# FILE 03/38: 03_AndroidLayouts.txt
# TITLE: Create suitable apps to design the different layouts of the android studio.
====================================================================================================

/*
========================================================================================
Filename: 03_AndroidLayouts.txt
Program 03: Create suitable apps to design the different layouts of the android studio.
Files Included: MainActivity.java, activity_main.xml
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 11 TextView (Section titles and demo labels):
     - Title: 'Android Layout Demonstration'
     - Section Headings: 'LinearLayout', 'RelativeLayout', 'FrameLayout', 'TableLayout', 'GridLayout'
     - Content Labels: 'Background', 'A', 'B', 'C', 'D'
   Add 9 Button:
     - LinearLayout section: 2 Buttons ('One', 'Two')
     - RelativeLayout section: 2 Buttons ('Left' aligned to parent start, 'Right' aligned to parent end)
     - FrameLayout section: 1 Button ('Top' layered above TextView)
     - GridLayout section: 4 Buttons ('1', '2', '3', '4' in 2x2 grid layout)

2. Layout Configuration:
   - Nested layout inside a ScrollView demonstrating LinearLayout, RelativeLayout, FrameLayout, TableLayout, and GridLayout.

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   Standard launcher activity declaration:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - None (Demonstrates UI layout structuring).
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.androidlayouts;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
    }
}

// ======================================================================================
// File: res/layout/activity_main.xml
// ======================================================================================
<?xml version="1.0" ?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
    <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center">
        <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center" android:padding="20dp">
            <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Android Layout Demonstration" android:textColor="#2196F3" android:textSize="28sp" android:textStyle="bold" android:fontFamily="sans-serif-condensed-medium" android:gravity="center" android:layout_marginBottom="25dp"/>
            <LinearLayout android:layout_width="300dp" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp" android:background="#F5F5F5" android:layout_marginBottom="15dp">
                <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="LinearLayout" android:textColor="#2196F3" android:textSize="20sp" android:textStyle="bold"/>
                <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal">
                    <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="One"/>
                    <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Two" android:layout_marginStart="12dp"/>
                </LinearLayout>
            </LinearLayout>
            <LinearLayout android:layout_width="300dp" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp" android:background="#F5F5F5" android:layout_marginBottom="15dp">
                <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RelativeLayout" android:textColor="#2196F3" android:textSize="20sp" android:textStyle="bold"/>
                <RelativeLayout android:layout_width="match_parent" android:layout_height="70dp">
                    <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:text="Left"/>
                    <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:text="Right"/>
                </RelativeLayout>
            </LinearLayout>
            <LinearLayout android:layout_width="300dp" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp" android:background="#F5F5F5" android:layout_marginBottom="15dp">
                <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="FrameLayout" android:textColor="#2196F3" android:textSize="20sp" android:textStyle="bold"/>
                <FrameLayout android:layout_width="match_parent" android:layout_height="110dp">
                    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Background" android:textSize="20sp" android:textStyle="bold"/>
                    <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top|center" android:text="Top"/>
                </FrameLayout>
            </LinearLayout>
            <LinearLayout android:layout_width="300dp" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp" android:background="#F5F5F5" android:layout_marginBottom="15dp">
                <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TableLayout" android:textColor="#2196F3" android:textSize="20sp" android:textStyle="bold"/>
                <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="*">
                    <TableRow>
                        <TextView android:gravity="center" android:padding="10dp" android:text="A"/>
                        <TextView android:gravity="center" android:padding="10dp" android:text="B"/>
                    </TableRow>
                    <TableRow>
                        <TextView android:gravity="center" android:padding="10dp" android:text="C"/>
                        <TextView android:gravity="center" android:padding="10dp" android:text="D"/>
                    </TableRow>
                </TableLayout>
            </LinearLayout>
            <LinearLayout android:layout_width="300dp" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp" android:background="#F5F5F5">
                <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GridLayout" android:textColor="#2196F3" android:textSize="20sp" android:textStyle="bold"/>
                <GridLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:columnCount="2" android:useDefaultMargins="true">
                    <Button android:layout_width="120dp" android:layout_height="wrap_content" android:text="1"/>
                    <Button android:layout_width="120dp" android:layout_height="wrap_content" android:text="2"/>
                    <Button android:layout_width="120dp" android:layout_height="wrap_content" android:text="3"/>
                    <Button android:layout_width="120dp" android:layout_height="wrap_content" android:text="4"/>
                </GridLayout>
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</FrameLayout>


====================================================================================================
# FILE 04/38: 04_Calculator.txt
# TITLE: Develop a simple calculator app.
====================================================================================================

/*
========================================================================================
Filename: 04_Calculator.txt
Program 04: Develop a simple calculator app.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 EditText (TextBox):
     - etFirstNumber (Hint: 'Enter the 1st Number', inputType='numberDecimal')
     - etSecondNumber (Hint: 'Enter the 2nd Number', inputType='numberDecimal')
   Add 4 Button:
     - Add: Text: 'Add', onClick: 'performAddition'
     - Subtract: Text: 'Subtract', onClick: 'performSubtraction'
     - Multiply: Text: 'Multiply', onClick: 'performMultiplication'
     - Divide: Text: 'Divide', onClick: 'performDivision'
   Add 2 TextView:
     - tvTitle: 'Calculator App'
     - tvResult: To display calculated result

2. Layout Configuration:
   - LinearLayout (vertical) with child horizontal LinearLayouts for action buttons.

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - None.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.sumapp;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    EditText etFirstNumber,etSecondNumber;
    TextView tvResult;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        etFirstNumber=findViewById(R.id.etFirstNumber);
        etSecondNumber=findViewById(R.id.etSecondNumber);
        tvResult=findViewById(R.id.tvResult);
    }

    String[] nums() {
        return new String[] {
            etFirstNumber.getText().toString().trim(),etSecondNumber.getText().toString().trim()
        };
    }

    public void performAddition(View v) {
        calc("Addition Result : ",1);
    }

    public void performSubtraction(View v) {
        calc("Subtraction Result : ",2);
    }

    public void performMultiplication(View v) {
        calc("Multiplication Result : ",3);
    }

    public void performDivision(View v) {
        String[] n=nums();
        if(n[0].isEmpty()||n[1].isEmpty()) {
            tvResult.setText("Please enter both numbers.");
            return;
        }

        double b=Double.parseDouble(n[1]);
        if(b==0) {
            tvResult.setText("Division by zero is not allowed.");
            return;
        }

        tvResult.setText("Division Result : "+(Double.parseDouble(n[0])/b));
    }

    void calc(String label,int op) {
        String[] n=nums();
        if(n[0].isEmpty()||n[1].isEmpty()) {
            tvResult.setText("Please enter both numbers.");
            return;
        }

        int a=Integer.parseInt(n[0]),b=Integer.parseInt(n[1]);
        int r=op==1?a+b:op==2?a-b:a*b;
        tvResult.setText(label+r);
    }
}


====================================================================================================
# FILE 05/38: 05_TextColorChange.txt
# TITLE: Create an app that changes text color when a button is clicked.
====================================================================================================

/*
========================================================================================
Filename: 05_TextColorChange.txt
Program 05: Create an app that changes text color when a button is clicked.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 TextView:
     - tvColorText: Heading 'Color Change'
     - tvColorName: Label showing the current color name (e.g. 'Red', 'Green', 'Blue')
   Add 1 Button:
     - Text: 'Change', onClick: 'changeTextColor'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - None.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.textcolorchange;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    TextView tvColorText,tvColorName;
    int[] colors= {
        Color.RED,Color.BLUE,Color.GREEN,Color.YELLOW,Color.MAGENTA
    };
    String[] names= {
        "RED","BLUE","GREEN","YELLOW","MAGENTA"
    };
    int i=0;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        tvColorText=findViewById(R.id.tvColorText);
        tvColorName=findViewById(R.id.tvColorName);
    }

    public void changeTextColor(View v) {
        tvColorText.setTextColor(colors[i]);
        tvColorName.setText(names[i]);
        i=(i+1)%colors.length;
    }
}


====================================================================================================
# FILE 06/38: 06_DateTimeLinear.txt
# TITLE: Create an app that displays Date and Time in different formats using Linear Layout.
====================================================================================================

/*
========================================================================================
Filename: 06_DateTimeLinear.txt
Program 06: Create an app that displays Date and Time in different formats using Linear Layout.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 4 TextView:
     - tvTitle: 'Date and Time'
     - tvNumericDate: To display date in numeric format (e.g., 'dd/MM/yyyy')
     - tvTextualDate: To display date in textual format (e.g., 'EEEE, MMMM d')
     - tvCurrentTime: To display time format (e.g., 'hh:mm a')
   Add 1 Button:
     - Text: 'Display', onClick: 'displayDateAndTime'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - None.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.datetimelinear;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    TextView tvNumericDate,tvTextualDate,tvCurrentTime;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        tvNumericDate=findViewById(R.id.tvNumericDate);
        tvTextualDate=findViewById(R.id.tvTextualDate);
        tvCurrentTime=findViewById(R.id.tvCurrentTime);
    }

    public void displayDateAndTime(View v) {
        Date d=Calendar.getInstance().getTime();
        tvNumericDate.setText(new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(d));
        tvTextualDate.setText(new SimpleDateFormat("EEEE, MMMM d",Locale.getDefault()).format(d));
        tvCurrentTime.setText(new SimpleDateFormat("hh:mm a",Locale.getDefault()).format(d));
    }
}


====================================================================================================
# FILE 07/38: 07_ToastMessage.txt
# TITLE: Create an app that displays a Toast on the launch of an activity.
====================================================================================================

/*
========================================================================================
Filename: 07_ToastMessage.txt
Program 07: Create an app that displays a Toast on the launch of an activity.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 EditText (TextBox):
     - etToastMessage (Hint: 'Enter Toast Message')
   Add 1 Button:
     - Text: 'Display Toast', onClick: 'displayToast'
   Add 1 TextView:
     - tvTitle: 'Custom Toast Message'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Displays a Toast automatically in onCreate() on activity launch, plus button click.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.toastmessage;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    EditText etToastMessage;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        etToastMessage=findViewById(R.id.etToastMessage);
        Toast.makeText(this,"Hello World",Toast.LENGTH_SHORT).show();
    }

    public void displayToast(View v) {
        String m=etToastMessage.getText().toString().trim();
        if(m.isEmpty())m="Hello World";
        Toast.makeText(this,m,Toast.LENGTH_SHORT).show();
    }
}


====================================================================================================
# FILE 08/38: 08_AlertBox.txt
# TITLE: Create an app that creates an Alert Dialog Box.
====================================================================================================

/*
========================================================================================
Filename: 08_AlertBox.txt
Program 08: Create an app that creates an Alert Dialog Box.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView:
     - tvTitle: 'Alert Box'
   Add 1 Button:
     - Text: 'Show Alert Dialog', onClick: 'showAlertDialog'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - AlertDialog.Builder with Positive, Negative, and Neutral buttons.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.alertbox;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
    }

    public void showAlertDialog(View v) {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("Notification");
        builder.setMessage("This is an alert dialog box triggered by your button click!");
        builder.setCancelable(false);
        builder.setPositiveButton("OK",(d,w)-> {
            Toast.makeText(this,"Clicked OK",Toast.LENGTH_SHORT).show();
            d.dismiss();
        }

        );
        builder.setNegativeButton("Cancel",(d,w)-> {
            Toast.makeText(this,"Dialog Cancelled",Toast.LENGTH_SHORT).show();
            d.dismiss();
        }

        );
        builder.create().show();
    }
}


====================================================================================================
# FILE 09/38: 09_GreetingCard.txt
# TITLE: Create a Greeting card app that displays an image.
====================================================================================================

/*
========================================================================================
Filename: 09_GreetingCard.txt
Program 09: Create a Greeting card app that displays an image.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView:
     - tvGreetingTitle: 'Birthday Greeting Card'
   Add 1 ImageView:
     - ivBirthdayCard: Initial visibility set to GONE or VISIBLE
   Add 1 Button:
     - Text: 'Show Greeting Card', onClick: 'showGreetingCard'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Place image in 'res/raw/birthday.png' or 'res/drawable/birthday.png'.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.greetingcard;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    TextView tvGreetingTitle;
    ImageView ivBirthdayCard;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        tvGreetingTitle=findViewById(R.id.tvGreetingTitle);
        ivBirthdayCard=findViewById(R.id.ivBirthdayCard);
    }

    public void showGreetingCard(View v) {
        tvGreetingTitle.setText("Happy Birthday");
        ivBirthdayCard.setVisibility(View.VISIBLE);
    }
}


====================================================================================================
# FILE 10/38: 10_PlayAudioVideo.txt
# TITLE: Create an app that plays audio when we click on the button "Play Music" and plays a video when we click on the button "Play Video".
====================================================================================================

/*
========================================================================================
Filename: 10_PlayAudioVideo.txt
Program 10: Create an app that plays audio when we click on the button "Play Music" and plays a video when we click on the button "Play Video".
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView:
     - tvTitle: 'Video Audio Player'
   Add 1 VideoView:
     - vvPlayer: For video playback with MediaController
   Add 2 Button:
     - Text: 'Play Video', onClick: 'toggleVideo'
     - Text: 'Play Audio', onClick: 'toggleAudio'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Create folder 'res/raw/' and add 'audio.mp3' (or 'audio') and 'video.mp4' (or 'video').
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.playaudiovideo;

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

public class MainActivity extends AppCompatActivity {
    MediaPlayer mediaPlayer;
    VideoView vvPlayer;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        vvPlayer=findViewById(R.id.vvPlayer);
        vvPlayer.setVideoPath("android.resource://"+getPackageName()+"/"+R.raw.video);
        mediaPlayer=MediaPlayer.create(this,R.raw.audio);
    }

    public void toggleVideo(View v) {
        Button b=(Button)v;
        if(vvPlayer.isPlaying()) {
            vvPlayer.pause();
            b.setText("Play Video");
        }

        else {
            vvPlayer.start();
            b.setText("Pause Video");
        }
    }

    public void toggleAudio(View v) {
        Button b=(Button)v;
        if(mediaPlayer!=null) {
            if(mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                b.setText("Play Audio");
            }

            else {
                mediaPlayer.start();
                b.setText("Pause Audio");
            }
        }
    }

    @Override
    protected void onDestroy() {
        if(mediaPlayer!=null) {
            mediaPlayer.release();
            mediaPlayer=null;
        }

        super.onDestroy();
    }
}


====================================================================================================
# FILE 11/38: 11_OnlineVideo.txt
# TITLE: Create an app that plays video from the internet.
====================================================================================================

/*
========================================================================================
Filename: 11_OnlineVideo.txt
Program 11: Create an app that plays video from the internet.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView:
     - tvTitle: 'Online Video'
   Add 1 VideoView:
     - vvVideo: For online video streaming
   Add 1 Button:
     - Text: 'Play Video', onClick: 'playVideo'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme. No changes needed.

5. AndroidManifest.xml:
   Add Internet permission above <application>:
   <uses-permission android:name="android.permission.INTERNET" />
   Standard launcher activity:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Ensure active Internet connection to stream the URL.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.onlinevideo;

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

public class MainActivity extends AppCompatActivity {
    VideoView vvVideo;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        vvVideo=findViewById(R.id.vvVideo);
        MediaController c=new MediaController(this);
        c.setAnchorView(vvVideo);
        vvVideo.setMediaController(c);
    }

    public void playVideo(View v) {
        vvVideo.setVideoURI(Uri.parse("https://www.w3schools.com/html/mov_bbb.mp4"));
        vvVideo.start();
    }
}


====================================================================================================
# FILE 12/38: 12_OptionsMenu.txt
# TITLE: Create an app to demonstrate Options Menu.
====================================================================================================

/*
========================================================================================
Filename: 12_OptionsMenu.txt
Program 12: Create an app to demonstrate Options Menu.
Files Included: MainActivity.java, menu_main.xml
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView:
     - tvTitle: 'Options Menu Demo'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - Create res/menu/menu_main.xml with 5 items: menuHome ('Home'), menuProfile ('Profile'), menuSettings ('Settings'), menuAbout ('About'), menuExit ('Exit').

4. Themes Configuration (res/values/themes.xml):
   - Must use a theme with an ActionBar (e.g. Theme.MaterialComponents.DayNight.DarkActionBar).

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Overrides onCreateOptionsMenu() and onOptionsItemSelected().
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.optionsmenu;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu m) {
        getMenuInflater().inflate(R.menu.menu_main,m);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        if(id==R.id.menuHome) {
            Toast.makeText(this,"Home Selected",Toast.LENGTH_SHORT).show();
            return true;
        }

        if(id==R.id.menuProfile) {
            Toast.makeText(this,"Profile Selected",Toast.LENGTH_SHORT).show();
            return true;
        }

        if(id==R.id.menuSettings) {
            Toast.makeText(this,"Settings Selected",Toast.LENGTH_SHORT).show();
            return true;
        }

        if(id==R.id.menuAbout) {
            Toast.makeText(this,"About Selected",Toast.LENGTH_SHORT).show();
            return true;
        }

        if(id==R.id.menuExit) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

// ======================================================================================
// File: res/menu/menu_main.xml
// ======================================================================================
<?xml version="1.0" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menuHome" android:title="Home"/>
    <item android:id="@+id/menuProfile" android:title="Profile"/>
    <item android:id="@+id/menuSettings" android:title="Settings"/>
    <item android:id="@+id/menuAbout" android:title="About"/>
    <item android:id="@+id/menuExit" android:title="Exit"/>
</menu>


====================================================================================================
# FILE 13/38: 13_ContextMenu.txt
# TITLE: Create an app that changes the background color of an activity using Context Menu.
====================================================================================================

/*
========================================================================================
Filename: 13_ContextMenu.txt
Program 13: Create an app that changes the background color of an activity using Context Menu.
Files Included: MainActivity.java, context_menu.xml
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 TextView:
     - tvTitle: 'Context Menu'
     - tvLongPress: 'Long Press to Change Color' (registered for ContextMenu)

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - Create res/menu/context_menu.xml with 3 items: colorRed ('Red'), colorGreen ('Green'), colorBlue ('Blue').

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Calls registerForContextMenu(tvLongPress); overrides onCreateContextMenu() and onContextItemSelected().
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.contextmenu;

import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.FrameLayout;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    FrameLayout mainLayout;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        mainLayout=findViewById(R.id.mainLayout);
        registerForContextMenu(findViewById(R.id.tvLongPress));
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu,View view,ContextMenu.ContextMenuInfo info) {
        super.onCreateContextMenu(menu,view,info);
        new MenuInflater(this).inflate(R.menu.context_menu,menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.colorRed) {
            mainLayout.setBackgroundColor(Color.RED);
            return true;
        }

        if(item.getItemId()==R.id.colorGreen) {
            mainLayout.setBackgroundColor(Color.GREEN);
            return true;
        }

        if(item.getItemId()==R.id.colorBlue) {
            mainLayout.setBackgroundColor(Color.BLUE);
            return true;
        }

        return super.onContextItemSelected(item);
    }
}

// ======================================================================================
// File: res/menu/context_menu.xml
// ======================================================================================
<?xml version="1.0" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/colorRed" android:title="Red"/>
    <item android:id="@+id/colorGreen" android:title="Green"/>
    <item android:id="@+id/colorBlue" android:title="Blue"/>
</menu>


====================================================================================================
# FILE 14/38: 14_CheckBoxRadioButton.txt
# TITLE: Create an app to demonstrate how radiobuttons and checkboxes can be used in android.
====================================================================================================

/*
========================================================================================
Filename: 14_CheckBoxRadioButton.txt
Program 14: Create an app to demonstrate how radiobuttons and checkboxes can be used in android.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 RadioGroup (rgGender) containing 2 RadioButtons:
     - rbMale ('Male')
     - rbFemale ('Female')
   Add 3 CheckBox:
     - cbReading ('Reading')
     - cbTravel ('Travelling')
     - cbMovies ('Watching Movies')
   Add 1 Button:
     - Text: 'Display', onClick: 'displaySelection'
   Add 5 TextView:
     - Headings: 'CheckBox and Radio Button', 'Gender', 'Hobbies'
     - Result TextViews: tvSelectedGender, tvSelectedHobbies

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - None.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.checkboxradiobutton;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    RadioGroup rgGender;
    CheckBox cbReading,cbTravel,cbMovies;
    TextView tvSelectedGender,tvSelectedHobbies;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        rgGender=findViewById(R.id.rgGender);
        cbReading=findViewById(R.id.cbReading);
        cbTravel=findViewById(R.id.cbTravel);
        cbMovies=findViewById(R.id.cbMovies);
        tvSelectedGender=findViewById(R.id.tvSelectedGender);
        tvSelectedHobbies=findViewById(R.id.tvSelectedHobbies);
    }

    public void displaySelection(View v) {
        int id=rgGender.getCheckedRadioButtonId();
        if(id==-1) {
            Toast.makeText(this,"Please select a gender",Toast.LENGTH_SHORT).show();
            return;
        }

        RadioButton r=findViewById(id);
        StringBuilder h=new StringBuilder();
        if(cbReading.isChecked())h.append("Reading");
        if(cbTravel.isChecked()) {
            if(h.length()>0)h.append(", ");
            h.append("Travelling");
        }

        if(cbMovies.isChecked()) {
            if(h.length()>0)h.append(", ");
            h.append("Watching Movies");
        }

        if(h.length()==0)h.append("None");
        tvSelectedGender.setText("Gender: "+r.getText());
        tvSelectedHobbies.setText("Hobbies: "+h);
    }
}


====================================================================================================
# FILE 15/38: 15_ButtonClickNewActivity.txt
# TITLE: Create an app that launches a new activity on a button click.
====================================================================================================

/*
========================================================================================
Filename: 15_ButtonClickNewActivity.txt
Program 15: Create an app that launches a new activity on a button click.
Files Included: MainActivity.java, SecondActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   In activity_main.xml:
     - 1 TextView: 'Activity Navigation'
     - 1 Button: Text: 'Open Second Activity', onClick: 'openSecondActivity'
   In activity_second.xml:
     - 1 TextView: 'Welcome to the Second Activity'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   Add second activity registration inside <application>:
   <activity android:name=".SecondActivity" android:exported="false" />
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Create SecondActivity.java extending AppCompatActivity.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.buttonclicknewactivity;

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

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
    }

    public void openSecondActivity(View v) {
        startActivity(new Intent(MainActivity.this,SecondActivity.class));
    }
}

// ======================================================================================
// File: SecondActivity.java
// ======================================================================================
package com.example.buttonclicknewactivity;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_second);
    }
}


====================================================================================================
# FILE 16/38: 16_StudentActivity.txt
# TITLE: Create an app that launches a new activity on a button click to display student details with checkbox and radio buttons.
====================================================================================================

/*
========================================================================================
Filename: 16_StudentActivity.txt
Program 16: Create an app that launches a new activity on a button click to display student details with checkbox and radio buttons.
Files Included: MainActivity.java, SecondaryActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   In activity_main.xml:
     - 2 EditText (TextBox): name (Name), phone (Phone)
     - 1 RadioGroup (radioGroupDept) with 3 RadioButtons: rbCS, rbCivil, rbMechanic
     - 1 RadioGroup (radioGroupGender) with 2 RadioButtons: rbMale, rbFemale
     - 4 CheckBox: cbAI, cbCloud, cbShip, cbAuto
     - 1 Button: Text: 'Insert', onClick: 'insert'
     - 4 TextView labels
   In activity_secondary.xml:
     - 6 TextView: tvName, tvPhone, tvDepartment, tvGender, tvCourses, heading

2. Layout Configuration:
   - LinearLayout / ScrollView

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   Add SecondaryActivity registration:
   <activity android:name=".SecondaryActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - Create SecondaryActivity.java to retrieve extras via getIntent().
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.studentactivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    EditText etName,etPhone;
    RadioGroup rgDept,rgGender;
    CheckBox cbInputAI,cbInputCloud,cbInputShip,cbInputAutocad;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        etName=findViewById(R.id.name);
        etPhone=findViewById(R.id.phone);
        rgDept=findViewById(R.id.radioGroupDept);
        rgGender=findViewById(R.id.radioGroupGender);
        cbInputAI=findViewById(R.id.cbAI);
        cbInputCloud=findViewById(R.id.cbCloud);
        cbInputShip=findViewById(R.id.cbShip);
        cbInputAutocad=findViewById(R.id.cbAuto);
    }

    public void insert(View v) {
        String name=etName.getText().toString().trim(),phone=etPhone.getText().toString().trim();
        if(name.isEmpty()) {
            etName.setError("Enter your name");
            return;
        }

        if(phone.length()!=10) {
            etPhone.setError("Enter a valid 10-digit phone number");
            return;
        }

        int d=rgDept.getCheckedRadioButtonId(),g=rgGender.getCheckedRadioButtonId();
        if(d==-1) {
            Toast.makeText(this,"Please select a department",Toast.LENGTH_SHORT).show();
            return;
        }

        if(g==-1) {
            Toast.makeText(this,"Please select a gender",Toast.LENGTH_SHORT).show();
            return;
        }

        String dept=((RadioButton)findViewById(d)).getText().toString(),gender=((RadioButton)findViewById(g)).getText().toString();
        StringBuilder courses=new StringBuilder();
        if(cbInputAI.isChecked())courses.append(cbInputAI.getText()).append(", ");
        if(cbInputCloud.isChecked())courses.append(cbInputCloud.getText()).append(", ");
        if(cbInputShip.isChecked())courses.append(cbInputShip.getText()).append(", ");
        if(cbInputAutocad.isChecked())courses.append(cbInputAutocad.getText()).append(", ");
        if(courses.length()==0)courses.append("None");
        else courses.setLength(courses.length()-2);
        Intent i=new Intent(this,SecondaryActivity.class);
        i.putExtra("name",name);
        i.putExtra("phone",phone);
        i.putExtra("department",dept);
        i.putExtra("gender",gender);
        i.putExtra("courses",courses.toString());
        startActivity(i);
    }
}

// ======================================================================================
// File: SecondaryActivity.java
// ======================================================================================
package com.example.studentactivity;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class SecondaryActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_secondary);
        String name=getIntent().getStringExtra("name"),phone=getIntent().getStringExtra("phone"),dept=getIntent().getStringExtra("department"),gender=getIntent().getStringExtra("gender"),courses=getIntent().getStringExtra("courses");
        ((TextView)findViewById(R.id.tvName)).setText("Name : "+name);
        ((TextView)findViewById(R.id.tvPhone)).setText("Phone : "+phone);
        ((TextView)findViewById(R.id.tvDepartment)).setText("Department : "+dept);
        ((TextView)findViewById(R.id.tvGender)).setText("Gender : "+gender);
        ((TextView)findViewById(R.id.tvCourses)).setText("Preferred Courses : "+courses);
    }
}


====================================================================================================
# FILE 17/38: 17_EmployeeActivity.txt
# TITLE: Create an app that launches a new activity on a button click to calculate and display employee details and salary.
====================================================================================================

/*
========================================================================================
Filename: 17_EmployeeActivity.txt
Program 17: Create an app that launches a new activity on a button click to calculate and display employee details and salary.
Files Included: MainActivity.java, SecondaryActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   In activity_main.xml:
     - 3 EditText (TextBox): etName (Name), etId (Employee ID), etSalary (Basic Salary)
     - 1 Button: Text: 'Calculate Salary', onClick: 'calculateSalary'
     - 1 TextView heading: 'Employee Salary Calculator'
   In activity_secondary.xml:
     - 7 TextView: tvName, tvId, tvBasic, tvHra, tvDa, tvGross, and heading

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   Add SecondaryActivity registration:
   <activity android:name=".SecondaryActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - HRA = 10% of basic, DA = 7% of basic, Gross = Basic + HRA + DA. Pass via Intent extras to SecondaryActivity.java.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.employeeactivity;

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

public class MainActivity extends AppCompatActivity {
    EditText etName,etId,etSalary;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        etName=findViewById(R.id.etName);
        etId=findViewById(R.id.etId);
        etSalary=findViewById(R.id.etSalary);
    }

    public void calculateSalary(View v) {
        String name=etName.getText().toString().trim(),id=etId.getText().toString().trim(),s=etSalary.getText().toString().trim();
        if(name.isEmpty()||id.isEmpty()||s.isEmpty()) {
            Toast.makeText(this,"Please fill all fields",Toast.LENGTH_SHORT).show();
            return;
        }

        double basic=Double.parseDouble(s),hra=basic*.20,da=basic*.10,gross=basic+hra+da;
        Intent i=new Intent(this,SecondaryActivity.class);
        i.putExtra("name",name);
        i.putExtra("id",id);
        i.putExtra("basic",basic);
        i.putExtra("hra",hra);
        i.putExtra("da",da);
        i.putExtra("gross",gross);
        startActivity(i);
    }
}

// ======================================================================================
// File: SecondaryActivity.java
// ======================================================================================
package com.example.employeeactivity;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class SecondaryActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_secondary);
        ((TextView)findViewById(R.id.tvName)).setText("Employee Name : "+getIntent().getStringExtra("name"));
        ((TextView)findViewById(R.id.tvId)).setText("Employee ID : "+getIntent().getStringExtra("id"));
        double basic=getIntent().getDoubleExtra("basic",0),hra=getIntent().getDoubleExtra("hra",0),da=getIntent().getDoubleExtra("da",0),gross=getIntent().getDoubleExtra("gross",0);
        ((TextView)findViewById(R.id.tvBasic)).setText("Basic Salary : "+basic);
        ((TextView)findViewById(R.id.tvHra)).setText("HRA (20%) : "+hra);
        ((TextView)findViewById(R.id.tvDa)).setText("DA (10%) : "+da);
        ((TextView)findViewById(R.id.tvGross)).setText("Gross Salary : "+gross);
    }
}


====================================================================================================
# FILE 18/38: 18_CustomBroadcast.txt
# TITLE: Create an app to broadcast a custom intent.
====================================================================================================

/*
========================================================================================
Filename: 18_CustomBroadcast.txt
Program 18: Create an app to broadcast a custom intent.
Files Included: MainActivity.java, MyReceiver.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView: 'Custom Broadcast'
   Add 1 Button: Text: 'Send Message', onClick: 'sendMessage'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   Register Custom Receiver in AndroidManifest.xml:
   <receiver android:name=".MyReceiver" android:exported="false">
       <intent-filter>
           <action android:name="com.example.custombroadcast.MY_ACTION" />
       </intent-filter>
   </receiver>

6. Additional Files & Resources Required:
   - Create MyReceiver.java extending BroadcastReceiver to show Toast on receiving the broadcast.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.custombroadcast;

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

public class MainActivity extends AppCompatActivity {
    public static final String MY_ACTION="com.example.custombroadcast.MY_ACTION";
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
    }

    public void sendMessage(View v) {
        Intent i=new Intent(MY_ACTION);
        i.putExtra("message","Hello from MainActivity...");
        i.setPackage(getPackageName());
        sendBroadcast(i);
    }
}

// ======================================================================================
// File: MyReceiver.java
// ======================================================================================
package com.example.custombroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context c,Intent i) {
        String m=i.getStringExtra("message");
        Toast.makeText(c,"Custom Broadcast Received: "+m,Toast.LENGTH_LONG).show();
    }
}


====================================================================================================
# FILE 19/38: 19_AirplaneMode.txt
# TITLE: Create an app to broadcast a system intent. (AIRPLANE MODE CHANGED).
====================================================================================================

/*
========================================================================================
Filename: 19_AirplaneMode.txt
Program 19: Create an app to broadcast a system intent. (AIRPLANE MODE CHANGED).
Files Included: MainActivity.java, AirplaneModeReceiver.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 TextView:
     - tvTitle: 'Airplane Mode Broadcast'
     - tvInstruction: 'Turn Airplane Mode ON or OFF and observe the Toast message.'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   Standard launcher activity:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Create AirplaneModeReceiver.java; dynamically registered in onStart() using IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED) and unregistered in onStop().
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.airplanemode;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    final AirplaneModeReceiver receiver=new AirplaneModeReceiver();
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        IntentFilter f=new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        if(android.os.Build.VERSION.SDK_INT>=33)registerReceiver(receiver,f,Context.RECEIVER_EXPORTED);
        else registerReceiver(receiver,f);
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        }

        catch(Exception ignored) {
        }

        super.onDestroy();
    }
}

// ======================================================================================
// File: AirplaneModeReceiver.java
// ======================================================================================
package com.example.airplanemode;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AirplaneModeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context c,Intent i) {
        if(Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(i.getAction())) {
            boolean on=i.getBooleanExtra("state",false);
            Toast.makeText(c,on?"Airplane Mode turned ON":"Airplane Mode turned OFF",Toast.LENGTH_LONG).show();
        }
    }
}


====================================================================================================
# FILE 20/38: 20_BatteryLow.txt
# TITLE: Create an app to broadcast a system intent – Battery Low.
====================================================================================================

/*
========================================================================================
Filename: 20_BatteryLow.txt
Program 20: Create an app to broadcast a system intent – Battery Low.
Files Included: MainActivity.java, BatteryReceiver.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 3 TextView:
     - tvTitle: 'Battery Low Broadcast'
     - tvInstruction: 'Reduce the battery level below 15% and observe the Toast message.'
     - tvBattery: 'Battery Percentage : --%'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Create BatteryReceiver.java; registered dynamically with Intent.ACTION_BATTERY_LOW and Intent.ACTION_BATTERY_CHANGED.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.batterylow;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    final BatteryReceiver receiver=new BatteryReceiver();
    TextView tvBattery;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        tvBattery=findViewById(R.id.tvBattery);
        IntentFilter f=new IntentFilter();
        f.addAction(Intent.ACTION_BATTERY_LOW);
        f.addAction(Intent.ACTION_BATTERY_CHANGED);
        if(android.os.Build.VERSION.SDK_INT>=33)registerReceiver(receiver,f,Context.RECEIVER_EXPORTED);
        else registerReceiver(receiver,f);
        Intent s=registerReceiver(null,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        if(s!=null) {
            int level=s.getIntExtra(BatteryManager.EXTRA_LEVEL,-1),scale=s.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
            int p=(int)((level*100f)/scale);
            tvBattery.setText("Battery Percentage : "+p+"%");
        }
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        }

        catch(Exception ignored) {
        }

        super.onDestroy();
    }
}

// ======================================================================================
// File: BatteryReceiver.java
// ======================================================================================
package com.example.batterylow;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.widget.Toast;

public class BatteryReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context c,Intent i) {
        if(Intent.ACTION_BATTERY_LOW.equals(i.getAction()))Toast.makeText(c,"Battery Low Broadcast Received!",Toast.LENGTH_LONG).show();
        if(Intent.ACTION_BATTERY_CHANGED.equals(i.getAction())) {
            int l=i.getIntExtra(BatteryManager.EXTRA_LEVEL,-1),s=i.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
            int p=(int)((l*100f)/s);
            if(p<=15)Toast.makeText(c,"Battery Low! ("+p+"%)",Toast.LENGTH_LONG).show();
        }
    }
}


====================================================================================================
# FILE 21/38: 21_AlarmClock.txt
# TITLE: Create an alarm application.
====================================================================================================

/*
========================================================================================
Filename: 21_AlarmClock.txt
Program 21: Create an alarm application.
Files Included: MainActivity.java, AlarmReceiver.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView: 'Alarm Clock'
   Add 2 Button:
     - btnSelectTime: Text: 'Select Time', onClick: 'showTimePicker'
     - btnSetAlarm: Text: 'Set Alarm', onClick: 'setAlarm'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   Register AlarmReceiver inside <application>:
   <receiver android:name=".AlarmReceiver" android:exported="false" />

6. Additional Files & Resources Required:
   - Create AlarmReceiver.java extending BroadcastReceiver (plays ringtone or shows Toast). Uses AlarmManager and TimePickerDialog.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.alarmclock;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    Button btnSelectTime;
    int hour,minute;
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        btnSelectTime=findViewById(R.id.btnSelectTime);
    }

    public void showTimePicker(View v) {
        Calendar c=Calendar.getInstance();
        new TimePickerDialog(this,(tp,h,m)-> {
            hour=h;
            minute=m;
            Calendar t=Calendar.getInstance();
            t.set(Calendar.HOUR_OF_DAY,h);
            t.set(Calendar.MINUTE,m);
            btnSelectTime.setText(new SimpleDateFormat("hh:mm a",Locale.getDefault()).format(t.getTime()));
        }

        ,c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),false).show();
    }

    public void setAlarm(View v) {
        Calendar c=Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY,hour);
        c.set(Calendar.MINUTE,minute);
        c.set(Calendar.SECOND,0);
        if(c.before(Calendar.getInstance()))c.add(Calendar.DATE,1);
        PendingIntent pi=PendingIntent.getBroadcast(this,0,new Intent(this,AlarmReceiver.class),PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);
        AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
        if(am!=null) {
            am.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pi);
            Toast.makeText(this,"Alarm Set Successfully",Toast.LENGTH_SHORT).show();
        }
    }
}

// ======================================================================================
// File: AlarmReceiver.java
// ======================================================================================
package com.example.alarmclock;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context c,Intent i) {
        Toast.makeText(c,"Alarm Ringing!",Toast.LENGTH_LONG).show();
        Uri u=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if(u==null)u=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r=RingtoneManager.getRingtone(c,u);
        if(r!=null)r.play();
    }
}


====================================================================================================
# FILE 22/38: 22_ContactDisplay.txt
# TITLE: Create an app that displays a simple ListView. (Contacts list).
====================================================================================================

/*
========================================================================================
Filename: 22_ContactDisplay.txt
Program 22: Create an app that displays a simple ListView. (Contacts list).
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView: 'Contact List'
   Add 1 ListView:
     - id: listView (for rendering contacts)

2. Layout Configuration:
   - LinearLayout (vertical, padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Default theme.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Populates ListView using ArrayAdapter<String> with contact names/numbers and sets setOnItemClickListener to show Toast.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.contactdisplay;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.activity_main);
        ListView listView=findViewById(R.id.listView);
        String[] contacts= {
            "Ashbi: 9863728373","Jees: 9765389276","Rena: 8795739074","Kishore: 9635489207","Jasin: 8975378493","Diya: 9657893765","Merlin: 8976467854"
        };
        listView.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,contacts));
    }
}


====================================================================================================
# FILE 23/38: 23_FoodOrderApp.txt
# TITLE: Develop an Android application in Java that enables customers to place a food order, view the order summary, and generate the final bill using three activities.
====================================================================================================

/*
========================================================================================
Filename: 23_FoodOrderApp.txt
Program 23: Develop an Android application in Java that enables customers to place a food order, view the order summary, and generate the final bill using three activities.
Files Included: MainActivity.java, OrderSummaryActivity.java, FinalInvoiceActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Activity 1 (activity_main.xml):
     - 2 EditText (TextBox): etCustomerName, etMobileNumber
     - 1 RadioGroup (rgMealType) with 2 RadioButtons: rbVeg, rbNonVeg
     - 4 CheckBox: cbPizza (₹250), cbBurger (₹150), cbSandwich (₹120), cbSoftDrink (₹60)
     - 1 Button: btnPlaceOrder ('Place Order')
     - 3 TextView labels
   Activity 2 (activity_order_summary.xml):
     - 5 TextViews (Name, Mobile, Meal Type, Items, Total Bill)
     - 1 Button: btnGenerateInvoice ('Generate Invoice')
   Activity 3 (activity_final_invoice.xml):
     - 8 TextViews showing invoice breakdown, discount, final amount

2. Layout Configuration:
   - LinearLayout / ScrollView

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Use NoActionBar theme (e.g. Theme.MaterialComponents.DayNight.NoActionBar in res/values/themes.xml).

5. AndroidManifest.xml:
   Register 2 additional activities:
   <activity android:name=".OrderSummaryActivity" android:exported="false" />
   <activity android:name=".FinalInvoiceActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - Create OrderSummaryActivity.java and FinalInvoiceActivity.java.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.foodorderapp;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    private EditText etCustomerName, etMobileNumber;
    private RadioGroup rgMealType;
    private CheckBox cbPizza, cbBurger, cbSandwich, cbSoftDrink;
    private Button btnPlaceOrder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etCustomerName = findViewById(R.id.etCustomerName);
        etMobileNumber = findViewById(R.id.etMobileNumber);
        rgMealType = findViewById(R.id.rgMealType);
        cbPizza = findViewById(R.id.cbPizza);
        cbBurger = findViewById(R.id.cbBurger);
        cbSandwich = findViewById(R.id.cbSandwich);
        cbSoftDrink = findViewById(R.id.cbSoftDrink);
        btnPlaceOrder = findViewById(R.id.btnPlaceOrder);
        btnPlaceOrder.setOnClickListener(v -> validateAndSubmitOrder());
    }
    private void validateAndSubmitOrder() {
        String name = etCustomerName.getText().toString().trim();
        String mobile = etMobileNumber.getText().toString().trim();
        if (name.isEmpty()) {
            etCustomerName.setError("Customer name cannot be empty");
            etCustomerName.requestFocus();
            return;
        }
        if (mobile.length() != 10 || !mobile.matches("\\d{10}")) {
            etMobileNumber.setError("Mobile number must be exactly 10 digits");
            etMobileNumber.requestFocus();
            return;
        }
        int selectedMealId = rgMealType.getCheckedRadioButtonId();
        if (selectedMealId == -1) {
            Toast.makeText(this, "Please select a meal type", Toast.LENGTH_SHORT).show();
            return;
        }
        RadioButton selectedRadioButton = findViewById(selectedMealId);
        String mealType = selectedRadioButton.getText().toString();
        ArrayList<String> selectedItems = new ArrayList<>();
        double totalBill = 0.0;
        if (cbPizza.isChecked()) {
            selectedItems.add("Pizza (₹250)");
            totalBill += 250;
        }
        if (cbBurger.isChecked()) {
            selectedItems.add("Burger (₹150)");
            totalBill += 150;
        }
        if (cbSandwich.isChecked()) {
            selectedItems.add("Sandwich (₹120)");
            totalBill += 120;
        }
        if (cbSoftDrink.isChecked()) {
            selectedItems.add("Soft Drink (₹60)");
            totalBill += 60;
        }
        if (selectedItems.isEmpty()) {
            Toast.makeText(this, "Please select at least one food item", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(MainActivity.this, OrderSummaryActivity.class);
        intent.putExtra("CUSTOMER_NAME", name);
        intent.putExtra("MOBILE_NUMBER", mobile);
        intent.putExtra("MEAL_TYPE", mealType);
        intent.putStringArrayListExtra("SELECTED_ITEMS", selectedItems);
        intent.putExtra("TOTAL_BILL", totalBill);
        startActivity(intent);
    }
}

// ======================================================================================
// File: OrderSummaryActivity.java
// ======================================================================================
package com.example.foodorderapp;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class OrderSummaryActivity extends AppCompatActivity {
    private TextView tvName, tvMobile, tvMealType, tvItems, tvTotalBill;
    private Button btnGenerateInvoice;
    private String name, mobile, mealType;
    private ArrayList<String> items;
    private double totalBill;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_summary);
        tvName = findViewById(R.id.tvSummaryName);
        tvMobile = findViewById(R.id.tvSummaryMobile);
        tvMealType = findViewById(R.id.tvSummaryMealType);
        tvItems = findViewById(R.id.tvSummaryItems);
        tvTotalBill = findViewById(R.id.tvTotalBill);
        btnGenerateInvoice = findViewById(R.id.btnGenerateInvoice);
        Intent intent = getIntent();
        if (intent != null) {
            name = intent.getStringExtra("CUSTOMER_NAME");
            mobile = intent.getStringExtra("MOBILE_NUMBER");
            mealType = intent.getStringExtra("MEAL_TYPE");
            items = intent.getStringArrayListExtra("SELECTED_ITEMS");
            totalBill = intent.getDoubleExtra("TOTAL_BILL", 0.0);
            tvName.setText("Name: " + name);
            tvMobile.setText("Mobile: " + mobile);
            tvMealType.setText("Meal Type: " + mealType);
            StringBuilder itemsFormatted = new StringBuilder("Selected Items:\n");
            if (items != null) {
                for (String item : items) {
                    itemsFormatted.append(" • ").append(item).append("\n");
                }
            }
            tvItems.setText(itemsFormatted.toString().trim());
            tvTotalBill.setText(String.format("Total Bill Amount: ₹%.2f", totalBill));
        }
        btnGenerateInvoice.setOnClickListener(v -> {
            Intent invoiceIntent = new Intent(OrderSummaryActivity.this, FinalInvoiceActivity.class);
            invoiceIntent.putExtra("CUSTOMER_NAME", name);
            invoiceIntent.putExtra("MOBILE_NUMBER", mobile);
            invoiceIntent.putExtra("MEAL_TYPE", mealType);
            invoiceIntent.putStringArrayListExtra("SELECTED_ITEMS", items);
            invoiceIntent.putExtra("TOTAL_BILL", totalBill);
            startActivity(invoiceIntent);
        });
    }
}

// ======================================================================================
// File: FinalInvoiceActivity.java
// ======================================================================================
package com.example.foodorderapp;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class FinalInvoiceActivity extends AppCompatActivity {
    private TextView tvName, tvMobile, tvMealType, tvItems;
    private TextView tvSubtotal, tvDiscount, tvFinalAmount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_final_invoice);
        tvName = findViewById(R.id.tvInvoiceName);
        tvMobile = findViewById(R.id.tvInvoiceMobile);
        tvMealType = findViewById(R.id.tvInvoiceMealType);
        tvItems = findViewById(R.id.tvInvoiceItems);
        tvSubtotal = findViewById(R.id.tvInvoiceSubtotal);
        tvDiscount = findViewById(R.id.tvInvoiceDiscount);
        tvFinalAmount = findViewById(R.id.tvInvoiceFinalAmount);
        Intent intent = getIntent();
        if (intent != null) {
            String name = intent.getStringExtra("CUSTOMER_NAME");
            String mobile = intent.getStringExtra("MOBILE_NUMBER");
            String mealType = intent.getStringExtra("MEAL_TYPE");
            ArrayList<String> items = intent.getStringArrayListExtra("SELECTED_ITEMS");
            double totalBill = intent.getDoubleExtra("TOTAL_BILL", 0.0);
            tvName.setText("Customer Name: " + name);
            tvMobile.setText("Mobile: " + mobile);
            tvMealType.setText("Meal Type: " + mealType);
            StringBuilder itemsFormatted = new StringBuilder("Ordered Items:\n");
            if (items != null) {
                for (String item : items) {
                    itemsFormatted.append(" • ").append(item).append("\n");
                }
            }
            tvItems.setText(itemsFormatted.toString().trim());
            double discountRate = 0.0;
            if (totalBill > 800) {
                discountRate = 0.15;
            } else if (totalBill >= 500) {
                discountRate = 0.10;
            } else {
                discountRate = 0.00;
            }
            double discountAmount = totalBill * discountRate;
            double finalAmount = totalBill - discountAmount;
            tvSubtotal.setText(String.format("Subtotal: ₹%.2f", totalBill));
            tvDiscount.setText(String.format("Discount (%.0f%%): -₹%.2f", discountRate * 100, discountAmount));
            tvFinalAmount.setText(String.format("Final Amount Payable: ₹%.2f", finalAmount));
        }
    }
}


====================================================================================================
# FILE 24/38: 24_ThreeActivityApp.txt
# TITLE: Develop an Android application using Java consisting of three activities. The application must use Explicit Intents, Intent Extras, RadioButtons, CheckBoxes, Options Menu.
====================================================================================================

/*
========================================================================================
Filename: 24_ThreeActivityApp.txt
Program 24: Develop an Android application using Java consisting of three activities. The application must use Explicit Intents, Intent Extras, RadioButtons, CheckBoxes, Options Menu.
Files Included: MainActivity.java, SecondActivity.java, ThirdActivity.java, main_menu.xml
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Activity 1 (activity_main.xml):
     - 2 EditText (TextBox): etName (Enter Name), etAge (Enter Age)
     - 1 Button: Text: 'Next', onClick: 'nextPage'
     - 1 TextView heading: 'Student Registration'
   Activity 2 (activity_second.xml):
     - 1 RadioGroup with 2 RadioButtons: rbMale, rbFemale
     - 1 Button: Text: 'Next', onClick: 'nextPage'
   Activity 3 (activity_third.xml):
     - 3 CheckBox: cbJava, cbAndroid, cbPython
     - 1 Button: Text: 'Submit', onClick: 'submit'
     - TextView: tvDetails

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - Create res/menu/main_menu.xml with menuClear ('Clear') and menuExit ('Exit').

4. Themes Configuration (res/values/themes.xml):
   - Default theme with ActionBar.

5. AndroidManifest.xml:
   Register SecondActivity and ThirdActivity:
   <activity android:name=".SecondActivity" android:exported="false" />
   <activity android:name=".ThirdActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - Create SecondActivity.java, ThirdActivity.java, and options menu in all activities.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.studentregistration;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    EditText etName, etAge;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etName = findViewById(R.id.etName);
        etAge = findViewById(R.id.etAge);
    }
    public void nextPage(View view) {
        String name = etName.getText().toString();
        String age = etAge.getText().toString();
        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("age", age);
        startActivity(intent);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menuClear) {
            etName.setText("");
            etAge.setText("");
            return true;
        }
        if (item.getItemId() == R.id.menuExit) {
            finishAffinity();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

// ======================================================================================
// File: SecondActivity.java
// ======================================================================================
package com.example.studentregistration;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
    RadioGroup radioGroup;
    String name, age;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        radioGroup = findViewById(R.id.radioGroup);
        name = getIntent().getStringExtra("name");
        age = getIntent().getStringExtra("age");
    }
    public void nextPage(View view) {
        int selectedId = radioGroup.getCheckedRadioButtonId();
        if (selectedId == -1) {
            return;
        }
        RadioButton radioButton = findViewById(selectedId);
        String gender = radioButton.getText().toString();
        Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("age", age);
        intent.putExtra("gender", gender);
        startActivity(intent);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menuClear) {
            radioGroup.clearCheck();
            return true;
        }
        if (item.getItemId() == R.id.menuExit) {
            finishAffinity();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

// ======================================================================================
// File: ThirdActivity.java
// ======================================================================================
package com.example.studentregistration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class ThirdActivity extends AppCompatActivity {
    TextView tvDetails;
    CheckBox cbJava, cbAndroid, cbPython;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third);
        tvDetails = findViewById(R.id.tvDetails);
        cbJava = findViewById(R.id.cbJava);
        cbAndroid = findViewById(R.id.cbAndroid);
        cbPython = findViewById(R.id.cbPython);
        String name = getIntent().getStringExtra("name");
        String age = getIntent().getStringExtra("age");
        String gender = getIntent().getStringExtra("gender");
        tvDetails.setText(
                "Name : " + name +
                        "\nAge : " + age +
                        "\nGender : " + gender
        );
    }
    public void submit(View view) {
        String courses = "";
        if (cbJava.isChecked())
            courses += "Java ";
        if (cbAndroid.isChecked())
            courses += "Android ";
        if (cbPython.isChecked())
            courses += "Python ";
        Toast.makeText(
                this,
                "Selected Courses: " + courses,
                Toast.LENGTH_LONG
        ).show();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menuClear) {
            cbJava.setChecked(false);
            cbAndroid.setChecked(false);
            cbPython.setChecked(false);
            return true;
        }
        if (item.getItemId() == R.id.menuExit) {
            finishAffinity();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

// ======================================================================================
// File: res/menu/main_menu.xml
// ======================================================================================
<?xml version="1.0" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/menuClear" android:title="Clear" app:showAsAction="never"/>
    <item android:id="@+id/menuExit" android:title="Exit" app:showAsAction="never"/>
</menu>


====================================================================================================
# FILE 25/38: 25_StudentDatabase.txt
# TITLE: Create an app to insert name and age with an add button with toast and a view details button to show all details from student table.
====================================================================================================

/*
========================================================================================
Filename: 25_StudentDatabase.txt
Program 25: Create an app to insert name and age with an add button with toast and a view details button to show all details from student table.
Files Included: MainActivity.java, DatabaseHelper.java, ViewDetailsActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   In activity_main.xml:
     - 2 EditText (TextBox): etName (Student Name), etAge (Age, inputType='number')
     - 2 Button: btnAdd ('Add Student', onClick='addStudent'), btnView ('View Details', onClick='viewDetails')
     - 1 TextView: tvTitle ('Student Database')
   In activity_view_details.xml:
     - 2 TextView: tvTitle ('Student Details'), tvDetails (to list records)

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   Register ViewDetailsActivity:
   <activity android:name=".ViewDetailsActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - Create DatabaseHelper.java (SQLiteOpenHelper creating table 'student' with id, name, age) and ViewDetailsActivity.java.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.studentdatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    EditText etName, etAge;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etName = findViewById(R.id.etName);
        etAge = findViewById(R.id.etAge);
        db = new DatabaseHelper(this);
    }
    public void addStudent(View view) {
        String name = etName.getText().toString();
        String age = etAge.getText().toString();
        if (name.isEmpty() || age.isEmpty()) {
            Toast.makeText(this,
                    "Enter all details",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        boolean inserted = db.insertStudent(name, age);
        if (inserted) {
            Toast.makeText(this,
                    "Row Inserted Successfully",
                    Toast.LENGTH_SHORT).show();
            etName.setText("");
            etAge.setText("");
        }
    }
    public void viewDetails(View view) {
        startActivity(new android.content.Intent(
                this, ViewDetailsActivity.class));
    }
}

// ======================================================================================
// File: DatabaseHelper.java
// ======================================================================================
package com.example.studentdatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
        super(context, "StudentDB", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
                "CREATE TABLE student(" +
                        "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                        "name TEXT," +
                        "age INTEGER)"
        );
    }
    @Override
    public void onUpgrade(SQLiteDatabase db,
                          int oldVersion,
                          int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS student");
        onCreate(db);
    }
    public boolean insertStudent(String name, String age) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("age", age);
        long result = db.insert("student", null, values);
        return result != -1;
    }
    public Cursor getStudents() {
        SQLiteDatabase db = getReadableDatabase();
        return db.rawQuery(
                "SELECT * FROM student",
                null
        );
    }
}

// ======================================================================================
// File: ViewDetailsActivity.java
// ======================================================================================
package com.example.studentdatabase;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class ViewDetailsActivity extends AppCompatActivity {
    TextView tvDetails;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_details);
        tvDetails = findViewById(R.id.tvDetails);
        db = new DatabaseHelper(this);
        Cursor cursor = db.getStudents();
        StringBuilder data = new StringBuilder();
        while (cursor.moveToNext()) {
            data.append("ID : ")
                    .append(cursor.getString(0))
                    .append("\n");
            data.append("Name : ")
                    .append(cursor.getString(1))
                    .append("\n");
            data.append("Age : ")
                    .append(cursor.getString(2))
                    .append("\n\n");
        }
        cursor.close();
        tvDetails.setText(data.toString());
    }
}


====================================================================================================
# FILE 26/38: 26_LibraryManagement.txt
# TITLE: Create an app for library management insert the following details to db: book_id, book_name, publisher, author, published_year, price, stock and a view button to view details of all books.
====================================================================================================

/*
========================================================================================
Filename: 26_LibraryManagement.txt
Program 26: Create an app for library management insert the following details to db: book_id, book_name, publisher, author, published_year, price, stock and a view button to view details of all books.
Files Included: MainActivity.java, DatabaseHelper.java, ViewDetailsActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   In activity_main.xml:
     - 7 EditText (TextBox): etBookId, etBookName, etAuthor, etPublisher, etYear, etPrice, etStock
     - 2 Button: btnAdd ('Add Book', onClick='addBook'), btnView ('View Details', onClick='viewBooks')
     - 1 TextView: heading 'Library Management'
   In activity_view_details.xml:
     - 2 TextView: heading 'Book Details', tvDetails (scrollable list of books)

2. Layout Configuration:
   - ScrollView with vertical LinearLayout

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   Register ViewDetailsActivity:
   <activity android:name=".ViewDetailsActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - Create DatabaseHelper.java (SQLite database table 'books' with book_id, book_name, author, publisher, year, price, stock) and ViewDetailsActivity.java.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.librarymanagement;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    EditText etBookId, etBookName, etAuthor, etPublisher;
    EditText etYear, etPrice, etStock;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etBookId = findViewById(R.id.etBookId);
        etBookName = findViewById(R.id.etBookName);
        etAuthor = findViewById(R.id.etAuthor);
        etPublisher = findViewById(R.id.etPublisher);
        etYear = findViewById(R.id.etYear);
        etPrice = findViewById(R.id.etPrice);
        etStock = findViewById(R.id.etStock);
        db = new DatabaseHelper(this);
    }
    public void addBook(View view) {
        String id = etBookId.getText().toString();
        String name = etBookName.getText().toString();
        String author = etAuthor.getText().toString();
        String publisher = etPublisher.getText().toString();
        String year = etYear.getText().toString();
        String price = etPrice.getText().toString();
        String stock = etStock.getText().toString();
        if (id.isEmpty() || name.isEmpty() ||
                author.isEmpty() || publisher.isEmpty() ||
                year.isEmpty() || price.isEmpty() ||
                stock.isEmpty()) {
            Toast.makeText(this,
                    "Enter all details",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        boolean inserted = db.insertBook(
                id, name, author, publisher,
                year, price, stock
        );
        if (inserted) {
            Toast.makeText(this,
                    "Book Inserted Successfully",
                    Toast.LENGTH_SHORT).show();
            etBookId.setText("");
            etBookName.setText("");
            etAuthor.setText("");
            etPublisher.setText("");
            etYear.setText("");
            etPrice.setText("");
            etStock.setText("");
        }
    }
    public void viewBooks(View view) {
        Intent intent = new Intent(
                this,
                ViewDetailsActivity.class
        );
        startActivity(intent);
    }
}

// ======================================================================================
// File: DatabaseHelper.java
// ======================================================================================
package com.example.librarymanagement;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
        super(context, "LibraryDB", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
                "CREATE TABLE book(" +
                        "bookid TEXT PRIMARY KEY," +
                        "bookname TEXT," +
                        "author TEXT," +
                        "publisher TEXT," +
                        "year INTEGER," +
                        "price REAL," +
                        "stock INTEGER)"
        );
    }
    @Override
    public void onUpgrade(SQLiteDatabase db,
                          int oldVersion,
                          int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS book");
        onCreate(db);
    }
    public boolean insertBook(
            String id,
            String name,
            String author,
            String publisher,
            String year,
            String price,
            String stock) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("bookid", id);
        values.put("bookname", name);
        values.put("author", author);
        values.put("publisher", publisher);
        values.put("year", year);
        values.put("price", price);
        values.put("stock", stock);
        long result = db.insert(
                "book",
                null,
                values
        );
        return result != -1;
    }
    public Cursor getBooks() {
        SQLiteDatabase db = getReadableDatabase();
        return db.rawQuery(
                "SELECT * FROM book",
                null
        );
    }
}

// ======================================================================================
// File: ViewDetailsActivity.java
// ======================================================================================
package com.example.librarymanagement;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class ViewDetailsActivity extends AppCompatActivity {
    TextView tvDetails;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_details);
        tvDetails = findViewById(R.id.tvDetails);
        db = new DatabaseHelper(this);
        Cursor cursor = db.getBooks();
        StringBuilder data = new StringBuilder();
        while (cursor.moveToNext()) {
            data.append("Book ID : ")
                    .append(cursor.getString(0))
                    .append("\n");
            data.append("Book Name : ")
                    .append(cursor.getString(1))
                    .append("\n");
            data.append("Author : ")
                    .append(cursor.getString(2))
                    .append("\n");
            data.append("Publisher : ")
                    .append(cursor.getString(3))
                    .append("\n");
            data.append("Published Year : ")
                    .append(cursor.getString(4))
                    .append("\n");
            data.append("Price : ")
                    .append(cursor.getString(5))
                    .append("\n");
            data.append("Stock : ")
                    .append(cursor.getString(6))
                    .append("\n\n");
        }
        cursor.close();
        tvDetails.setText(data.toString());
    }
}


====================================================================================================
# FILE 27/38: 27_ProductDatabase.txt
# TITLE: Create an app to show product names using database and the following controls: ListView, GridView, TextBox, Button.
====================================================================================================

/*
========================================================================================
Filename: 27_ProductDatabase.txt
Program 27: Create an app to show product names using database and the following controls: ListView, GridView, TextBox, Button.
Files Included: MainActivity.java, DatabaseHelper.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 EditText (TextBox):
     - etProduct (Hint: 'Enter Product Name')
   Add 1 Button:
     - Text: 'Add Product', onClick: 'addProduct'
   Add 3 TextView:
     - Heading: 'Product Database'
     - Subheadings: 'Product List', 'Product Grid'
   Add 1 ListView: id listView (renders product list)
   Add 1 GridView: id gridView (numColumns='2', renders product grid)

2. Layout Configuration:
   - LinearLayout (vertical, padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Create DatabaseHelper.java for SQLite storage of product names. Displays data simultaneously in ListView and GridView via ArrayAdapter.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.productdatabase;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    EditText etProduct;
    ListView listView;
    GridView gridView;
    DatabaseHelper db;
    ArrayList<String> products;
    ArrayAdapter<String> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etProduct = findViewById(R.id.etProduct);
        listView = findViewById(R.id.listView);
        gridView = findViewById(R.id.gridView);
        db = new DatabaseHelper(this);
        showProducts();
    }
    public void addProduct(View view) {
        String product = etProduct.getText().toString();
        if (product.isEmpty()) {
            Toast.makeText(this, "Enter Product Name", Toast.LENGTH_SHORT).show();
            return;
        }
        db.insertProduct(product);
        Toast.makeText(this, "Product Inserted", Toast.LENGTH_SHORT).show();
        etProduct.setText("");
        showProducts();
    }
    private void showProducts() {
        products = new ArrayList<>();
        Cursor cursor = db.getProducts();
        while (cursor.moveToNext()) {
            products.add(cursor.getString(1));
        }
        cursor.close();
        adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_list_item_1,
                products
        );
        listView.setAdapter(adapter);
        gridView.setAdapter(adapter);
    }
}

// ======================================================================================
// File: DatabaseHelper.java
// ======================================================================================
package com.example.productdatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
        super(context, "ProductDB", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
                "CREATE TABLE product(" +
                        "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                        "name TEXT)"
        );
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS product");
        onCreate(db);
    }
    public void insertProduct(String name) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", name);
        db.insert("product", null, values);
    }
    public Cursor getProducts() {
        SQLiteDatabase db = getReadableDatabase();
        return db.rawQuery(
                "SELECT * FROM product",
                null
        );
    }
}


====================================================================================================
# FILE 28/38: 28_CounterApp.txt
# TITLE: Create an app to demonstrate counter.
====================================================================================================

/*
========================================================================================
Filename: 28_CounterApp.txt
Program 28: Create an app to demonstrate counter.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 TextView:
     - Title: 'Counter'
     - counterText: Displaying current count (initial '0', textSize 48sp)
   Add 3 Button:
     - Increment: Text: 'Increment', onClick: 'increment'
     - Decrement: id: decrementButton, Text: 'Decrement', onClick: 'decrement'
     - Reset: Text: 'Reset', onClick: 'reset'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - None.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.counterapp;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    TextView counterText;
    Button decrementButton;
    int count = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        counterText = findViewById(R.id.counterText);
        decrementButton = findViewById(R.id.decrementButton);
    }
    public void increment(View view) {
        count++;
        counterText.setText(String.valueOf(count));
        if (count >= 1) {
            decrementButton.setVisibility(View.VISIBLE);
        }
    }
    public void decrement(View view) {
        count--;
        if (count == 0) {
            decrementButton.setVisibility(View.GONE);
        }
        counterText.setText(String.valueOf(count));
    }
    public void reset(View view) {
        count = 0;
        counterText.setText(String.valueOf(count));
        decrementButton.setVisibility(View.GONE);
    }
}


====================================================================================================
# FILE 29/38: 29_TextToSpeechApp.txt
# TITLE: Create an app to convert text to speech.
====================================================================================================

/*
========================================================================================
Filename: 29_TextToSpeechApp.txt
Program 29: Create an app to convert text to speech.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView: 'Text to Speech'
   Add 1 EditText (TextBox):
     - textInput (Hint: 'Enter text')
   Add 1 Button:
     - Text: 'Speak', onClick: 'speakText'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Implements TextToSpeech.OnInitListener. Remember to shut down TextToSpeech in onDestroy().
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.texttospeechapp;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
    EditText textInput;
    TextToSpeech textToSpeech;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textInput = findViewById(R.id.textInput);
        textToSpeech = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                textToSpeech.setLanguage(Locale.US);
            }
        });
    }
    public void speakText(View view) {
        String text = textInput.getText().toString();
        if (text.isEmpty()) {
            Toast.makeText(this, "Enter some text", Toast.LENGTH_SHORT).show();
        } else {
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
        }
    }
    @Override
    protected void onDestroy() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onDestroy();
    }
}


====================================================================================================
# FILE 30/38: 30_AsynchronousTask.txt
# TITLE: Create an app to perform asynchronous task.
====================================================================================================

/*
========================================================================================
Filename: 30_AsynchronousTask.txt
Program 30: Create an app to perform asynchronous task.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 TextView:
     - Title: 'Asynchronous Task'
     - statusText: 'Click the button to start'
   Add 1 Button:
     - startButton: Text: 'Start Task', onClick: 'startTask'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Performs background execution using ExecutorService / Handler or AsyncTask simulation, showing progress updates.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.asynchronoustask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
    TextView statusText;
    Button startButton;
    ExecutorService executor;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        statusText = findViewById(R.id.statusText);
        startButton = findViewById(R.id.startButton);
        executor = Executors.newSingleThreadExecutor();
        handler = new Handler(Looper.getMainLooper());
    }
    public void startTask(View view) {
        // Disable button
        startButton.setEnabled(false);
        startButton.setText("Task Running...");
        startButton.setAlpha(0.5f);
        statusText.setText("Task is running...");
        executor.execute(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.post(() -> {
                statusText.setText("Task completed!");
                // Enable button again
                startButton.setEnabled(true);
                startButton.setText("Start Task");
                startButton.setAlpha(1.0f);
            });
        });
    }
    @Override
    protected void onDestroy() {
        executor.shutdown();
        super.onDestroy();
    }
}


====================================================================================================
# FILE 31/38: 31_LoginRegistration.txt
# TITLE: Create an app for Registration and Login Activity using database.
====================================================================================================

/*
========================================================================================
Filename: 31_LoginRegistration.txt
Program 31: Create an app for Registration and Login Activity using database.
Files Included: MainActivity.java, RegisterActivity.java, LoginActivity.java, DatabaseHelper.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   MainActivity (activity_main.xml):
     - 1 TextView: 'User Account'
     - 2 Button: 'Register' (onClick='openRegister'), 'Login' (onClick='openLogin')
   RegisterActivity (activity_register.xml):
     - 1 TextView: 'Registration'
     - 2 EditText (TextBox): username, password
     - 1 Button: 'Register' (onClick='register')
   LoginActivity (activity_login.xml):
     - 1 TextView: 'Login'
     - 2 EditText (TextBox): username, password
     - 1 Button: 'Login' (onClick='login')

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   Register LoginActivity and RegisterActivity:
   <activity android:name=".RegisterActivity" android:exported="false" />
   <activity android:name=".LoginActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - Create DatabaseHelper.java (SQLite table 'users' with username and password), RegisterActivity.java, and LoginActivity.java.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.loginregistration;

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

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void openRegister(View view) {
        Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
        startActivity(intent);
    }

    public void openLogin(View view) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
    }
}

// ======================================================================================
// File: RegisterActivity.java
// ======================================================================================
package com.example.loginregistration;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class RegisterActivity extends AppCompatActivity {
    EditText username, password;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        db = new DatabaseHelper(this);
    }
    public void register(View view) {
        String user = username.getText().toString();
        String pass = password.getText().toString();
        if (user.isEmpty() || pass.isEmpty()) {
            Toast.makeText(this,
                    "Enter all details",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        boolean result = db.registerUser(user, pass);
        if (result) {
            Toast.makeText(this,
                    "Registration Successful",
                    Toast.LENGTH_SHORT).show();
            username.setText("");
            password.setText("");
        } else {
            Toast.makeText(this,
                    "Registration Failed",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

// ======================================================================================
// File: LoginActivity.java
// ======================================================================================
package com.example.loginregistration;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity {
    EditText username, password;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        db = new DatabaseHelper(this);
    }
    public void login(View view) {
        String user = username.getText().toString();
        String pass = password.getText().toString();
        if (user.isEmpty() || pass.isEmpty()) {
            Toast.makeText(this,
                    "Enter all details",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        boolean result = db.loginUser(user, pass);
        if (result) {
            Toast.makeText(this,
                    "Login Successful",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this,
                    "Invalid Username or Password",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

// ======================================================================================
// File: DatabaseHelper.java
// ======================================================================================
package com.example.loginregistration;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
        super(context, "UserDB", null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE users(" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "username TEXT," +
                "password TEXT)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS users");
        onCreate(db);
    }
    public boolean registerUser(String username, String password) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username", username);
        values.put("password", password);
        long result = db.insert("users", null, values);
        return result != -1;
    }
    public boolean loginUser(String username, String password) {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(
                "SELECT * FROM users WHERE username=? AND password=?",
                new String[]{username, password}
        );
        boolean result = cursor.getCount() > 0;
        cursor.close();
        return result;
    }
}


====================================================================================================
# FILE 32/38: 32_FlashLightApp.txt
# TITLE: Create an app to turn on and off the flashlight.
====================================================================================================

/*
========================================================================================
Filename: 32_FlashLightApp.txt
Program 32: Create an app to turn on and off the flashlight.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 TextView:
     - Title: 'Flashlight'
     - statusText: 'Flashlight is OFF' (clickable with toggle or icon)

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   Add Camera permission and feature above <application>:
   <uses-permission android:name="android.permission.CAMERA" />
   <uses-feature android:name="android.hardware.camera.flash" />

6. Additional Files & Resources Required:
   - Uses CameraManager.setTorchMode(cameraId, state).
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.flashlightapp;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    ToggleButton toggleButton;
    TextView statusText;
    CameraManager cameraManager;
    String cameraId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toggleButton = findViewById(R.id.toggleButton);
        statusText = findViewById(R.id.statusText);
        cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
        try {
            cameraId = cameraManager.getCameraIdList()[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        toggleButton.setOnCheckedChangeListener((button, isChecked) -> {
            try {
                cameraManager.setTorchMode(cameraId, isChecked);
                if (isChecked) {
                    statusText.setText("Flashlight is ON");
                } else {
                    statusText.setText("Flashlight is OFF");
                }
            } catch (Exception e) {
                statusText.setText("Flashlight is OFF");
            }
        });
    }
}


====================================================================================================
# FILE 33/38: 33_ShakeColorApp.txt
# TITLE: Create an app to change the background color when the phone is shaked or tilted.
====================================================================================================

/*
========================================================================================
Filename: 33_ShakeColorApp.txt
Program 33: Create an app to change the background color when the phone is shaked or tilted.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 2 TextView:
     - Title: 'Shake / Tilt Color'
     - statusText: 'Shake or tilt your phone'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Implements SensorEventListener using SensorManager and Sensor.TYPE_ACCELEROMETER to detect shake/tilt acceleration.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.shakecolorapp;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class MainActivity extends AppCompatActivity
        implements SensorEventListener {
    SensorManager sensorManager;
    Sensor accelerometer;
    TextView statusText;
    Random random = new Random();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        statusText = findViewById(R.id.statusText);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }
    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(
                this,
                accelerometer,
                SensorManager.SENSOR_DELAY_NORMAL
        );
    }
    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        if (Math.abs(x) > 7 || Math.abs(y) > 7) {
            int color = Color.rgb(
                    random.nextInt(256),
                    random.nextInt(256),
                    random.nextInt(256)
            );
            findViewById(android.R.id.content).setBackgroundColor(color);
            statusText.setText("Background Color Changed");
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}


====================================================================================================
# FILE 34/38: 34_CommunicationApp.txt
# TITLE: Create an app to i) Send an SMS. ii) Send an email. iii) To make a call.
====================================================================================================

/*
========================================================================================
Filename: 34_CommunicationApp.txt
Program 34: Create an app to i) Send an SMS. ii) Send an email. iii) To make a call.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView: 'Communication'
   Add 3 Navigation Buttons at the top:
     - 'Send SMS' (onClick='showSMS')
     - 'Send Email' (onClick='showEmail')
     - 'Make a Call' (onClick='showCall')
   SMS Section (initially visible or toggleable):
     - 2 EditText (TextBox): phoneNumber (Phone Number), smsMessage (SMS Message)
     - 1 Button: sendSmsButton ('Send SMS', onClick='sendSMS')
   Email Section (toggleable):
     - 3 EditText (TextBox): email (Email Address), subject (Subject), emailMessage (Email Message)
     - 1 Button: sendEmailButton ('Send Email', onClick='sendEmail')
   Call Section (toggleable):
     - 1 EditText (TextBox): callNumber (Phone Number)
     - 1 Button: makeCallButton ('Make a Call', onClick='makeCall')

2. Layout Configuration:
   - LinearLayout inside ScrollView (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   Uses system implicit intents (ACTION_SENDTO with smsto:/mailto: and ACTION_DIAL with tel:), so no dangerous permissions are strictly needed.
   Standard launcher activity:
   <activity android:name=".MainActivity" android:exported="true" android:windowSoftInputMode="adjustResize" />

6. Additional Files & Resources Required:
   - hideAll() toggles visibility of respective fields dynamically.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.communicationapp;
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.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    EditText phoneNumber, smsMessage;
    EditText email, subject, emailMessage;
    EditText callNumber;
    Button sendSmsButton, sendEmailButton, makeCallButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        phoneNumber = findViewById(R.id.phoneNumber);
        smsMessage = findViewById(R.id.smsMessage);
        email = findViewById(R.id.email);
        subject = findViewById(R.id.subject);
        emailMessage = findViewById(R.id.emailMessage);
        callNumber = findViewById(R.id.callNumber);
        sendSmsButton = findViewById(R.id.sendSmsButton);
        sendEmailButton = findViewById(R.id.sendEmailButton);
        makeCallButton = findViewById(R.id.makeCallButton);
    }
    public void showSMS(View view) {
        hideAll();
        phoneNumber.setVisibility(View.VISIBLE);
        smsMessage.setVisibility(View.VISIBLE);
        sendSmsButton.setVisibility(View.VISIBLE);
    }
    public void showEmail(View view) {
        hideAll();
        email.setVisibility(View.VISIBLE);
        subject.setVisibility(View.VISIBLE);
        emailMessage.setVisibility(View.VISIBLE);
        sendEmailButton.setVisibility(View.VISIBLE);
    }
    public void showCall(View view) {
        hideAll();
        callNumber.setVisibility(View.VISIBLE);
        makeCallButton.setVisibility(View.VISIBLE);
    }
    public void hideAll() {
        phoneNumber.setVisibility(View.GONE);
        smsMessage.setVisibility(View.GONE);
        sendSmsButton.setVisibility(View.GONE);
        email.setVisibility(View.GONE);
        subject.setVisibility(View.GONE);
        emailMessage.setVisibility(View.GONE);
        sendEmailButton.setVisibility(View.GONE);
        callNumber.setVisibility(View.GONE);
        makeCallButton.setVisibility(View.GONE);
    }
    public void sendSMS(View view) {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("smsto:" +
                phoneNumber.getText().toString()));
        intent.putExtra("sms_body",
                smsMessage.getText().toString());
        startActivity(intent);
    }
    public void sendEmail(View view) {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:" +
                email.getText().toString()));
        intent.putExtra(Intent.EXTRA_SUBJECT,
                subject.getText().toString());
        intent.putExtra(Intent.EXTRA_TEXT,
                emailMessage.getText().toString());
        startActivity(intent);
    }
    public void makeCall(View view) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" +
                callNumber.getText().toString()));
        startActivity(intent);
    }
}


====================================================================================================
# FILE 35/38: 35_SensorsApp.txt
# TITLE: Create an Android application to demonstrate the use of light, pressure, and humidity sensors.
====================================================================================================

/*
========================================================================================
Filename: 35_SensorsApp.txt
Program 35: Create an Android application to demonstrate the use of light, pressure, and humidity sensors.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 4 TextView:
     - Title: 'Sensor Monitor'
     - lightText: 'Light: -- lux'
     - pressureText: 'Pressure: -- hPa'
     - humidityText: 'Humidity: -- %'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Implements SensorEventListener. Uses SensorManager to listen to Sensor.TYPE_LIGHT, Sensor.TYPE_PRESSURE, and Sensor.TYPE_RELATIVE_HUMIDITY.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.sensorsapp;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
    SensorManager sensorManager;
    Sensor lightSensor;
    Sensor pressureSensor;
    Sensor humiditySensor;
    TextView lightText;
    TextView pressureText;
    TextView humidityText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lightText = findViewById(R.id.lightText);
        pressureText = findViewById(R.id.pressureText);
        humidityText = findViewById(R.id.humidityText);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        humiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
        if (lightSensor == null) {
            lightText.setText("Light Sensor Not Available");
        }
        if (pressureSensor == null) {
            pressureText.setText("Pressure Sensor Not Available");
        }
        if (humiditySensor == null) {
            humidityText.setText("Humidity Sensor Not Available");
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (lightSensor != null) {
            sensorManager.registerListener(
                    this,
                    lightSensor,
                    SensorManager.SENSOR_DELAY_NORMAL
            );
        }
        if (pressureSensor != null) {
            sensorManager.registerListener(
                    this,
                    pressureSensor,
                    SensorManager.SENSOR_DELAY_NORMAL
            );
        }
        if (humiditySensor != null) {
            sensorManager.registerListener(
                    this,
                    humiditySensor,
                    SensorManager.SENSOR_DELAY_NORMAL
            );
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
            float light = event.values[0];
            lightText.setText(
                    "Light: " + light + " lux"
            );
        }
        if (event.sensor.getType() == Sensor.TYPE_PRESSURE) {
            float pressure = event.values[0];
            pressureText.setText(
                    "Pressure: " + pressure + " hPa"
            );
        }
        if (event.sensor.getType() == Sensor.TYPE_RELATIVE_HUMIDITY) {
            float humidity = event.values[0];
            humidityText.setText(
                    "Humidity: " + humidity + " %"
            );
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Not required
    }
}


====================================================================================================
# FILE 36/38: 36_HallBookingSystem.txt
# TITLE: Hall Booking System (Campus Venue Requisition & Collision Detection Project).
====================================================================================================

/*
========================================================================================
Filename: 36_HallBookingSystem.txt
Program 36: Hall Booking System (Campus Venue Requisition & Collision Detection Project)
Files Included: MainActivity.java, DatabaseHelper.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 4 EditText (TextBox):
     - etApplicantName: Hint: 'Applicant / Coordinator Name'
     - etDepartment: Hint: 'Department / Organization'
     - etContactNumber: Hint: 'Contact Phone Number', inputType: 'phone'
     - etSelectedDate: Hint: 'Select Date', focusable: 'false', clickable: 'true'
   Add 2 Spinner widgets:
     - spinnerHall: Venue selection (Main Auditorium, Chavara Hall, etc.)
     - spinnerSlot: Time slot selection (Morning, Afternoon, Full Day)
   Add 2 Button:
     - btnBookHall: Text: 'Submit Requisition', onClick: 'bookHallSlot'
     - btnViewBookings: Text: 'View All Bookings', onClick: 'viewAllBookings'
   Add 2 TextView:
     - Title: 'Hall Booking System'
     - tvStatusDisplay: For displaying booking ledger and status updates

2. Layout Configuration:
   - ScrollView containing vertical LinearLayout (padding 20dp)

3. Menu Configuration:
   - None required (or optional options menu for Logout/Filter).

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in res/values/themes.xml.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Create DatabaseHelper.java extending SQLiteOpenHelper (with tables for halls and bookings, collision detection method isSlotBooked(hall, date, slot), and insertBooking).
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.hallbookingsystem;
import android.app.DatePickerDialog;
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.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
    private EditText etApplicantName, etDepartment, etContactNumber, etSelectedDate;
    private Spinner spinnerHall, spinnerSlot;
    private Button btnBookHall, btnViewBookings;
    private TextView tvStatusDisplay;
    private DatabaseHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etApplicantName = findViewById(R.id.etApplicantName);
        etDepartment = findViewById(R.id.etDepartment);
        etContactNumber = findViewById(R.id.etContactNumber);
        etSelectedDate = findViewById(R.id.etSelectedDate);
        spinnerHall = findViewById(R.id.spinnerHall);
        spinnerSlot = findViewById(R.id.spinnerSlot);
        btnBookHall = findViewById(R.id.btnBookHall);
        btnViewBookings = findViewById(R.id.btnViewBookings);
        tvStatusDisplay = findViewById(R.id.tvStatusDisplay);
        dbHelper = new DatabaseHelper(this);
        String[] halls = {
                "Main Auditorium (Cap: 800)",
                "Chavara Hall (Cap: 300)",
                "Conference Hall A (Cap: 100)",
                "Seminar Hall B (Cap: 150)"
        };
        ArrayAdapter<String> hallAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, halls);
        spinnerHall.setAdapter(hallAdapter);
        String[] slots = {
                "Morning (09:00 AM - 01:00 PM)",
                "Afternoon (01:30 PM - 05:30 PM)",
                "Full Day (09:00 AM - 05:00 PM)"
        };
        ArrayAdapter<String> slotAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, slots);
        spinnerSlot.setAdapter(slotAdapter);
        etSelectedDate.setOnClickListener(v -> showDatePicker());
        btnBookHall.setOnClickListener(v -> bookHallSlot());
        btnViewBookings.setOnClickListener(v -> viewAllBookings());
    }
    private void showDatePicker() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(this, (view, y, m, d) -> {
            String date = String.format("%02d/%02d/%04d", d, m + 1, y);
            etSelectedDate.setText(date);
        }, year, month, day);
        dialog.show();
    }
    private void bookHallSlot() {
        String name = etApplicantName.getText().toString().trim();
        String dept = etDepartment.getText().toString().trim();
        String contact = etContactNumber.getText().toString().trim();
        String date = etSelectedDate.getText().toString().trim();
        String hall = spinnerHall.getSelectedItem().toString();
        String slot = spinnerSlot.getSelectedItem().toString();
        if (name.isEmpty() || dept.isEmpty() || contact.isEmpty() || date.isEmpty()) {
            Toast.makeText(this, "Please fill all requisition fields", Toast.LENGTH_SHORT).show();
            return;
        }
        if (dbHelper.isSlotBooked(hall, date, slot)) {
            Toast.makeText(this, "Collision Detected! Slot already reserved.", Toast.LENGTH_LONG).show();
            return;
        }
        boolean success = dbHelper.insertBooking(name, dept, contact, hall, date, slot);
        if (success) {
            Toast.makeText(this, "Booking Requisition Submitted Successfully!", Toast.LENGTH_SHORT).show();
            tvStatusDisplay.setText("Last Request: " + hall + "\nDate: " + date + "\nSlot: " + slot + "\nStatus: Approved");
            etApplicantName.setText("");
            etDepartment.setText("");
            etContactNumber.setText("");
            etSelectedDate.setText("");
        } else {
            Toast.makeText(this, "Failed to submit booking", Toast.LENGTH_SHORT).show();
        }
    }
    private void viewAllBookings() {
        String records = dbHelper.getAllBookings();
        if (records.isEmpty()) {
            tvStatusDisplay.setText("No active venue bookings found.");
        } else {
            tvStatusDisplay.setText(records);
        }
    }
}
// ======================================================================================

// ======================================================================================
// File: DatabaseHelper.java
// ======================================================================================
package com.example.hallbookingsystem;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "HallBooking.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_BOOKINGS = "bookings";
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_BOOKINGS + " (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "applicant_name TEXT, " +
                "department TEXT, " +
                "contact_number TEXT, " +
                "hall_name TEXT, " +
                "booking_date TEXT, " +
                "time_slot TEXT)";
        db.execSQL(createTable);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKINGS);
        onCreate(db);
    }
    public boolean isSlotBooked(String hall, String date, String slot) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(
                "SELECT * FROM " + TABLE_BOOKINGS + " WHERE hall_name = ? AND booking_date = ? AND time_slot = ?",
                new String[]{hall, date, slot}
        );
        boolean booked = cursor.getCount() > 0;
        cursor.close();
        return booked;
    }
    public boolean insertBooking(String name, String dept, String contact, String hall, String date, String slot) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("applicant_name", name);
        values.put("department", dept);
        values.put("contact_number", contact);
        values.put("hall_name", hall);
        values.put("booking_date", date);
        values.put("time_slot", slot);
        long result = db.insert(TABLE_BOOKINGS, null, values);
        return result != -1;
    }
    public String getAllBookings() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_BOOKINGS + " ORDER BY id DESC", null);
        StringBuilder builder = new StringBuilder();
        while (cursor.moveToNext()) {
            builder.append("Booking ID: ").append(cursor.getInt(0)).append("\n")
                   .append("Applicant: ").append(cursor.getString(1)).append("\n")
                   .append("Dept: ").append(cursor.getString(2)).append("\n")
                   .append("Contact: ").append(cursor.getString(3)).append("\n")
                   .append("Hall: ").append(cursor.getString(4)).append("\n")
                   .append("Date: ").append(cursor.getString(5)).append("\n")
                   .append("Slot: ").append(cursor.getString(6)).append("\n")
                   .append("------------------------------------\n");
        }
        cursor.close();
        return builder.toString();
    }
}


====================================================================================================
# FILE 37/38: 37_HospitalManagement.txt
# TITLE: Hospital Management Multi-Activity Application (Patient Registration, Department Consultation, and Final Billing).
====================================================================================================

/*
========================================================================================
Filename: 37_HospitalManagement.txt
Program 37: Hospital Management Multi-Activity Application (Patient Registration, Department Consultation, and Final Billing)
Files Included: MainActivity.java, DepartmentActivity.java, FinalBillActivity.java, main_menu.xml
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Activity 1 (activity_main.xml):
     - 3 EditText (TextBox): etPatientId, etName, etAge
     - 1 RadioGroup (rgGender) with 2 RadioButtons: Male, Female
     - 4 CheckBox: cbBloodTest (₹200), cbXray (₹500), cbScan (₹1000), cbMedicine (₹300)
     - 1 Button: btnNext ('Next / Continue')
   Activity 2 (activity_department.xml):
     - 1 RadioGroup (rgDepartment) with RadioButtons (General Medicine, Cardiology, Orthopedics)
     - 1 Button: btnCalculate ('Calculate Charges')
   Activity 3 (activity_final_bill.xml):
     - TextView: tvBill (formatted itemized invoice)

2. Layout Configuration:
   - ScrollView / LinearLayout with vertical orientation

3. Menu Configuration:
   - Create res/menu/main_menu.xml with menuHome ('Home'), menuNewRegistration ('New Registration'), menuExit ('Exit').

4. Themes Configuration (res/values/themes.xml):
   - Theme with ActionBar (Theme.MaterialComponents.DayNight.DarkActionBar).

5. AndroidManifest.xml:
   Register DepartmentActivity and FinalBillActivity inside <application>:
   <activity android:name=".DepartmentActivity" android:exported="false" />
   <activity android:name=".FinalBillActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - Create DepartmentActivity.java and FinalBillActivity.java, receiving Intent extras and calculating grand total.
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.hospitalmanagement;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    EditText etPatientId, etName, etAge;
    RadioGroup rgGender;
    CheckBox cbBloodTest, cbXray, cbScan, cbMedicine;
    Button btnNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etPatientId = findViewById(R.id.etPatientId);
        etName = findViewById(R.id.etName);
        etAge = findViewById(R.id.etAge);
        rgGender = findViewById(R.id.rgGender);
        cbBloodTest = findViewById(R.id.cbBloodTest);
        cbXray = findViewById(R.id.cbXray);
        cbScan = findViewById(R.id.cbScan);
        cbMedicine = findViewById(R.id.cbMedicine);
        btnNext = findViewById(R.id.btnNext);
        btnNext.setOnClickListener(v -> validateAndNext());
    }
    private void validateAndNext() {
        String patientId = etPatientId.getText().toString().trim();
        String name = etName.getText().toString().trim();
        String age = etAge.getText().toString().trim();
        if (patientId.isEmpty()) {
            etPatientId.setError("Enter Patient ID");
            return;
        }
        if (name.isEmpty()) {
            etName.setError("Enter Patient Name");
            return;
        }
        if (age.isEmpty()) {
            etAge.setError("Enter Patient Age");
            return;
        }
        int genderId = rgGender.getCheckedRadioButtonId();
        if (genderId == -1) {
            Toast.makeText(this, "Select Gender", Toast.LENGTH_SHORT).show();
            return;
        }
        RadioButton genderButton = findViewById(genderId);
        String gender = genderButton.getText().toString();
        StringBuilder services = new StringBuilder();
        double serviceCharges = 0;
        if (cbBloodTest.isChecked()) {
            services.append("Blood Test\n");
            serviceCharges += 200;
        }
        if (cbXray.isChecked()) {
            services.append("X-Ray\n");
            serviceCharges += 500;
        }
        if (cbScan.isChecked()) {
            services.append("Scanning\n");
            serviceCharges += 1000;
        }
        if (cbMedicine.isChecked()) {
            services.append("Medicine\n");
            serviceCharges += 300;
        }
        if (services.length() == 0) {
            Toast.makeText(this,
                    "Select at least one medical service",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(MainActivity.this, DepartmentActivity.class);
        intent.putExtra("PATIENT_ID", patientId);
        intent.putExtra("NAME", name);
        intent.putExtra("AGE", age);
        intent.putExtra("GENDER", gender);
        intent.putExtra("SERVICES", services.toString());
        intent.putExtra("SERVICE_CHARGES", serviceCharges);
        startActivity(intent);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menuHome) {
            return true;
        }
        if (item.getItemId() == R.id.menuNewRegistration) {
            recreate();
            return true;
        }
        if (item.getItemId() == R.id.menuExit) {
            finishAffinity();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
// ======================================================================================

// ======================================================================================
// File: DepartmentActivity.java
// ======================================================================================
package com.example.hospitalmanagement;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class DepartmentActivity extends AppCompatActivity {
    TextView tvPatient;
    RadioGroup rgDepartment;
    Button btnCalculate;
    String patientId, name, age, gender, services;
    double serviceCharges;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_department);
        tvPatient = findViewById(R.id.tvPatient);
        rgDepartment = findViewById(R.id.rgDepartment);
        btnCalculate = findViewById(R.id.btnCalculate);
        Intent intent = getIntent();
        patientId = intent.getStringExtra("PATIENT_ID");
        name = intent.getStringExtra("NAME");
        age = intent.getStringExtra("AGE");
        gender = intent.getStringExtra("GENDER");
        services = intent.getStringExtra("SERVICES");
        serviceCharges = intent.getDoubleExtra("SERVICE_CHARGES", 0);
        tvPatient.setText("Patient: " + name + "\nID: " + patientId);
        btnCalculate.setOnClickListener(v -> calculateCharges());
    }

    private void calculateCharges() {
        int departmentId = rgDepartment.getCheckedRadioButtonId();
        if (departmentId == -1) {
            Toast.makeText(this,                    "Select Consultation Department",                    Toast.LENGTH_SHORT).show();
            return;
        }

        RadioButton departmentButton = findViewById(departmentId);
        String department = departmentButton.getText().toString();
        double consultationFee = 0;
        if (department.equals("General Medicine")) {
            consultationFee = 300;
        }

        else if (department.equals("Cardiology")) {
            consultationFee = 800;
        }

        else if (department.equals("Orthopedics")) {
            consultationFee = 600;
        }

        double totalCharges = serviceCharges + consultationFee;
        Intent intent = new Intent(                DepartmentActivity.this,                FinalBillActivity.class);
        intent.putExtra("PATIENT_ID", patientId);
        intent.putExtra("NAME", name);
        intent.putExtra("AGE", age);
        intent.putExtra("GENDER", gender);
        intent.putExtra("SERVICES", services);
        intent.putExtra("DEPARTMENT", department);
        intent.putExtra("CONSULTATION_FEE", consultationFee);
        intent.putExtra("SERVICE_CHARGES", serviceCharges);
        intent.putExtra("TOTAL_CHARGES", totalCharges);
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menuHome) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            return true;
        }

        if (item.getItemId() == R.id.menuNewRegistration) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            return true;
        }

        if (item.getItemId() == R.id.menuExit) {
            finishAffinity();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

// ======================================================================================
// File: FinalBillActivity.java
// ======================================================================================
package com.example.hospitalmanagement;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class FinalBillActivity extends AppCompatActivity {
    TextView tvBill;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_final_bill);
        tvBill = findViewById(R.id.tvBill);
        Intent intent = getIntent();
        String patientId = intent.getStringExtra("PATIENT_ID");
        String name = intent.getStringExtra("NAME");
        String age = intent.getStringExtra("AGE");
        String gender = intent.getStringExtra("GENDER");
        String services = intent.getStringExtra("SERVICES");
        String department = intent.getStringExtra("DEPARTMENT");
        double consultationFee =                intent.getDoubleExtra("CONSULTATION_FEE", 0);
        double serviceCharges =                intent.getDoubleExtra("SERVICE_CHARGES", 0);
        double totalCharges =                intent.getDoubleExtra("TOTAL_CHARGES", 0);
        String category;
        if (totalCharges >= 1500) {
            category = "Premium Treatment";
        }

        else if (totalCharges >= 800) {
            category = "Standard Treatment";
        }

        else {
            category = "Basic Treatment";
        }

        String bill =                "Patient ID: " + patientId +                        "\nName: " + name +                        "\nAge: " + age +                        "\nGender: " + gender +                        "\n\nDepartment: " + department +                        "\n\nMedical Services:\n" + services +                        "\nConsultation Fee: ₹" +                        String.format("%.2f", consultationFee) +                        "\nService Charges: ₹" +                        String.format("%.2f", serviceCharges) +                        "\n\nTotal Charges: ₹" +                        String.format("%.2f", totalCharges) +                        "\n\nTreatment Category: " + category;
        tvBill.setText(bill);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menuHome) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            return true;
        }

        if (item.getItemId() == R.id.menuNewRegistration) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            return true;
        }

        if (item.getItemId() == R.id.menuExit) {
            finishAffinity();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

// ======================================================================================
// File: res/menu/main_menu.xml
// ======================================================================================
<?xml version="1.0" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/menuHome" android:title="Home" app:showAsAction="never"/>
    <item android:id="@+id/menuNewRegistration" android:title="New Registration" app:showAsAction="never"/>
    <item android:id="@+id/menuExit" android:title="Exit" app:showAsAction="never"/>
</menu>


====================================================================================================
# FILE 38/38: 38_StudentDatabase_CRUD.txt
# TITLE: Student Database Management System (SQLite CRUD: Insert and View Records with Multi-Activity Navigation).
====================================================================================================

/*
========================================================================================
Filename: 38_StudentDatabase_CRUD.txt
Program 38: Student Database Management System (SQLite CRUD: Insert and View Records with Multi-Activity Navigation)
Files Included: MainActivity.java, DatabaseHelper.java, ViewDetailsActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   In activity_main.xml:
     - 2 EditText (TextBox):
       * etName: Hint: 'Student Name'
       * etAge: Hint: 'Age', inputType: 'number'
     - 2 Button:
       * btnAdd: Text: 'Add Student', onClick: 'addStudent'
       * btnView: Text: 'View Details', onClick: 'viewDetails'
     - 1 TextView: Heading 'Student Database'
   In activity_view_details.xml:
     - 2 TextView: Heading 'Student Details', tvDetails (displaying retrieved SQLite records)

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in res/values/themes.xml.

5. AndroidManifest.xml:
   Register ViewDetailsActivity inside <application>:
   <activity android:name=".ViewDetailsActivity" android:exported="false" />

6. Additional Files & Resources Required:
   - Create DatabaseHelper.java (extends SQLiteOpenHelper with table 'student': id, name, age) and ViewDetailsActivity.java (queries SQLite cursor and binds records to tvDetails).
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.studentdatabase;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    EditText etName, etAge;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etName = findViewById(R.id.etName);
        etAge = findViewById(R.id.etAge);
        db = new DatabaseHelper(this);
    }
    public void addStudent(View view) {
        String name = etName.getText().toString();
        String age = etAge.getText().toString();
        if (name.isEmpty() || age.isEmpty()) {
            Toast.makeText(this,
                    "Enter all details",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        boolean inserted = db.insertStudent(name, age);
        if (inserted) {
            Toast.makeText(this,
                    "Row Inserted Successfully",
                    Toast.LENGTH_SHORT).show();
            etName.setText("");
            etAge.setText("");
        }
    }
    public void viewDetails(View view) {
        startActivity(new Intent(this, ViewDetailsActivity.class));
    }
}
// ======================================================================================

// ======================================================================================
// File: DatabaseHelper.java
// ======================================================================================
package com.example.librarymanagement;

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

public class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
        super(context, "LibraryDB", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(                "CREATE TABLE book(" +                        "bookid TEXT PRIMARY KEY," +                        "bookname TEXT," +                        "author TEXT," +                        "publisher TEXT," +                        "year INTEGER," +                        "price REAL," +                        "stock INTEGER)"        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db,                          int oldVersion,                          int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS book");
        onCreate(db);
    }

    public boolean insertBook(            String id,            String name,            String author,            String publisher,            String year,            String price,            String stock) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("bookid", id);
        values.put("bookname", name);
        values.put("author", author);
        values.put("publisher", publisher);
        values.put("year", year);
        values.put("price", price);
        values.put("stock", stock);
        long result = db.insert(                "book",                null,                values        );
        return result != -1;
    }

    public Cursor getBooks() {
        SQLiteDatabase db = getReadableDatabase();
        return db.rawQuery(                "SELECT * FROM book",                null        );
    }
}

// ======================================================================================
// File: ViewDetailsActivity.java
// ======================================================================================
package com.example.librarymanagement;

import android.database.Cursor;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class ViewDetailsActivity extends AppCompatActivity {
    TextView tvDetails;
    DatabaseHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_details);
        tvDetails = findViewById(R.id.tvDetails);
        db = new DatabaseHelper(this);
        Cursor cursor = db.getBooks();
        StringBuilder data = new StringBuilder();
        while (cursor.moveToNext()) {
            data.append("Book ID : ")                    .append(cursor.getString(0))                    .append("\n");
            data.append("Book Name : ")                    .append(cursor.getString(1))                    .append("\n");
            data.append("Author : ")                    .append(cursor.getString(2))                    .append("\n");
            data.append("Publisher : ")                    .append(cursor.getString(3))                    .append("\n");
            data.append("Published Year : ")                    .append(cursor.getString(4))                    .append("\n");
            data.append("Price : ")                    .append(cursor.getString(5))                    .append("\n");
            data.append("Stock : ")                    .append(cursor.getString(6))                    .append("\n\n");
        }

        cursor.close();
        tvDetails.setText(data.toString());
    }
}

