Slips

Code













Create a Application which shows Life Cycle of Activity.

package com.example.lifecycledemo;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "LifecycleDemo";

    // onCreate() is called when the activity is first created
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate() called");
    }

    // onStart() is called when the activity becomes visible to the user
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart() called");
    }

    // onResume() is called when the activity starts interacting with the user
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume() called");
    }

    // onPause() is called when the system is about to start resuming another activity
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause() called");
    }

    // onStop() is called when the activity is no longer visible to the user
    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop() called");
    }

    // onRestart() is called when the activity is coming back to interact with the user
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart() called");
    }

    // onDestroy() is called before the activity is destroyed
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy() called");
    }
}


Create an Android Application to accept two numbers to calculate it’s Power and Average. Create two buttons: Power and Average. Display the appropriate result on the next activity on Button click.

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

    <EditText
        android:id="@+id/number1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter First Number"
        android:inputType="numberDecimal" />

    <EditText
        android:id="@+id/number2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Second Number"
        android:inputType="numberDecimal" />

    <Button
        android:id="@+id/powerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculate Power"
        android:layout_marginTop="20dp" />

    <Button
        android:id="@+id/averageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculate Average"
        android:layout_marginTop="20dp" />

</LinearLayout>

MainActivity.java
----------------------
package com.example.calculator;

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

public class MainActivity extends AppCompatActivity {

    EditText number1EditText, number2EditText;
    Button powerButton, averageButton;

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

        number1EditText = findViewById(R.id.number1);
        number2EditText = findViewById(R.id.number2);
        powerButton = findViewById(R.id.powerButton);
        averageButton = findViewById(R.id.averageButton);

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

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

    private void calculatePower() {
        try {
            double num1 = Double.parseDouble(number1EditText.getText().toString());
            double num2 = Double.parseDouble(number2EditText.getText().toString());

            double power = Math.pow(num1, num2);

            // Pass result to ResultActivity
            Intent intent = new Intent(MainActivity.this, ResultActivity.class);
            intent.putExtra("resultType", "Power");
            intent.putExtra("result", power);
            startActivity(intent);

        } catch (NumberFormatException e) {
            Toast.makeText(MainActivity.this, "Please enter valid numbers", Toast.LENGTH_SHORT).show();
        }
    }

    private void calculateAverage() {
        try {
            double num1 = Double.parseDouble(number1EditText.getText().toString());
            double num2 = Double.parseDouble(number2EditText.getText().toString());

            double average = (num1 + num2) / 2;

            // Pass result to ResultActivity
            Intent intent = new Intent(MainActivity.this, ResultActivity.class);
            intent.putExtra("resultType", "Average");
            intent.putExtra("result", average);
            startActivity(intent);

        } catch (NumberFormatException e) {
            Toast.makeText(MainActivity.this, "Please enter valid numbers", Toast.LENGTH_SHORT).show();
        }
    }
}

activity_result.xml
-----------------------

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

    <TextView
        android:id="@+id/resultTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result"
        android:textSize="24sp"
        android:layout_marginBottom="20dp"/>

    <TextView
        android:id="@+id/resultText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result will be displayed here"
        android:textSize="20sp" />

</LinearLayout>

ResultActivity.java
-----------------------
package com.example.calculator;

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

public class ResultActivity extends AppCompatActivity {

    TextView resultTitle, resultText;

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

        resultTitle = findViewById(R.id.resultTitle);
        resultText = findViewById(R.id.resultText);

        // Get the result and type from the Intent
        String resultType = getIntent().getStringExtra("resultType");
        double result = getIntent().getDoubleExtra("result", 0);

        resultTitle.setText(resultType);
        resultText.setText(String.valueOf(result));
    }
}

Create application using JSON to provide Employee Information.

Create a folder named assets inside the src/main directory, and add the employee.json file there.

assets/employee.json

[
    {
        "name": "John Doe",
        "position": "Software Engineer",
        "salary": "70000"
    },
    {
        "name": "Jane Smith",
        "position": "Product Manager",
        "salary": "80000"
    },
    {
        "name": "Emily Johnson",
        "position": "Designer",
        "salary": "60000"
    }
]

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

    <RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="16dp"/>

</LinearLayout>

item_employee.xml
-----------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="?android:attr/selectableItemBackground"
    android:layout_marginBottom="8dp">

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/position"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textColor="#757575" />

    <TextView
        android:id="@+id/salary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#4CAF50"
        android:layout_marginTop="8dp"/>
</LinearLayout>


Now we need to create the necessary Java classes to parse the JSON data and display it in the RecyclerView.

Employee.java
--------------
package com.example.employeeinfo;

public class Employee {
    private String name;
    private String position;
    private String salary;

    // Constructor
    public Employee(String name, String position, String salary) {
        this.name = name;
        this.position = position;
        this.salary = salary;
    }

    // Getters
    public String getName() {
        return name;
    }

    public String getPosition() {
        return position;
    }

    public String getSalary() {
        return salary;
    }
}

EmployeeAdapter.java
--------------------

package com.example.employeeinfo;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class EmployeeAdapter extends RecyclerView.Adapter<EmployeeAdapter.EmployeeViewHolder> {
    private List<Employee> employeeList;

    // Constructor
    public EmployeeAdapter(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }

    @Override
    public EmployeeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_employee, parent, false);
        return new EmployeeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(EmployeeViewHolder holder, int position) {
        Employee employee = employeeList.get(position);
        holder.nameTextView.setText(employee.getName());
        holder.positionTextView.setText(employee.getPosition());
        holder.salaryTextView.setText("Salary: $" + employee.getSalary());
    }

    @Override
    public int getItemCount() {
        return employeeList.size();
    }

    public static class EmployeeViewHolder extends RecyclerView.ViewHolder {
        TextView nameTextView, positionTextView, salaryTextView;

        public EmployeeViewHolder(View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.name);
            positionTextView = itemView.findViewById(R.id.position);
            salaryTextView = itemView.findViewById(R.id.salary);
        }
    }
}

MainActivity.java
-----------------

package com.example.employeeinfo;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EmployeeAdapter adapter;
    private List<Employee> employeeList;

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

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // Load employee data from JSON file
        loadEmployeeData();
    }

    private void loadEmployeeData() {
        try {
            // Load the JSON data from the assets folder
            AssetManager assetManager = getAssets();
            BufferedReader reader = new BufferedReader(new InputStreamReader(assetManager.open("employee.json")));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String jsonData = stringBuilder.toString();

            // Parse the JSON data using Gson
            Gson gson = new Gson();
            Type employeeListType = new TypeToken<List<Employee>>() {}.getType();
            employeeList = gson.fromJson(jsonData, employeeListType);

            // Set up RecyclerView with parsed data
            adapter = new EmployeeAdapter(employeeList);
            recyclerView.setAdapter(adapter);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Error loading employee data", Toast.LENGTH_SHORT).show();
        }
    }
}

Construct an Android application to accept a number and calculate Armstrong and Perfect
number of a given number.
activity_main.xml
----------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center">

    <EditText
        android:id="@+id/numberInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter a number"
        android:inputType="number"
        android:layout_marginBottom="20dp" />

    <Button
        android:id="@+id/armstrongButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check Armstrong Number"
        android:layout_marginBottom="10dp"/>

    <Button
        android:id="@+id/perfectButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check Perfect Number"
        android:layout_marginBottom="20dp"/>

    <TextView
        android:id="@+id/resultText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="18sp"
        android:textColor="#FF0000"/>
</LinearLayout>

MainActivity.java
----------------------
package com.example.numbercheck;

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    EditText numberInput;
    Button armstrongButton, perfectButton;
    TextView resultText;

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

        // Initialize views
        numberInput = findViewById(R.id.numberInput);
        armstrongButton = findViewById(R.id.armstrongButton);
        perfectButton = findViewById(R.id.perfectButton);
        resultText = findViewById(R.id.resultText);

        // Set listeners for buttons
        armstrongButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkArmstrongNumber();
            }
        });

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

    // Method to check if the number is Armstrong
    private void checkArmstrongNumber() {
        String input = numberInput.getText().toString();

        if (input.isEmpty()) {
            Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show();
            return;
        }

        int number = Integer.parseInt(input);
        int originalNumber = number;
        int sum = 0;
        int digits = String.valueOf(number).length();

        while (number > 0) {
            int remainder = number % 10;
            sum += Math.pow(remainder, digits);  // Raise each digit to the power of number of digits
            number /= 10;
        }

        if (sum == originalNumber) {
            resultText.setText(originalNumber + " is an Armstrong Number.");
        } else {
            resultText.setText(originalNumber + " is not an Armstrong Number.");
        }
    }

    // Method to check if the number is Perfect
    private void checkPerfectNumber() {
        String input = numberInput.getText().toString();

        if (input.isEmpty()) {
            Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show();
            return;
        }

        int number = Integer.parseInt(input);
        int sum = 0;

        // Find the divisors of the number
        for (int i = 1; i <= number / 2; i++) {
            if (number % i == 0) {
                sum += i;
            }
        }

        if (sum == number) {
            resultText.setText(number + " is a Perfect Number.");
        } else {
            resultText.setText(number + " is not a Perfect Number.");
        }
    }
}

Write a Java Android Program to Demonstrate List View Activity with all operations
Such as: Insert, Delete, Search

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

    <!-- EditText to input item to be added -->
    <EditText
        android:id="@+id/editTextItem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter item to add"
        android:inputType="text" />

    <!-- Button to Insert item -->
    <Button
        android:id="@+id/btnInsert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Insert Item"
        android:layout_marginTop="10dp" />

    <!-- EditText to search the ListView items -->
    <EditText
        android:id="@+id/editTextSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Search items"
        android:layout_marginTop="20dp" />

    <!-- ListView to show items -->
    <ListView
        android:id="@+id/listViewItems"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_marginTop="20dp"/>

</LinearLayout>

MainActivity.java
----------------------
package com.example.listviewoperations;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.Filter;
import android.widget.Filterable;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    // Declare UI elements
    EditText editTextItem, editTextSearch;
    Button btnInsert;
    ListView listViewItems;

    // Declare ArrayList to store the list items
    ArrayList<String> itemList;
    ArrayAdapter<String> adapter;

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

        // Initialize the UI elements
        editTextItem = findViewById(R.id.editTextItem);
        editTextSearch = findViewById(R.id.editTextSearch);
        btnInsert = findViewById(R.id.btnInsert);
        listViewItems = findViewById(R.id.listViewItems);

        // Initialize the ArrayList and Adapter
        itemList = new ArrayList<>();
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, itemList);

        // Set the adapter for the ListView
        listViewItems.setAdapter(adapter);

        // Insert item when Insert button is clicked
        btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String item = editTextItem.getText().toString();
                if (!item.isEmpty()) {
                    itemList.add(item); // Add item to list
                    adapter.notifyDataSetChanged(); // Refresh the ListView
                    editTextItem.setText(""); // Clear the input field
                    Toast.makeText(MainActivity.this, "Item Added", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Please enter an item", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Set an item click listener to delete an item when clicked
        listViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String item = itemList.get(position);
                itemList.remove(position); // Remove item from list
                adapter.notifyDataSetChanged(); // Refresh the ListView
                Toast.makeText(MainActivity.this, item + " Deleted", Toast.LENGTH_SHORT).show();
            }
        });

        // Implement search functionality
        editTextSearch.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                // Filter the list as the user types in the search box
                adapter.getFilter().filter(charSequence);
            }

            @Override
            public void afterTextChanged(android.text.Editable editable) {}
        });
    }
}

Create an application to demonstrate login form with validation.
LoginActivity.java
------------------
package com.example.loginvalidation;

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

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    EditText editTextUsername, editTextPassword;
    Button buttonLogin;
    TextView textViewError;

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

        // Initialize the views
        editTextUsername = findViewById(R.id.editTextUsername);
        editTextPassword = findViewById(R.id.editTextPassword);
        buttonLogin = findViewById(R.id.buttonLogin);
        textViewError = findViewById(R.id.textViewError);

        // Set the login button's onClickListener
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Validate login
                validateLogin();
            }
        });
    }

    private void validateLogin() {
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        // Simple validation: Check if fields are empty
        if (username.isEmpty() || password.isEmpty()) {
            textViewError.setText("Please enter both username and password.");
        } 
        // Hardcoded correct credentials (just for simplicity)
        else if (username.equals("user") && password.equals("12345")) {
            // If login is successful, show a Toast message (or you can navigate to a new activity)
            Toast.makeText(LoginActivity.this, "Login Successful! Welcome " + username, Toast.LENGTH_SHORT).show();
        } else {
            // Invalid credentials
            textViewError.setText("Invalid username or password.");
        }
    }
}

activity_login.xml
------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="32dp"
    android:gravity="center">

    <!-- EditText for Username -->
    <EditText
        android:id="@+id/editTextUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Username"
        android:inputType="text"/>

    <!-- EditText for Password -->
    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword"
        android:layout_marginTop="16dp"/>

    <!-- Button for Login -->
    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:layout_marginTop="32dp"/>

    <!-- TextView to display error messages -->
    <TextView
        android:id="@+id/textViewError"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FF0000"
        android:layout_marginTop="16dp"/>

</LinearLayout>

AndroidManifest.xml
-------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.loginvalidation">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Login Validation"
        android:theme="@style/Theme.AppCompat.Light">

        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>


Write a Java Android Program to Demonstrate List View Activity with all operations
Such as: Insert, Delete, Search
activity_main.xml
----------------------

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

    <!-- EditText for user input -->
    <EditText
        android:id="@+id/editTextMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter greet message" />

    <!-- Button to send message to the second activity -->
    <Button
        android:id="@+id/buttonSendMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Message" />

</LinearLayout>


MainActivity.java
-----------------
package com.example.greetmessageapp;

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

public class MainActivity extends AppCompatActivity {

    private EditText editTextMessage;
    private Button buttonSendMessage;

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

        editTextMessage = findViewById(R.id.editTextMessage);
        buttonSendMessage = findViewById(R.id.buttonSendMessage);

        // Set OnClickListener to the button
        buttonSendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get the message entered by the user
                String greetMessage = editTextMessage.getText().toString();

                // Create an intent to start the second activity
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);

                // Pass the greet message to the second activity
                intent.putExtra("GREET_MESSAGE", greetMessage);

                // Start the second activity
                startActivity(intent);
            }
        });
    }
}

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

    <!-- TextView to display the greet message -->
    <TextView
        android:id="@+id/textViewGreetMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Greet message will be displayed here"
        android:textSize="18sp" />

</LinearLayout>

SecondActivity.java
--------------------
package com.example.greetmessageapp;

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

public class SecondActivity extends AppCompatActivity {

    private TextView textViewGreetMessage;

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

        textViewGreetMessage = findViewById(R.id.textViewGreetMessage);

        // Get the greet message from the Intent
        Intent intent = getIntent();
        String greetMessage = intent.getStringExtra("GREET_MESSAGE");

        // Display the greet message
        textViewGreetMessage.setText(greetMessage);
    }
}

AndroidManifest.xml
-------------------
<application
    ... >
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".SecondActivity" />
</application>


Create an application to change Font Size, Color and Font Family of String.
activity_main.xml
------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <!-- TextView to display the string -->
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change My Style"
        android:textSize="18sp"
        android:layout_gravity="center"
        android:padding="20dp"
        android:textColor="#000000"/>

    <!-- Button to change font size -->
    <Button
        android:id="@+id/btnChangeSize"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Font Size"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"/>

    <!-- Button to change text color -->
    <Button
        android:id="@+id/btnChangeColor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Text Color"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"/>

    <!-- Button to change font family -->
    <Button
        android:id="@+id/btnChangeFamily"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Font Family"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"/>

</LinearLayout>

MainActivity.java
------------------
package com.example.fontchanger;

import android.graphics.Color;
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 {

    private TextView textView;
    private Button btnChangeSize, btnChangeColor, btnChangeFamily;

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

        // Initialize the views
        textView = findViewById(R.id.textView);
        btnChangeSize = findViewById(R.id.btnChangeSize);
        btnChangeColor = findViewById(R.id.btnChangeColor);
        btnChangeFamily = findViewById(R.id.btnChangeFamily);

        // Change Font Size on Button Click
        btnChangeSize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setTextSize(30);  // Change text size to 30sp
            }
        });

        // Change Text Color on Button Click
        btnChangeColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setTextColor(Color.RED);  // Change text color to red
            }
        });

        // Change Font Family on Button Click
        btnChangeFamily.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setTypeface(getResources().getFont(R.font.roboto_regular));  // Change to Roboto font family
            }
        });
    }
}

AndroidManifest.xml
-------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fontchanger">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Font Changer"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.FontChanger">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Create an application for registration form given below. Also perform appropriate validation.
activity_main.xml
-----------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center">

    <!-- Name Field -->
    <EditText
        android:id="@+id/edtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Name"
        android:inputType="textPersonName"/>

    <!-- Email Field -->
    <EditText
        android:id="@+id/edtEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Email"
        android:inputType="textEmailAddress"
        android:layout_marginTop="10dp"/>

    <!-- Password Field -->
    <EditText
        android:id="@+id/edtPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Password"
        android:inputType="textPassword"
        android:layout_marginTop="10dp"/>

    <!-- Age Field -->
    <EditText
        android:id="@+id/edtAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Age"
        android:inputType="number"
        android:layout_marginTop="10dp"/>

    <!-- Mobile Number Field -->
    <EditText
        android:id="@+id/edtMobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Mobile Number"
        android:inputType="phone"
        android:layout_marginTop="10dp"/>

    <!-- Register Button -->
    <Button
        android:id="@+id/btnRegister"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:layout_marginTop="20dp"/>
    
</LinearLayout>

MainActivity.java
-----------------
package com.example.registrationform;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText edtName, edtEmail, edtPassword, edtAge, edtMobile;
    private Button btnRegister;

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

        // Initialize views
        edtName = findViewById(R.id.edtName);
        edtEmail = findViewById(R.id.edtEmail);
        edtPassword = findViewById(R.id.edtPassword);
        edtAge = findViewById(R.id.edtAge);
        edtMobile = findViewById(R.id.edtMobile);
        btnRegister = findViewById(R.id.btnRegister);

        // Register button click listener
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Validate form fields
                if (validateForm()) {
                    // If valid, show a success message
                    Toast.makeText(MainActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private boolean validateForm() {
        // Get user input values
        String name = edtName.getText().toString().trim();
        String email = edtEmail.getText().toString().trim();
        String password = edtPassword.getText().toString().trim();
        String ageString = edtAge.getText().toString().trim();
        String mobile = edtMobile.getText().toString().trim();

        // Validate Name
        if (TextUtils.isEmpty(name)) {
            edtName.setError("Name is required");
            edtName.requestFocus();
            return false;
        }

        // Validate Email
        if (TextUtils.isEmpty(email) || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            edtEmail.setError("Enter a valid email address");
            edtEmail.requestFocus();
            return false;
        }

        // Validate Password
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            edtPassword.setError("Password must be at least 6 characters");
            edtPassword.requestFocus();
            return false;
        }

        // Validate Age (Should be a valid number)
        if (TextUtils.isEmpty(ageString)) {
            edtAge.setError("Age is required");
            edtAge.requestFocus();
            return false;
        } else {
            try {
                int age = Integer.parseInt(ageString);
                if (age < 18) {
                    edtAge.setError("You must be at least 18 years old");
                    edtAge.requestFocus();
                    return false;
                }
            } catch (NumberFormatException e) {
                edtAge.setError("Invalid age format");
                edtAge.requestFocus();
                return false;
            }
        }

        // Validate Mobile Number
        if (TextUtils.isEmpty(mobile) || mobile.length() != 10) {
            edtMobile.setError("Enter a valid 10-digit mobile number");
            edtMobile.requestFocus();
            return false;
        }

        return true;  // If all validations pass
    }
}

AndroidManifest.xml
-------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.registrationform">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Registration Form"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.RegistrationForm">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>


Create an application that Demonstrates List View and Onclick of List Display with Toast
Message.

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

    <!-- Registration Form Section -->
    <EditText
        android:id="@+id/edtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Name"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/edtEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Email"
        android:inputType="textEmailAddress"
        android:layout_marginTop="10dp" />

    <EditText
        android:id="@+id/edtPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Password"
        android:inputType="textPassword"
        android:layout_marginTop="10dp" />

    <EditText
        android:id="@+id/edtAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Age"
        android:inputType="number"
        android:layout_marginTop="10dp" />

    <EditText
        android:id="@+id/edtMobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Mobile Number"
        android:inputType="phone"
        android:layout_marginTop="10dp" />

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:layout_marginTop="20dp" />

    <!-- ListView Section -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click on List Item Below"
        android:textSize="18sp"
        android:layout_marginTop="30dp" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />

</LinearLayout>

MainActivity.java
-----------------
package com.example.registrationlistview;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText edtName, edtEmail, edtPassword, edtAge, edtMobile;
    private Button btnRegister;
    private ListView listView;

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

        // Initialize views
        edtName = findViewById(R.id.edtName);
        edtEmail = findViewById(R.id.edtEmail);
        edtPassword = findViewById(R.id.edtPassword);
        edtAge = findViewById(R.id.edtAge);
        edtMobile = findViewById(R.id.edtMobile);
        btnRegister = findViewById(R.id.btnRegister);
        listView = findViewById(R.id.listView);

        // Set up ListView with some items
        String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
        listView.setAdapter(adapter);

        // Set up ListView item click listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Show a Toast with the item clicked
                String item = (String) parent.getItemAtPosition(position);
                Toast.makeText(MainActivity.this, "You clicked: " + item, Toast.LENGTH_SHORT).show();
            }
        });

        // Register button click listener
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Validate the form and show success or error messages
                if (validateForm()) {
                    Toast.makeText(MainActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private boolean validateForm() {
        // Get user input values
        String name = edtName.getText().toString().trim();
        String email = edtEmail.getText().toString().trim();
        String password = edtPassword.getText().toString().trim();
        String ageString = edtAge.getText().toString().trim();
        String mobile = edtMobile.getText().toString().trim();

        // Validate Name
        if (TextUtils.isEmpty(name)) {
            edtName.setError("Name is required");
            edtName.requestFocus();
            return false;
        }

        // Validate Email
        if (TextUtils.isEmpty(email) || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            edtEmail.setError("Enter a valid email address");
            edtEmail.requestFocus();
            return false;
        }

        // Validate Password
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            edtPassword.setError("Password must be at least 6 characters");
            edtPassword.requestFocus();
            return false;
        }

        // Validate Age (Should be a valid number)
        if (TextUtils.isEmpty(ageString)) {
            edtAge.setError("Age is required");
            edtAge.requestFocus();
            return false;
        } else {
            try {
                int age = Integer.parseInt(ageString);
                if (age < 18) {
                    edtAge.setError("You must be at least 18 years old");
                    edtAge.requestFocus();
                    return false;
                }
            } catch (NumberFormatException e) {
                edtAge.setError("Invalid age format");
                edtAge.requestFocus();
                return false;
            }
        }

        // Validate Mobile Number
        if (TextUtils.isEmpty(mobile) || mobile.length() != 10) {
            edtMobile.setError("Enter a valid 10-digit mobile number");
            edtMobile.requestFocus();
            return false;
        }

        return true;  // If all validations pass
    }
}

AndroidManifest.xml
-------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.registrationlistview">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Registration and ListView"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.RegistrationListView">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>


Design an application for login activity. Write android code to check login credentials with username = "mca" and password = "android". Display appropriate toast message to the user.

activity_login.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <!-- Username Input Field --> <EditText android:id="@+id/edtUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Username" android:inputType="textPersonName" /> <!-- Password Input Field --> <EditText android:id="@+id/edtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Password" android:inputType="textPassword" android:layout_marginTop="10dp" /> <!-- Login Button --> <Button android:id="@+id/btnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login" android:layout_marginTop="20dp" /> </LinearLayout>
LoginActivity.java
------------------
package com.example.loginapp; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class LoginActivity extends AppCompatActivity { // Predefined username and password private static final String USERNAME = "mca"; private static final String PASSWORD = "android"; private EditText edtUsername, edtPassword; private Button btnLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Initialize the views edtUsername = findViewById(R.id.edtUsername); edtPassword = findViewById(R.id.edtPassword); btnLogin = findViewById(R.id.btnLogin); // Set up the login button click listener btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Get the username and password entered by the user String username = edtUsername.getText().toString().trim(); String password = edtPassword.getText().toString().trim(); // Check if the entered credentials match the predefined ones if (username.equals(USERNAME) && password.equals(PASSWORD)) { // Display a success message Toast.makeText(LoginActivity.this, "Login Successful!", Toast.LENGTH_SHORT).show(); } else { // Display an error message Toast.makeText(LoginActivity.this, "Invalid Username or Password", Toast.LENGTH_SHORT).show(); } } }); } }

AndroidManifest.xml:

--------------------

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.loginapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Login App" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.LoginApp"> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>


Create the simple calculator shown below also perform appropriate operation.
activity_main.xml
-----------------
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <!-- Display Result --> <EditText android:id="@+id/edtResult" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="none" android:textSize="30sp" android:gravity="end" android:focusable="false" android:layout_marginBottom="20dp" android:background="@android:drawable/edit_text" android:text="0" /> <!-- Calculator Buttons (Numbers + Operations) --> <GridLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:columnCount="4" android:orientation="horizontal"> <!-- Row 1 --> <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:textSize="20sp" /> <Button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2" android:textSize="20sp" /> <Button android:id="@+id/btn3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="3" android:textSize="20sp" /> <Button android:id="@+id/btnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:textSize="20sp" /> <!-- Row 2 --> <Button android:id="@+id/btn4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="4" android:textSize="20sp" /> <Button android:id="@+id/btn5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="5" android:textSize="20sp" /> <Button android:id="@+id/btn6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="6" android:textSize="20sp" /> <Button android:id="@+id/btnSub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-" android:textSize="20sp" /> <!-- Row 3 --> <Button android:id="@+id/btn7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="7" android:textSize="20sp" /> <Button android:id="@+id/btn8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="8" android:textSize="20sp" /> <Button android:id="@+id/btn9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="9" android:textSize="20sp" /> <Button android:id="@+id/btnMul" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="*" android:textSize="20sp" /> <!-- Row 4 --> <Button android:id="@+id/btn0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" android:textSize="20sp" /> <Button android:id="@+id/btnClear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C" android:textSize="20sp" /> <Button android:id="@+id/btnEqual" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="=" android:textSize="20sp" /> <Button android:id="@+id/btnDiv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="/" android:textSize="20sp" /> </GridLayout> </LinearLayout>

MainActivity.java
------------------
package com.example.simplecalculator; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private EditText edtResult; private String currentInput = ""; private String operator = ""; private double firstOperand = 0; private double secondOperand = 0; private boolean isOperatorClicked = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the EditText and Buttons edtResult = findViewById(R.id.edtResult); Button btn1 = findViewById(R.id.btn1); Button btn2 = findViewById(R.id.btn2); Button btn3 = findViewById(R.id.btn3); Button btn4 = findViewById(R.id.btn4); Button btn5 = findViewById(R.id.btn5); Button btn6 = findViewById(R.id.btn6); Button btn7 = findViewById(R.id.btn7); Button btn8 = findViewById(R.id.btn8); Button btn9 = findViewById(R.id.btn9); Button btn0 = findViewById(R.id.btn0); Button btnAdd = findViewById(R.id.btnAdd); Button btnSub = findViewById(R.id.btnSub); Button btnMul = findViewById(R.id.btnMul); Button btnDiv = findViewById(R.id.btnDiv); Button btnClear = findViewById(R.id.btnClear); Button btnEqual = findViewById(R.id.btnEqual); // Set OnClickListeners for the number buttons btn1.setOnClickListener(v -> appendToInput("1")); btn2.setOnClickListener(v -> appendToInput("2")); btn3.setOnClickListener(v -> appendToInput("3")); btn4.setOnClickListener(v -> appendToInput("4")); btn5.setOnClickListener(v -> appendToInput("5")); btn6.setOnClickListener(v -> appendToInput("6")); btn7.setOnClickListener(v -> appendToInput("7")); btn8.setOnClickListener(v -> appendToInput("8")); btn9.setOnClickListener(v -> appendToInput("9")); btn0.setOnClickListener(v -> appendToInput("0")); // Set OnClickListeners for operator buttons btnAdd.setOnClickListener(v -> handleOperator("+")); btnSub.setOnClickListener(v -> handleOperator("-")); btnMul.setOnClickListener(v -> handleOperator("*")); btnDiv.setOnClickListener(v -> handleOperator("/")); // Set OnClickListener for the clear button btnClear.setOnClickListener(v -> clearInput()); // Set OnClickListener for the equal button to perform calculation btnEqual.setOnClickListener(v -> calculateResult()); } // Method to append numbers to the input private void appendToInput(String value) { currentInput += value; edtResult.setText(currentInput); } // Method to handle operator buttons (+, -, *, /) private void handleOperator(String operator) { if (currentInput.isEmpty()) return; this.operator = operator; firstOperand = Double.parseDouble(currentInput); currentInput = ""; edtResult.setText(""); } // Method to clear the input private void clearInput() { currentInput = ""; edtResult.setText(""); operator = ""; firstOperand = 0; secondOperand = 0; } // Method to calculate the result private void calculateResult() { if (currentInput.isEmpty()) return; secondOperand = Double.parseDouble(currentInput); double result = 0; switch (operator) { case "+": result = firstOperand + secondOperand; break; case "-": result = firstOperand - secondOperand; break; case "*": result = firstOperand * secondOperand; break; case "/": if (secondOperand == 0) { Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_SHORT).show(); return; } result = firstOperand / secondOperand; break; default: return; } // Display the result in the EditText edtResult.setText(String.valueOf(result)); currentInput = String.valueOf(result); // Allow for continuing operations with the result operator = ""; } }

Create an Android Application to find the factorial of a number and Display the Result on alert

activity_main.xml
-----------------
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <!-- Input field for number --> <EditText android:id="@+id/edtNumber" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter a number" android:inputType="number" android:textSize="18sp" android:layout_marginBottom="20dp"/> <!-- Button to calculate factorial --> <Button android:id="@+id/btnCalculate" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Calculate Factorial" android:textSize="18sp" /> </LinearLayout>

MainActivity.java
-----------------
package com.example.factorialapp; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private EditText edtNumber; private Button btnCalculate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the views edtNumber = findViewById(R.id.edtNumber); btnCalculate = findViewById(R.id.btnCalculate); // Set up the button click listener btnCalculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Get the number from the EditText String input = edtNumber.getText().toString(); // Check if the input is empty if (input.isEmpty()) { Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show(); return; } try { // Parse the input number int number = Integer.parseInt(input); // Check if the number is negative if (number < 0) { Toast.makeText(MainActivity.this, "Please enter a non-negative number", Toast.LENGTH_SHORT).show(); return; } // Calculate the factorial long factorial = calculateFactorial(number); // Display the result in an AlertDialog showResult(factorial); } catch (NumberFormatException e) { Toast.makeText(MainActivity.this, "Invalid input. Please enter a valid number", Toast.LENGTH_SHORT).show(); } } }); } // Method to calculate the factorial of a number private long calculateFactorial(int number) { long result = 1; for (int i = 1; i <= number; i++) { result *= i; } return result; } // Method to show the result in an AlertDialog private void showResult(long factorial) { // Create an AlertDialog to display the factorial AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Factorial Result") .setMessage("The factorial is: " + factorial) .setPositiveButton("OK", null) .show(); } }

AndroidManifest.xml
-------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.factorialapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Factorial App" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.FactorialApp"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Create an application that allows the user to enter a number in the textbox. Check whether the number in the textbox is Armstrong or not. Print the message accordingly in the label control.

activity_main.xml
-----------------
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <!-- Input field for number --> <EditText android:id="@+id/edtNumber" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter a number" android:inputType="number" android:textSize="18sp" android:layout_marginBottom="20dp"/> <!-- Button to check Armstrong number --> <Button android:id="@+id/btnCheck" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Check Armstrong" android:textSize="18sp" /> <!-- TextView to display result --> <TextView android:id="@+id/tvResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Result will appear here" android:textSize="18sp" android:layout_marginTop="20dp" android:textColor="#000000"/> </LinearLayout>


MainActivity.java
-----------------
package com.example.armstrongnumber; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private EditText edtNumber; private Button btnCheck; private TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the views edtNumber = findViewById(R.id.edtNumber); btnCheck = findViewById(R.id.btnCheck); tvResult = findViewById(R.id.tvResult); // Set the click listener for the button btnCheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Get the number from the EditText String input = edtNumber.getText().toString(); // Check if the input is empty if (input.isEmpty()) { Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show(); return; } try { // Parse the number from the input int number = Integer.parseInt(input); // Check if the number is an Armstrong number if (isArmstrong(number)) { tvResult.setText(number + " is an Armstrong number."); } else { tvResult.setText(number + " is NOT an Armstrong number."); } } catch (NumberFormatException e) { Toast.makeText(MainActivity.this, "Invalid input. Please enter a valid number.", Toast.LENGTH_SHORT).show(); } } }); } // Method to check if a number is an Armstrong number private boolean isArmstrong(int number) { int sum = 0; int originalNumber = number; int digits = String.valueOf(number).length(); // Calculate the sum of the digits raised to the power of the number of digits while (number != 0) { int digit = number % 10; sum += Math.pow(digit, digits); number /= 10; } // Return true if the sum equals the original number return sum == originalNumber; } }

AndroidManifest.xml:

-------------------

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.armstrongnumber"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Armstrong Number Checker" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Create an application that demonstrate Options Menu, Context Menu and Popup Menu in android.

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <!-- TextView to display selected menu item --> <TextView android:id="@+id/tvSelectedOption" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select a menu option" android:textSize="18sp" android:textColor="#000000" android:layout_marginBottom="20dp"/> <!-- Button to show options menu --> <Button android:id="@+id/btnOptionsMenu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Options Menu" android:textSize="16sp"/> <!-- Button to show context menu --> <Button android:id="@+id/btnContextMenu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Context Menu" android:textSize="16sp" android:layout_marginTop="20dp"/> <!-- Button to show popup menu --> <Button android:id="@+id/btnPopupMenu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Popup Menu" android:textSize="16sp" android:layout_marginTop="20dp"/> </LinearLayout>

MainActivity.java
------------------
package com.example.menudemo; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.view.menu.MenuBuilder; import androidx.appcompat.widget.PopupMenu; public class MainActivity extends AppCompatActivity { private TextView tvSelectedOption; private Button btnOptionsMenu, btnContextMenu, btnPopupMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvSelectedOption = findViewById(R.id.tvSelectedOption); btnOptionsMenu = findViewById(R.id.btnOptionsMenu); btnContextMenu = findViewById(R.id.btnContextMenu); btnPopupMenu = findViewById(R.id.btnPopupMenu); // Button to show Options Menu btnOptionsMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openOptionsMenu(); } }); // Button to show Context Menu btnContextMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registerForContextMenu(v); // Register the view for context menu openContextMenu(v); // Open the context menu for the view } }); // Button to show Popup Menu btnPopupMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopupMenu(v); } }); } // Options Menu @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu (options menu) getMenuInflater().inflate(R.menu.menu_options, menu); return true; } // Handle item selection from Options Menu @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_1: tvSelectedOption.setText("Option 1 selected from Options Menu"); return true; case R.id.menu_item_2: tvSelectedOption.setText("Option 2 selected from Options Menu"); return true; case R.id.menu_item_3: tvSelectedOption.setText("Option 3 selected from Options Menu"); return true; default: return super.onOptionsItemSelected(item); } } // Context Menu @Override public void onCreateContextMenu(android.view.ContextMenu menu, View v, android.view.ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // Inflate the context menu getMenuInflater().inflate(R.menu.menu_context, menu); } // Handle item selection from Context Menu @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.context_item_1: tvSelectedOption.setText("Option 1 selected from Context Menu"); return true; case R.id.context_item_2: tvSelectedOption.setText("Option 2 selected from Context Menu"); return true; case R.id.context_item_3: tvSelectedOption.setText("Option 3 selected from Context Menu"); return true; default: return super.onContextItemSelected(item); } } // Popup Menu private void showPopupMenu(View view) { PopupMenu popupMenu = new PopupMenu(MainActivity.this, view); getMenuInflater().inflate(R.menu.menu_popup, popupMenu.getMenu()); // Set the listener for PopupMenu items popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.popup_item_1: tvSelectedOption.setText("Option 1 selected from Popup Menu"); return true; case R.id.popup_item_2: tvSelectedOption.setText("Option 2 selected from Popup Menu"); return true; case R.id.popup_item_3: tvSelectedOption.setText("Option 3 selected from Popup Menu"); return true; default: return false; } } }); popupMenu.show(); } }

menu_options.xml (for Options Menu)

-----------------------------------

Create this file in the res/menu/ folder.

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_item_1" android:title="Option 1"/> <item android:id="@+id/menu_item_2" android:title="Option 2"/> <item android:id="@+id/menu_item_3" android:title="Option 3"/> </menu>

menu_context.xml (for Context Menu)

Create this file in the res/menu/ folder.

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/context_item_1" android:title="Context Option 1"/> <item android:id="@+id/context_item_2" android:title="Context Option 2"/> <item android:id="@+id/context_item_3" android:title="Context Option 3"/> </menu>

menu_popup.xml (for Popup Menu)

Create this file in the res/menu/ folder.

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/popup_item_1" android:title="Popup Option 1"/> <item android:id="@+id/popup_item_2" android:title="Popup Option 2"/> <item android:id="@+id/popup_item_3" android:title="Popup Option 3"/> </menu>

AndroidManifest.xml

------------------

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.menudemo"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Menu Demo" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Create the following Vertical Scroll View Creation in Android.
activity_main.xml
-----------------
<?xml version="1.0" encoding="utf-8"?> <androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <!-- LinearLayout to contain the buttons --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <!-- Button 1 --> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 1" /> <!-- Button 2 --> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 2" /> <!-- Button 3 --> <Button android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 3" /> <!-- Button 4 --> <Button android:id="@+id/button4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 4" /> <!-- Button 5 --> <Button android:id="@+id/button5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 5" /> <!-- Button 6 --> <Button android:id="@+id/button6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 6" /> <!-- Button 7 --> <Button android:id="@+id/button7" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 7" /> <!-- Button 8 --> <Button android:id="@+id/button8" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 8" /> </LinearLayout> </androidx.core.widget.NestedScrollView>

MainActivity.java
-----------------
package com.example.scrollviewdemo; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize buttons Button button1 = findViewById(R.id.button1); Button button2 = findViewById(R.id.button2); Button button3 = findViewById(R.id.button3); Button button4 = findViewById(R.id.button4); Button button5 = findViewById(R.id.button5); Button button6 = findViewById(R.id.button6); Button button7 = findViewById(R.id.button7); Button button8 = findViewById(R.id.button8); // Set click listeners for buttons button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button 1 clicked", Toast.LENGTH_SHORT).show(); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button 2 clicked", Toast.LENGTH_SHORT).show(); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button 3 clicked", Toast.LENGTH_SHORT).show(); } }); button4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button 4 clicked", Toast.LENGTH_SHORT).show(); } }); button5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button 5 clicked", Toast.LENGTH_SHORT).show(); } }); button6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button 6 clicked", Toast.LENGTH_SHORT).show(); } }); button7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button 7 clicked", Toast.LENGTH_SHORT).show(); } }); button8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button 8 clicked", Toast.LENGTH_SHORT).show(); } }); } }

AndroidManifest.xml
-------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.scrollviewdemo"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="ScrollView Demo" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>



Create First Activity to accept information like Employee First Name, Middle Name, Last Name, Date of birth, Address, Email ID and display all information on Second Activity when user click on Submit button.

XML Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <!-- Employee First Name --> <EditText android:id="@+id/edtFirstName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="First Name" android:inputType="textPersonName" /> <!-- Employee Middle Name --> <EditText android:id="@+id/edtMiddleName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Middle Name" android:inputType="textPersonName" /> <!-- Employee Last Name --> <EditText android:id="@+id/edtLastName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Last Name" android:inputType="textPersonName" /> <!-- Employee Date of Birth --> <EditText android:id="@+id/edtDateOfBirth" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Date of Birth (yyyy-mm-dd)" android:inputType="date" /> <!-- Employee Address --> <EditText android:id="@+id/edtAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Address" android:inputType="textMultiLine" /> <!-- Employee Email --> <EditText android:id="@+id/edtEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email" android:inputType="textEmailAddress" /> <!-- Submit Button --> <Button android:id="@+id/btnSubmit" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Submit" /> </LinearLayout>

Java Code for MainActivity

In this MainActivity.java, we will capture the employee data from the EditText fields, and pass it to the second activity using an Intent.


package com.example.employeeinfo; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // Declare UI elements private EditText edtFirstName, edtMiddleName, edtLastName, edtDateOfBirth, edtAddress, edtEmail; private Button btnSubmit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize UI elements edtFirstName = findViewById(R.id.edtFirstName); edtMiddleName = findViewById(R.id.edtMiddleName); edtLastName = findViewById(R.id.edtLastName); edtDateOfBirth = findViewById(R.id.edtDateOfBirth); edtAddress = findViewById(R.id.edtAddress); edtEmail = findViewById(R.id.edtEmail); btnSubmit = findViewById(R.id.btnSubmit); // Set click listener on submit button btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Get the values from the EditText fields String firstName = edtFirstName.getText().toString(); String middleName = edtMiddleName.getText().toString(); String lastName = edtLastName.getText().toString(); String dateOfBirth = edtDateOfBirth.getText().toString(); String address = edtAddress.getText().toString(); String email = edtEmail.getText().toString(); // Check if any field is empty if (firstName.isEmpty() || middleName.isEmpty() || lastName.isEmpty() || dateOfBirth.isEmpty() || address.isEmpty() || email.isEmpty()) { Toast.makeText(MainActivity.this, "Please fill all fields", Toast.LENGTH_SHORT).show(); } else { // Create an Intent to send data to SecondActivity Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtra("first_name", firstName); intent.putExtra("middle_name", middleName); intent.putExtra("last_name", lastName); intent.putExtra("date_of_birth", dateOfBirth); intent.putExtra("address", address); intent.putExtra("email", email); // Start the Second Activity startActivity(intent); } } }); } }

XML Layout (activity_second.xml) for Second Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <!-- TextViews to display the employee information --> <TextView android:id="@+id/tvFirstName" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="First Name: " android:textSize="18sp" /> <TextView android:id="@+id/tvMiddleName" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Middle Name: " android:textSize="18sp" /> <TextView android:id="@+id/tvLastName" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Last Name: " android:textSize="18sp" /> <TextView android:id="@+id/tvDateOfBirth" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Date of Birth: " android:textSize="18sp" /> <TextView android:id="@+id/tvAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Address: " android:textSize="18sp" /> <TextView android:id="@+id/tvEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Email: " android:textSize="18sp" /> </LinearLayout>

Java Code for SecondActivity.java

package com.example.employeeinfo; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class SecondActivity extends AppCompatActivity { // Declare TextViews to display employee information private TextView tvFirstName, tvMiddleName, tvLastName, tvDateOfBirth, tvAddress, tvEmail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // Initialize TextViews tvFirstName = findViewById(R.id.tvFirstName); tvMiddleName = findViewById(R.id.tvMiddleName); tvLastName = findViewById(R.id.tvLastName); tvDateOfBirth = findViewById(R.id.tvDateOfBirth); tvAddress = findViewById(R.id.tvAddress); tvEmail = findViewById(R.id.tvEmail); // Get the Intent that started this activity Intent intent = getIntent(); // Retrieve the employee data from the Intent String firstName = intent.getStringExtra("first_name"); String middleName = intent.getStringExtra("middle_name"); String lastName = intent.getStringExtra("last_name"); String dateOfBirth = intent.getStringExtra("date_of_birth"); String address = intent.getStringExtra("address"); String email = intent.getStringExtra("email"); // Display the employee data on the TextViews tvFirstName.setText("First Name: " + firstName); tvMiddleName.setText("Middle Name: " + middleName); tvLastName.setText("Last Name: " + lastName); tvDateOfBirth.setText("Date of Birth: " + dateOfBirth); tvAddress.setText("Address: " + address); tvEmail.setText("Email: " + email); } }

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.employeeinfo"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Employee Info" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SecondActivity" /> </application> </manifest>


Create application to send an email.

activity_main.xml
-----------------
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/edtRecipient" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Recipient Email" android:inputType="textEmailAddress"/> <EditText android:id="@+id/edtSubject" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Subject" android:inputType="text"/> <EditText android:id="@+id/edtBody" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Message Body" android:inputType="textMultiLine" android:lines="5" android:gravity="top|start"/> <Button android:id="@+id/btnSendEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Send Email"/> </LinearLayout>

MainActivity.java
------------------
package com.example.sendemailapp; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private EditText edtRecipient, edtSubject, edtBody; private Button btnSendEmail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtRecipient = findViewById(R.id.edtRecipient); edtSubject = findViewById(R.id.edtSubject); edtBody = findViewById(R.id.edtBody); btnSendEmail = findViewById(R.id.btnSendEmail); btnSendEmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String recipient = edtRecipient.getText().toString(); String subject = edtSubject.getText().toString(); String body = edtBody.getText().toString(); if (recipient.isEmpty() || subject.isEmpty() || body.isEmpty()) { Toast.makeText(MainActivity.this, "Please fill in all fields", Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient}); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, body); try { startActivity(Intent.createChooser(intent, "Choose an email client")); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(MainActivity.this, "No email client found", Toast.LENGTH_SHORT).show(); } } } }); } }

AndroidManifest.xml
-------------------
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sendemailapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Send Email App" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

Create sample application with login module. Verify Check username and password. On successful login, pass username to next screen and if login fails, prompt the user.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/edtUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Username" android:inputType="text"/> <EditText android:id="@+id/edtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword"/> <Button android:id="@+id/btnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login"/> <TextView android:id="@+id/tvError" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textColor="#FF0000" android:visibility="gone"/> </LinearLayout>

activity_dashboard.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/tvWelcome" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome!" android:textSize="20sp"/> </LinearLayout>

MainActivity.java

package com.example.loginapp; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private EditText edtUsername, edtPassword; private Button btnLogin; private TextView tvError; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtUsername = findViewById(R.id.edtUsername); edtPassword = findViewById(R.id.edtPassword); btnLogin = findViewById(R.id.btnLogin); tvError = findViewById(R.id.tvError); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = edtUsername.getText().toString(); String password = edtPassword.getText().toString(); if (username.equals("user") && password.equals("password123")) { Intent intent = new Intent(MainActivity.this, DashboardActivity.class); intent.putExtra("username", username); startActivity(intent); finish(); } else { tvError.setVisibility(View.VISIBLE); tvError.setText("Invalid username or password"); } } }); } }

DashboardActivity.java

package com.example.loginapp; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class DashboardActivity extends AppCompatActivity { private TextView tvWelcome; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); tvWelcome = findViewById(R.id.tvWelcome); String username = getIntent().getStringExtra("username"); if (username != null) { tvWelcome.setText("Welcome, " + username + "!"); } } }

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.loginapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="LoginApp" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"> <activity android:name=".DashboardActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity"/> </application> </manifest>


Create a Simple Application, which reads a positive number from the user and display its factorial value in another activity.

activity_main.xml (Main Activity Layout)

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/edtNumber" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter a positive number" android:inputType="number"/> <Button android:id="@+id/btnCalculate" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Calculate Factorial"/> </LinearLayout>

activity_result.xml (Result Activity Layout)

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <TextView android:id="@+id/tvResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Factorial Result" android:textSize="20sp"/> </LinearLayout>

MainActivity.java (Main Activity Logic)

package com.example.factorialapp; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private EditText edtNumber; private Button btnCalculate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtNumber = findViewById(R.id.edtNumber); btnCalculate = findViewById(R.id.btnCalculate); btnCalculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String input = edtNumber.getText().toString(); if (!input.isEmpty()) { int number = Integer.parseInt(input); if (number >= 0) { // Calculate factorial and pass to the ResultActivity long factorialResult = calculateFactorial(number); Intent intent = new Intent(MainActivity.this, ResultActivity.class); intent.putExtra("factorial", factorialResult); startActivity(intent); } else { Toast.makeText(MainActivity.this, "Please enter a positive number", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show(); } } }); } private long calculateFactorial(int number) { long result = 1; for (int i = 1; i <= number; i++) { result *= i; } return result; } }

ResultActivity.java (Result Activity Logic)

package com.example.factorialapp; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class ResultActivity extends AppCompatActivity { private TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); tvResult = findViewById(R.id.tvResult); // Get factorial result from Intent long factorial = getIntent().getLongExtra("factorial", -1); if (factorial != -1) { tvResult.setText("Factorial: " + factorial); } } }

AndroidManifest.xml (Manifest File)

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.factorialapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="FactorialApp" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"> <activity android:name=".ResultActivity" /> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

build.gradle (app level)

Make sure you have the appropriate dependencies set for the app.

dependencies { implementation 'androidx.appcompat:appcompat:1.2.0' }


Create a simple To-Do List Application using React JS.

To install:
npx create-react-app todo-app

Once the app is created, navigate to the todo-app folder:

cd todo-app

2. App.js (Main Application File)


import React, { useState } from 'react'; import './App.css'; function App() { // State for storing tasks const [task, setTask] = useState(""); const [todos, setTodos] = useState([]); // Add new task to the list const handleAddTask = () => { if (task.trim() !== "") { setTodos([ ...todos, { id: Date.now(), text: task, completed: false } ]); setTask(""); } }; // Mark task as completed const toggleComplete = (id) => { setTodos(todos.map(todo => todo.id === id ? { ...todo, completed: !todo.completed } : todo )); }; // Delete task const deleteTask = (id) => { setTodos(todos.filter(todo => todo.id !== id)); }; return ( <div className="App"> <h1>To-Do List</h1> {/* Input field for new task */} <input type="text" value={task} onChange={(e) => setTask(e.target.value)} placeholder="Enter a task" /> {/* Add Task Button */} <button onClick={handleAddTask}>Add Task</button> <ul> {todos.map(todo => ( <li key={todo.id} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}> <span onClick={() => toggleComplete(todo.id)}>{todo.text}</span> <button onClick={() => deleteTask(todo.id)}>Delete</button> </li> ))} </ul> </div> ); } export default App;

3. App.css (Styling the To-Do List)

.App { font-family: Arial, sans-serif; width: 300px; margin: 0 auto; text-align: center; } h1 { color: #4CAF50; } input { width: 70%; padding: 10px; margin-bottom: 10px; margin-right: 5px; } button { padding: 10px; background-color: #4CAF50; color: white; border: none; cursor: pointer; } button:hover { background-color: #45a049; } ul { list-style-type: none; padding: 0; } li { display: flex; justify-content: space-between; align-items: center; margin: 10px 0; } li button { background-color: red; color: white; padding: 5px 10px; border: none; cursor: pointer; } li button:hover { background-color: darkred; } span { cursor: pointer; }

To start enter the command : npm start


Create an Android Application that Demonstrate Radio Button.

. Layout File (activity_main.xml)

The layout will have a group of radio buttons inside a RadioGroup, and a TextView to display the selected option.

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <!-- Title Text --> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select Your Favorite Fruit" android:textSize="20sp" android:layout_marginBottom="16dp" /> <!-- RadioGroup to contain multiple RadioButtons --> <RadioGroup android:id="@+id/radioGroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- Radio Buttons --> <RadioButton android:id="@+id/radioApple" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Apple" /> <RadioButton android:id="@+id/radioBanana" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Banana" /> <RadioButton android:id="@+id/radioCherry" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cherry" /> </RadioGroup> <!-- TextView to show the selected fruit --> <TextView android:id="@+id/tvResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Selected Fruit: None" android:textSize="18sp" android:layout_marginTop="16dp" /> </LinearLayout>

2. MainActivity.java

In this activity, we will handle the selection of the radio buttons and update the TextView based on the user's choice.

package com.example.radiobuttonapp; import android.os.Bundle; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private RadioGroup radioGroup; private RadioButton radioApple, radioBanana, radioCherry; private TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize UI components radioGroup = findViewById(R.id.radioGroup); radioApple = findViewById(R.id.radioApple); radioBanana = findViewById(R.id.radioBanana); radioCherry = findViewById(R.id.radioCherry); tvResult = findViewById(R.id.tvResult); // Set listener for the RadioGroup radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // Check which radio button is selected if (checkedId == R.id.radioApple) { tvResult.setText("Selected Fruit: Apple"); } else if (checkedId == R.id.radioBanana) { tvResult.setText("Selected Fruit: Banana"); } else if (checkedId == R.id.radioCherry) { tvResult.setText("Selected Fruit: Cherry"); } } }); } }

3. AndroidManifest.xml

Make sure the MainActivity is declared in the AndroidManifest.xml.


<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.radiobuttonapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="RadioButtonApp" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.DayNight.NoActionBar"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>


Create an Android Application that Demonstrate Switch and Toggle Button.

(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <!-- TextView to show the status --> <TextView android:id="@+id/statusTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch and ToggleButton Status" android:textSize="18sp" android:layout_marginBottom="20dp" android:layout_marginTop="20dp"/> <!-- Switch --> <Switch android:id="@+id/switchButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch" android:layout_marginBottom="20dp" /> <!-- ToggleButton --> <ToggleButton android:id="@+id/toggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="ON" android:textOff="OFF" android:layout_marginBottom="20dp"/> </LinearLayout>

MainActivity.java

package com.example.switchtogglebuttondemo; import android.os.Bundle; import android.view.View; import android.widget.Switch; import android.widget.TextView; import android.widget.ToggleButton; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private Switch switchButton; private ToggleButton toggleButton; private TextView statusTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize UI components switchButton = findViewById(R.id.switchButton); toggleButton = findViewById(R.id.toggleButton); statusTextView = findViewById(R.id.statusTextView); // Set listeners for Switch and ToggleButton switchButton.setOnCheckedChangeListener((buttonView, isChecked) -> updateStatus()); toggleButton.setOnCheckedChangeListener((buttonView, isChecked) -> updateStatus()); } // Method to update the status TextView based on Switch and ToggleButton states private void updateStatus() { String switchStatus = switchButton.isChecked() ? "ON" : "OFF"; String toggleStatus = toggleButton.isChecked() ? "ON" : "OFF"; String statusText = "Switch is " + switchStatus + "\n" + "ToggleButton is " + toggleStatus; statusTextView.setText(statusText); } }

Create a custom "Contact" layout to hold multiple pieces of information, including: Photo, Name, Contact Number, E-mail id.

Contact Item Layout (contact_item.xml)

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp" android:background="?android:attr/selectableItemBackground"> <!-- ImageView for contact photo --> <ImageView android:id="@+id/contactPhoto" android:layout_width="60dp" android:layout_height="60dp" android:src="@drawable/ic_person" <!-- Default image (use any drawable) --> android:layout_marginEnd="16dp" android:contentDescription="Contact Photo"/> <!-- Vertical LinearLayout for name, number, and email --> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1"> <!-- TextView for contact name --> <TextView android:id="@+id/contactName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="John Doe" android:textSize="18sp" android:textStyle="bold"/> <!-- TextView for contact number --> <TextView android:id="@+id/contactNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="123-456-7890" android:textSize="16sp" android:textColor="#888"/> <!-- TextView for contact email --> <TextView android:id="@+id/contactEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="email@example.com" android:textSize="16sp" android:textColor="#888"/> </LinearLayout> </LinearLayout>

Model Class (Contact.java)

package com.example.contactapp; public class Contact { private String photoUrl; // URL or Drawable resource for photo private String name; private String contactNumber; private String email; // Constructor public Contact(String photoUrl, String name, String contactNumber, String email) { this.photoUrl = photoUrl; this.name = name; this.contactNumber = contactNumber; this.email = email; } // Getters and setters public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }

RecyclerView Adapter (ContactAdapter.java)

The adapter will bind the Contact data to the views in the contact_item.xml.

package com.example.contactapp; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; // For loading images from URLs import java.util.List; public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> { private List<Contact> contactList; public ContactAdapter(List<Contact> contactList) { this.contactList = contactList; } @Override public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.contact_item, parent, false); return new ContactViewHolder(view); } @Override public void onBindViewHolder(ContactViewHolder holder, int position) { Contact contact = contactList.get(position); // Set the contact's name, number, and email holder.nameTextView.setText(contact.getName()); holder.numberTextView.setText(contact.getContactNumber()); holder.emailTextView.setText(contact.getEmail()); // Load the contact's photo (using Glide to handle image loading) Glide.with(holder.itemView.getContext()) .load(contact.getPhotoUrl()) // This could be a URL or drawable resource .into(holder.photoImageView); } @Override public int getItemCount() { return contactList.size(); } public static class ContactViewHolder extends RecyclerView.ViewHolder { ImageView photoImageView; TextView nameTextView, numberTextView, emailTextView; public ContactViewHolder(View itemView) { super(itemView); photoImageView = itemView.findViewById(R.id.contactPhoto); nameTextView = itemView.findViewById(R.id.contactName); numberTextView = itemView.findViewById(R.id.contactNumber); emailTextView = itemView.findViewById(R.id.contactEmail); } } }

MainActivity (MainActivity.java)

In the MainActivity, we will set up a RecyclerView to display the list of contacts.

package com.example.contactapp; import android.os.Bundle; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private ContactAdapter contactAdapter; private List<Contact> contactList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); // Initialize contact list contactList = new ArrayList<>(); loadContacts(); // Set up the adapter for the RecyclerView contactAdapter = new ContactAdapter(contactList); recyclerView.setAdapter(contactAdapter); } private void loadContacts() { // Adding some sample contacts contactList.add(new Contact("https://example.com/photo1.jpg", "John Doe", "123-456-7890", "john.doe@example.com")); contactList.add(new Contact("https://example.com/photo2.jpg", "Jane Smith", "987-654-3210", "jane.smith@example.com")); contactList.add(new Contact("https://example.com/photo3.jpg", "Emma Brown", "555-555-5555", "emma.brown@example.com")); } }

Layout for MainActivity (activity_main.xml)

We will use a RecyclerView to display the list of contacts in the main activity.

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

Gradle Dependencies (for Glide)

If you're using Glide to load images from URLs, you need to add Glide to your project by adding this dependency in your build.gradle file.


dependencies { implementation 'com.github.bumptech.glide:glide:4.12.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0' }

Create an application to demonstrate date and time picker?

activity_main.xml

In the layout file, we'll have two buttons, one to pick a date and the other to pick a time, and TextViews to display the selected date and time.


<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <!-- Button to open Date Picker --> <Button android:id="@+id/btnDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pick Date" /> <!-- TextView to display the selected date --> <TextView android:id="@+id/tvSelectedDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Selected Date: " android:textSize="18sp" android:layout_marginTop="16dp"/> <!-- Button to open Time Picker --> <Button android:id="@+id/btnTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pick Time" android:layout_marginTop="16dp"/> <!-- TextView to display the selected time --> <TextView android:id="@+id/tvSelectedTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Selected Time: " android:textSize="18sp" android:layout_marginTop="16dp"/> </LinearLayout>

MainActivity.java

In the MainActivity.java, we'll set up listeners for the Date Picker and Time Picker dialogs. When a user selects a date or time, it will be displayed in the TextView below the respective button.

package com.example.dateandtimepicker; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.util.Calendar; public class MainActivity extends AppCompatActivity { private Button btnDate, btnTime; private TextView tvSelectedDate, tvSelectedTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize views btnDate = findViewById(R.id.btnDate); btnTime = findViewById(R.id.btnTime); tvSelectedDate = findViewById(R.id.tvSelectedDate); tvSelectedTime = findViewById(R.id.tvSelectedTime); // Set onClickListener for the Date Picker button btnDate.setOnClickListener(v -> openDatePicker()); // Set onClickListener for the Time Picker button btnTime.setOnClickListener(v -> openTimePicker()); } // Method to open Date Picker private void openDatePicker() { // Get the current date Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); // Create and show the Date Picker Dialog DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, selectedYear, selectedMonth, selectedDay) -> { // Display selected date in the TextView tvSelectedDate.setText("Selected Date: " + selectedDay + "/" + (selectedMonth + 1) + "/" + selectedYear); }, year, month, day); datePickerDialog.show(); } // Method to open Time Picker private void openTimePicker() { // Get the current time Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); // Create and show the Time Picker Dialog TimePickerDialog timePickerDialog = new TimePickerDialog(this, (view, selectedHour, selectedMinute) -> { // Display selected time in the TextView tvSelectedTime.setText("Selected Time: " + selectedHour + ":" + String.format("%02d", selectedMinute)); }, hour, minute, true); timePickerDialog.show(); } }

Comments