Android App Developement Practicals Programs

 

Android App Developement Practicals Programs

                                       SAVITRIBAI PHULE PUNE UNIVERSITY 

                                              M.Sc. (Computer Science) Sem-II 

                                              Practical Examination 2023 - 2024 

                   SUBJECT: CS-555-MJP Lab Course on CS-552-MJ 

                                         Mobile App Development Technologies




Slip 1

1.  Write an java android application to create a splash screen.

1. Design the Splash Screen Layout:

  • Create a new layout file under res/layout folder.
  • Name it descriptively, like activity_splash.xml.
  • Design the layout using XML. You can include elements like ImageView for a logo, TextView for app name, or a background image.

2. Create the Splash Activity:

  • In the java folder of your project, right-click and create a new Java class.
  • Name it SplashActivity.java.
  • This class will extend AppCompatActivity.

3. Implement the Splash Screen Logic:

  • In SplashActivity.java, override the onCreate method.
  • Set the activity to fullscreen using getWindow().setFlags(...).
  • Inflate the layout you created in step 1 using setContentView(R.layout.activity_splash).

4. Navigate to Main Activity:

  • Use a Handler to post a delayed task that starts your main activity after a desired delay (e.g., 2 seconds).
  • In the delayed task, create an Intent to launch your main activity class and call startActivity.

5. Configure the Manifest File:

  • Open AndroidManifest.xml.
  • Set the android:theme attribute for your splash activity to a theme that hides the action bar (@style/Theme.AppCompat.Light.NoActionBar).
  • Declare the splash activity in the <activity> tag with an intent filter with category set to android.intent.category.LAUNCHER. This makes it the default launch activity.

Here's an example code for SplashActivity.java:

Java
public class SplashActivity extends AppCompatActivity {

    private static final int SPLASH_SCREEN_TIME_OUT = 2000; // 2 seconds

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set full screen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(() -> {
            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }, SPLASH_SCREEN_TIME_OUT);
    }
}




2. Create table Student (roll_no, name, address, percentage). Create Application for performing the following operation on the table. (Using SQLite database). i] Insert record of 5 new student details. ii] Show all the student detail


1. Create the Database Helper Class:

Java
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "student.db";
    private static final int DATABASE_VERSION = 1;

    public static final String TABLE_NAME = "Student";
    public static final String COLUMN_ROLL_NO = "roll_no";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_ADDRESS = "address";
    public static final String COLUMN_PERCENTAGE = "percentage";

    private static final String CREATE_TABLE_STUDENT = "CREATE TABLE " + TABLE_NAME + "("
            + COLUMN_ROLL_NO + " INTEGER PRIMARY KEY,"
            + COLUMN_NAME + " TEXT,"
            + COLUMN_ADDRESS + " TEXT,"
            + COLUMN_PERCENTAGE + " REAL" + ")";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_STUDENT);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Handle database schema upgrades if needed
    }
}

2. Create Methods for CRUD Operations (Create, Read, Update, Delete):

Java
public class DatabaseHelper extends SQLiteOpenHelper {

    // ... existing code ...

    public void insertStudent(int rollNo, String name, String address, double percentage) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_ROLL_NO, rollNo);
        values.put(DatabaseHelper.COLUMN_NAME, name);
        values.put(DatabaseHelper.COLUMN_ADDRESS, address);
        values.put(DatabaseHelper.COLUMN_PERCENTAGE, percentage);
        db.insert(DatabaseHelper.TABLE_NAME, null, values);
        db.close();
    }

    public List<Student> getAllStudents() {
        List<Student> students = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_NAME, null);

        if (cursor.moveToFirst()) {
            do {
                int rollNo = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ROLL_NO));
                String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));
                String address = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_ADDRESS));
                double percentage = cursor.getDouble(cursor.getColumnIndex(DatabaseHelper.COLUMN_PERCENTAGE));
                students.add(new Student(rollNo, name, address, percentage));
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return students;
    }

    // ... other CRUD methods as needed ...
}

public class Student {
    private int rollNo;
    private String name;
    private String address;
    private double percentage;

    // ... constructors and getters/setters ...
}

3. Implement the Functionality in an Activity:

Java
public class MainActivity extends AppCompatActivity {

    private DatabaseHelper dbHelper;

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

        dbHelper = new DatabaseHelper(this);

        // Insert sample data (replace with button or user input)
        insertSampleData();

        // Show all students (replace with button or UI element)
        showStudentDetails();
    }

    private void insertSampleData() {
        dbHelper.insertStudent(1, "John Doe", "Address 1", 85.5);
        dbHelper.insertStudent(2, "Jane Smith", "Address 2", 92.0);
        // ... add more student data ...
    }

    private void showStudentDetails() {
        List<Student> students = dbHelper.getAllStudents();
        for (Student student : students) {
            // Display student information using TextViews or other UI elements
            Log.d("Student Details", "Roll No: " + student.getRollNo() + ", Name: " + student.getName());
        }
    }
}

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

Slip 2

1. Create an application that allows the user to enter a number in the textbox. Check whether the number in the textbox is perfect number or not. Print the message using Toast control


1. Create the Activity Layout (activity_main.xml):

XML
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

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

    <Button
        android:id="@+id/check_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Check Perfect Number" />

</LinearLayout>

2. Create the Activity Class (MainActivity.java):

Java
public class MainActivity extends AppCompatActivity {

    private EditText numberInput;
    private Button checkButton;

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

        numberInput = findViewById(R.id.number_input);
        checkButton = findViewById(R.id.check_button);

        checkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputString = numberInput.getText().toString().trim();

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

                int number;
                try {
                    number = Integer.parseInt(inputString);
                } catch (NumberFormatException e) {
                    Toast.makeText(MainActivity.this, "Invalid number format", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (isPerfectNumber(number)) {
                    Toast.makeText(MainActivity.this, number + " is a perfect number", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, number + " is not a perfect number", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private boolean isPerfectNumber(int number) {
        if (number <= 1) {
            return false;
        }

        int sum = 0;
        for (int i = 1; i < number; i++) {
            if (number % i == 0) {
                sum += i;
            }
        }

        return sum == number;
    }
}

Explanation:

  • The layout file defines an EditText for user input and a Button to trigger the check.
  • The activity class handles user interaction and logic.
  • It retrieves the input from the EditText and validates it.
  • The isPerfectNumber method checks if the number is a perfect number by calculating the sum of its divisors (excluding itself).
  • Toast messages are displayed based on the result.



2.) Java Android Program to perform all arithmetic Operations using Calculator


1. Layout File (activity_main.xml):

XML
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/result_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="0"
        android:textAlignment="textEnd" />

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="4">

        <Button
            android:id="@+id/button_7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="7" />

        <Button
            android:id="@+id/button_8"
            android:layout_width="wrap_content"
            android.layout_height="wrap_content"
            android:text="8" />

        <Button
            android:id="@+id/button_9"
            android:layout_width="wrap_content"
            android.layout_height="wrap_content"
            android:text="9" />

        <Button
            android:id="@+id/button_divide"
            android:layout_width="wrap_content"
            android.layout_height="wrap_content"
            android:text="/" />

        </GridLayout>

</LinearLayout>

2. Activity Class (MainActivity.java):

Java
public class MainActivity extends AppCompatActivity {

    private TextView resultText;
    private double firstNumber = Double.NaN; // To check if a number is entered
    private char operator;

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

        resultText = findViewById(R.id.result_text);

        // Set click listeners for number buttons
        findViewById(R.id.button_7).setOnClickListener(numberClickListener);
        // ... add click listeners for other number buttons ...

        // Set click listeners for operator buttons
        findViewById(R.id.button_divide).setOnClickListener(operatorClickListener);
        // ... add click listeners for other operator buttons ...

        // Button to clear the display
        findViewById(R.id.button_clear).setOnClickListener(v -> {
            clearCalculator();
        });

        // Button to calculate the result
        findViewById(R.id.button_equal).setOnClickListener(v -> {
            calculateResult();
        });
    }

    private View.OnClickListener numberClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String number = ((Button) v).getText().toString();
            appendNumberToResult(number);
        }
    };

    private View.OnClickListener operatorClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            char op = ((Button) v).getText().toString().charAt(0);
            setOperator(op);
        }
    };

    private void appendNumberToResult(String number) {
        String currentResult = resultText.getText().toString();
        if (currentResult.equals("0") || firstNumber == Double.NaN) {
            resultText.setText(number);
        } else {
            resultText.setText(currentResult + number);
        }
        firstNumber = Double.parseDouble(currentResult);
    }

    private void setOperator(char op) {
        if (!Double.isNaN(firstNumber)) {
            operator = op;
            resultText.setText("0"); // Clear display for next number
        }
    }

    private void calculateResult() {
        if (!Double.isNaN(firstNumber)) {
            double secondNumber = Double.parseDouble(resultText.getText().toString());


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

Slip 3

1.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

1. Create the Activity Layout (activity_main.xml):

<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:padding="16dp"

    tools:context=".MainActivity">


    <EditText

        android:id="@+id/number_input"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Enter a number"

        android:inputType="number" />


    <Button

        android:id="@+id/check_button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="16dp"

        android:text="Check Armstrong Number" />


    <TextView

        android:id="@+id/result_label"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="" />


</LinearLayout>


2. Create the Activity Class (MainActivity.java):

public class MainActivity extends AppCompatActivity {

    private EditText numberInput;
    private Button checkButton;
    private TextView resultLabel;

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

        numberInput = findViewById(R.id.number_input);
        checkButton = findViewById(R.id.check_button);
        resultLabel = findViewById(R.id.result_label);

        checkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputString = numberInput.getText().toString().trim();

                if (inputString.isEmpty()) {
                    resultLabel.setText("Please enter a number");
                    return;
                }

                int number;
                try {
                    number = Integer.parseInt(inputString);
                } catch (NumberFormatException e) {
                    resultLabel.setText("Invalid number format");
                    return;
                }

                if (isArmstrongNumber(number)) {
                    resultLabel.setText(number + " is an Armstrong number");
                } else {
                    resultLabel.setText(number + " is not an Armstrong number");
                }
            }
        });
    }

    private boolean isArmstrongNumber(int number) {
        int originalNumber = number;
        int sum = 0;
        int numberOfDigits = String.valueOf(number).length();

        while (number > 0) {
            int digit = number % 10;
            sum += Math.pow(digit, numberOfDigits);
            number /= 10;
        }

        return originalNumber == sum;
    }
}



Explanation:

  • The layout file defines an EditText for user input, a Button to trigger the check, and a TextView to display the result.
  • The activity class handles user interaction and logic.
  • It retrieves the input from the EditText and validates it.
  • The isArmstrongNumber method checks if the number is an Armstrong number by calculating the sum of each digit raised to the power of the number of digits.
  • The result label is updated based on whether the number is Armstrong or not.



2.Create an Android application which examine a phone number entered by a user with the given format. • Area code should be one of the following: 040, 041, 050, 0400, 044 • There should 6 - 8 numbers in telephone number (+ area code).


2. Implement Phone Number Validation Method:

Java
public class MainActivity extends AppCompatActivity {

    private static final String[] VALID_AREA_CODES = {"040", "041", "050", "0400", "044"};

    private boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return false;
        }

        // Remove non-numeric characters
        phoneNumber = phoneNumber.replaceAll("[^0-9]", "");

        // Check length (6 to 8 digits)
        int length = phoneNumber.length();
        if (length < 6 || length > 8) {
            return false;
        }

        // Check area code
        String areaCode = phoneNumber.substring(0, Math.min(phoneNumber.length(), 4));
        return Arrays.asList(VALID_AREA_CODES).contains(areaCode);
    }
}

3. Create the Activity Layout (activity_main.xml):

XML
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/phone_number_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter phone number"
        android:inputType="phone" />

    <Button
        android:id="@+id/check_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Check Phone Number" />

    <TextView
        android:id="@+id/result_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

4. Create the Activity Class (MainActivity.java):

Java
public class MainActivity extends AppCompatActivity {

    private static final String[] VALID_AREA_CODES = {"040", "041", "050", "0400", "044"};

    private EditText phoneNumberInput;
    private Button checkButton;
    private TextView resultLabel;

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

        phoneNumberInput = findViewById(R.id.phone_number_input);
        checkButton = findViewById(R.id.check_button);
        resultLabel = findViewById(R.id.result_label);

        checkButton.setOnClickListener(v -> {
            String phoneNumber = phoneNumberInput.getText().toString().trim();
            if (isValidPhoneNumber(phoneNumber)) {
                resultLabel.setText(phoneNumber + " is a valid phone number");
            } else {
                resultLabel.setText(phoneNumber + " is not a valid phone number");
            }
        });
    }

    private boolean isValidPhoneNumber(String phoneNumber) {
        // ... (implementation from step 2) ...
    }
}

Explanation:

  1. The VALID_AREA_CODES array stores the allowed area codes.
  2. The isValidPhoneNumber method checks:
    • If the phone number is empty or null.
    • Removes non-numeric characters.
    • Checks if the length is between 6 and 8 digits.
    • Extracts the area code and verifies it's in the valid list.
  3. The layout file defines an EditText for phone number input, a Button to trigger validation, and a TextView to display the result.
  4. The activity class handles user interaction and calls the isValidPhoneNumber method to check the format. It displays a message based on the validation result.

Note: This is a basic implementation. You can enhance


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


Slip 4

1.) Construct image switcher using setFactory()

1. Image Switcher Component:

The ImageSwitcher component provides a way to transition between images with animations. You can define it in your layout file (XML):

XML
<ImageSwitcher
    android:id="@+id/imageSwitcher"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

2. Setting the Factory:

The setFactory() method of ImageSwitcher allows you to specify a ViewFactory that creates the ImageView objects used for displaying images. This gives you control over the creation and configuration of each view.

Here's how to implement it:

Java
ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
imageSwitcher.setFactory(new ViewFactory() {
    @Override
    public View makeView() {
        ImageView imageView = new ImageView(getApplicationContext());
        // You can set properties for the ImageView here (e.g., scale type)
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return imageView;
    }
});

This code retrieves the ImageSwitcher reference and sets a ViewFactory that creates a new ImageView with CENTER_CROP scale type each time an image needs to be displayed.

3. Adding Animations (Optional):

You can enhance the image transition by setting in and out animations for the ImageSwitcher:

Java
Animation inAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_in_left);
Animation outAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_out_right);
imageSwitcher.setInAnimation(inAnimation);
imageSwitcher.setOutAnimation(outAnimation);

This code loads pre-defined animations (slide_in_left and slide_out_right) and sets them for the ImageSwitcher.

4. Setting Images:

There are multiple ways to set images in the ImageSwitcher:

  • Using setImageResource:
Java
imageSwitcher.setImageResource(R.drawable.image1);
  • Using setImageURI:
Java
Uri imageUri = Uri.parse("path/to/your/image.jpg");
imageSwitcher.setImageURI(imageUri);

5. User Interaction (Optional):

You can add buttons or gestures to switch between images by calling imageSwitcher.setImageNext() or imageSwitcher.setImagePrevious().

Remember:

  • Replace R.anim.slide_in_left and R.anim.slide_out_right with your actual animation resource IDs.
  • Ensure you have the necessary animation files defined in your res/anim directory.



2.Write a program to search a specific location on Google Map.



import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.model.GeocodingResult;
import com.google.maps.model.LatLng;

public class GoogleMapsSearch {
    public static void main(String[] args) {
        // Replace "YOUR_API_KEY" with your actual API key
        String apiKey = "YOUR_API_KEY";

        // Specify the address or location you want to search for
        String address = "1600 Amphitheatre Parkway, Mountain View, CA";

        // Initialize the GeoApiContext with your API key
        GeoApiContext context = new GeoApiContext.Builder()
                                    .apiKey(apiKey)
                                    .build();

        try {
            // Perform the geocoding request to get the location details
            GeocodingResult[] results = GeocodingApi.geocode(context, address).await();

            // Check if there are any results
            if (results != null && results.length > 0) {
                // Get the latitude and longitude of the location
                LatLng location = results[0].geometry.location;

                // Print the latitude and longitude
                System.out.println("Latitude: " + location.lat);
                System.out.println("Longitude: " + location.lng);
            } else {
                System.out.println("No results found for the specified address.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


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

Slip 5

1.Java Android Program to Demonstrate Alert Dialog Box

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Get reference to the button

        Button showAlertButton = findViewById(R.id.showAlertButton);


        // Set click listener for the button

        showAlertButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                // Create AlertDialog builder

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);


                // Set title and message for AlertDialog

                alertDialogBuilder.setTitle("Alert Dialog");

                alertDialogBuilder.setMessage("This is an example of an Alert Dialog");


                // Set positive button and its click listener

                alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        // Do something when OK button is clicked

                        dialog.dismiss();

                    }

                });


                // Create and show AlertDialog

                AlertDialog alertDialog = alertDialogBuilder.create();

                alertDialog.show();

            }

        });

    }

}



in this program:
  1. We create an AlertDialog.Builder object alertDialogBuilder.
  2. We set the title and message for the AlertDialog using setTitle() and setMessage().
  3. We set the positive button for the AlertDialog using setPositiveButton(). When the user clicks this button, the dialog is dismissed.
  4. We create the AlertDialog object by calling create() on the builder.
  5. We call show() on the AlertDialog object to display the dialog to the user.

Make sure to have a layout file (e.g., activity_main.xml) with a button (e.g., showAlertButton) that triggers the display of the AlertDialog.


2.   Create an Android application which will ask the user to input his / her name. A message should display the two items concatenated in a label. Change the format of the label using radio buttons and check boxes for selection. The user can make the label text bold, underlined or italic as well as change its color. Also include buttons to display the message in the label, clear the text boxes as well as label. Finally exit.


1. Layout File (activity_main.xml):

XML
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/user_name_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name" />

    <TextView
        android:id="@+id/greeting_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Formatting options:" />

    <RadioGroup
        android:id="@+id/format_radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/radio_normal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Normal"
            android:checked="true" />

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

        <RadioButton
            android:id="@+id/radio_italic"
            android:layout_width="wrap_content"
            android.layout.height="wrap_content"
            android:text="Italic" />

        <RadioButton
            android:id="@+id/radio_underline"
            android:layout_width="wrap_content"
            android.layout.height="wrap_content"
            android:text="Underline" />
    </RadioGroup>

    <CheckBox
        android:id="@+id/checkbox_color"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Color" />

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

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

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

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

</LinearLayout>

2. Activity Class (MainActivity.java):

Java
public class MainActivity extends AppCompatActivity {

    private EditText userNameInput;
    private TextView greetingLabel;
    private RadioGroup formatRadioGroup;
    private CheckBox colorCheckbox;
    private Button showButton, clearButton, exitButton;

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

        userNameInput = findViewById(R.id.user_name_input);
        greetingLabel = findViewById(R.id.greeting_label);
        formatRadioGroup = findViewById(R.id.format_radio_group);
        colorCheckbox = findViewById(R.id.checkbox_color);
        showButton = findViewById(R.id.button_show);
        clearButton = findViewById(R.id.button_clear);
        exitButton = findViewById(R.id.button_exit);

        showButton.setOnClickListener(v -> showMessage());
        clearButton.setOnClickListener(v -> clearInput());
        exitButton.set



Slip 6

write Java Android Program to demonstrate login form with validation

email password login


import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.text.TextUtils;

import android.util.Patterns;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;


public class LoginActivity extends AppCompatActivity {


    private EditText emailEditText, passwordEditText;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);


        emailEditText = findViewById(R.id.emailEditText);

        passwordEditText = findViewById(R.id.passwordEditText);

        Button loginButton = findViewById(R.id.loginButton);


        loginButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                validateAndLogin();

            }

        });

    }


    private void validateAndLogin() {

        String email = emailEditText.getText().toString().trim();

        String password = passwordEditText.getText().toString().trim();


        if (TextUtils.isEmpty(email)) {

            Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();

            return;

        }


        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {

            Toast.makeText(this, "Please enter a valid email", Toast.LENGTH_SHORT).show();

            return;

        }


        if (TextUtils.isEmpty(password)) {

            Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show();

            return;

        }


        // Here you can implement your login logic, such as sending a request to a server

        // with the entered email and password and handling the response accordingly.


        // For demonstration purposes, let's just display a toast message indicating successful login.

        Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show();

    }

}











 Write a program to search a specific location on Google Map

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MapsActivity extends AppCompatActivity {

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

        Button searchButton = findViewById(R.id.searchButton);
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Replace "latitude,longitude" with the coordinates of the location you want to search
                String location = "latitude,longitude";

                // Create a Uri object with the geo scheme and the location coordinates
                Uri gmmIntentUri = Uri.parse("geo:" + location + "?q=" + Uri.encode("Your Location"));

                // Create an Intent with ACTION_VIEW and the Uri
                Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);

                // Set the package to Google Maps
                mapIntent.setPackage("com.google.android.apps.maps");

                // Attempt to start the Google Maps application
                if (mapIntent.resolveActivity(getPackageManager()) != null) {
                    startActivity(mapIntent);
                } else {
                    // If Google Maps app is not available, handle the situation accordingly
                    // For example, you could open the location in a web browser
                    // Or prompt the user to install Google Maps
                }
            }
        });
    }
}


Slip 7

] Java Android Program to Demonstrate ProgressBar.


import android.os.Bundle;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.ProgressBar;


public class ProgressBarActivity extends AppCompatActivity {


    private ProgressBar progressBar;

    private Button startButton;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_progress_bar);


        progressBar = findViewById(R.id.progressBar);

        startButton = findViewById(R.id.startButton);


        startButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                startProgress();

            }

        });

    }


    private void startProgress() {

        // Set progress to 0 initially

        progressBar.setProgress(0);


        // Create a handler to update progress periodically

        final Handler handler = new Handler();

        handler.postDelayed(new Runnable() {

            @Override

            public void run() {

                int progress = progressBar.getProgress();

                if (progress < progressBar.getMax()) {

                    // Increment progress by 10

                    progressBar.setProgress(progress + 10);

                    // Repeat after 1 second (1000 milliseconds)

                    handler.postDelayed(this, 1000);

                } else {

                    // When progress reaches max, reset progress bar and display completion message

                    progressBar.setProgress(0);

                    // Optionally, display a completion message

                    // Toast.makeText(ProgressBarActivity.this, "Progress completed!", Toast.LENGTH_SHORT).show();

                }

            }

        }, 1000); // Start progress after 1 second

    }

}






Create table Employee (E_id, name, address, ph_no). Create Application for performing the following operation on the table. (Using SQLite database). i] Insert record of 5 new Employees. ii] Show all the details of Employee


import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private SQLiteDatabase mDatabase;

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

        // Create or open the database
        EmployeeDbHelper dbHelper = new EmployeeDbHelper(this);
        mDatabase = dbHelper.getWritableDatabase();

        // Insert 5 new employees
        insertEmployee("John Doe", "123 Main St", "1234567890");
        insertEmployee("Jane Smith", "456 Elm St", "9876543210");
        insertEmployee("Alice Johnson", "789 Oak St", "5551234567");
        insertEmployee("Bob Brown", "111 Pine St", "4449876543");
        insertEmployee("Eva Garcia", "222 Maple St", "2223334444");

        // Show all employee details
        showEmployeeDetails();
    }

    private void insertEmployee(String name, String address, String phoneNumber) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(EmployeeContract.EmployeeEntry.COLUMN_NAME, name);
        contentValues.put(EmployeeContract.EmployeeEntry.COLUMN_ADDRESS, address);
        contentValues.put(EmployeeContract.EmployeeEntry.COLUMN_PH_NO, phoneNumber);

        long newRowId = mDatabase.insert(EmployeeContract.EmployeeEntry.TABLE_NAME, null, contentValues);

        if (newRowId == -1) {
            Toast.makeText(this, "Error inserting employee", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Employee inserted with ID: " + newRowId, Toast.LENGTH_SHORT).show();
        }
    }

    private void showEmployeeDetails() {
        Cursor cursor = mDatabase.rawQuery("SELECT * FROM " + EmployeeContract.EmployeeEntry.TABLE_NAME, null);

        StringBuilder stringBuilder = new StringBuilder();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_ID));
            String name = cursor.getString(cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_NAME));
            String address = cursor.getString(cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_ADDRESS));
            String phoneNumber = cursor.getString(cursor.getColumnIndex(EmployeeContract.EmployeeEntry.COLUMN_PH_NO));

            stringBuilder.append("ID: ").append(id).append(", Name: ").append(name)
                    .append(", Address: ").append(address).append(", Phone: ").append(phoneNumber)
                    .append("\n");
        }

        cursor.close();

        TextView textView = findViewById(R.id.textView);
        textView.setText(stringBuilder.toString());
    }
}

 

Slip 8

 Create a Application which shows Life Cycle of Activity


import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;


public class MainActivity extends AppCompatActivity {


    private static final String TAG = "MainActivity";


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Log.d(TAG, "onCreate: Activity created");

    }


    @Override

    protected void onStart() {

        super.onStart();

        Log.d(TAG, "onStart: Activity started");

    }


    @Override

    protected void onResume() {

        super.onResume();

        Log.d(TAG, "onResume: Activity resumed");

    }


    @Override

    protected void onPause() {

        super.onPause();

        Log.d(TAG, "onPause: Activity paused");

    }


    @Override

    protected void onStop() {

        super.onStop();

        Log.d(TAG, "onStop: Activity stopped");

    }


    @Override

    protected void onDestroy() {

        super.onDestroy();

        Log.d(TAG, "onDestroy: Activity destroyed");

    }


    @Override

    protected void onRestart() {

        super.onRestart();

        Log.d(TAG, "onRestart: Activity restarted");

    }

}






Create table Customer (id, name, address, ph_no). Create Application for performing the following operation on the table. (Using SQLite database). i] Insert new customer details (At least 5 records). ii] Show all the customer details


  1. Define the Customer table:
sql
CREATE TABLE Customer ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, ph_no TEXT );
  1. Implement the Android application:


Certainly! Here's an Android application that allows you to perform CRUD operations on a SQLite database table named Customer.

  1. Define the Customer table:
sql
CREATE TABLE Customer ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, ph_no TEXT );
  1. Implement the Android application:

Create an Android application with the following components:

  • Layout XML files for UI design.
  • Java code to handle database operations.

Here's a basic implementation:

  1. Layout XML file for the main activity (activity_main.xml):
xml
<!-- activity_main.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <Button android:id="@+id/btnInsert" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Insert Customer" /> <Button android:id="@+id/btnShowAll" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Show All Customers" /> <TextView android:id="@+id/tvResult" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="" /> </LinearLayout>
  1. Java code for main activity (MainActivity.java):
java
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private SQLiteDatabase mDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create or open the database CustomerDbHelper dbHelper = new CustomerDbHelper(this); mDatabase = dbHelper.getWritableDatabase(); Button btnInsert = findViewById(R.id.btnInsert); Button btnShowAll = findViewById(R.id.btnShowAll); final TextView tvResult = findViewById(R.id.tvResult); btnInsert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { insertCustomer("John Doe", "123 Main St", "1234567890"); insertCustomer("Jane Smith", "456 Elm St", "9876543210"); insertCustomer("Alice Johnson", "789 Oak St", "5551234567"); insertCustomer("Bob Brown", "111 Pine St", "4449876543"); insertCustomer("Eva Garcia", "222 Maple St", "2223334444"); Toast.makeText(MainActivity.this, "Customers inserted successfully", Toast.LENGTH_SHORT).show(); } }); btnShowAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Cursor cursor = mDatabase.rawQuery("SELECT * FROM Customer", null); StringBuilder result = new StringBuilder(); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String address = cursor.getString(cursor.getColumnIndex("address")); String phone = cursor.getString(cursor.getColumnIndex("ph_no")); result.append("ID: ").append(id).append(", Name: ").append(name).append(", Address: ").append(address).append(", Phone: ").append(phone).append("\n"); } tvResult.setText(result.toString()); cursor.close(); } }); } private void insertCustomer(String name, String address, String phone) { ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("address", address); contentValues.put("ph_no", phone); mDatabase.insert("Customer", null, contentValues); } }
  1. Database helper class (CustomerDbHelper.java):
java
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class CustomerDbHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "Customer.db"; private static final int DATABASE_VERSION = 1; public CustomerDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { final String SQL_CREATE_CUSTOMER_TABLE = "CREATE TABLE Customer (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT," + "address TEXT," + "ph_no TEXT);"; db.execSQL(SQL_CREATE_CUSTOMER_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS Customer"); onCreate(db); } }




Slip 9

Create an application that allows the user to enter a number in the textbox named „getnum‟. Check whether the number in the textbox „getnum‟ is Palindrome or not. Print the message accordingly in the label when the user clicks on the button „Check‟.



Sure! Below is an example of an Android application that allows the user to enter a number in a EditText named "getnum", checks whether the entered number is a palindrome or not, and displays the result in a TextView when the user clicks on a Button named "Check":

  1. Layout XML file (activity_main.xml):
xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/getnum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="Enter a number" android:inputType="number" app:layout_constraintBottom_toTopOf="@id/checkButton" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/checkButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Check" app:layout_constraintBottom_toTopOf="@id/resultTextView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> <TextView android:id="@+id/resultTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textSize="20sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/checkButton" /> </androidx.constraintlayout.widget.ConstraintLayout>
  1. Java code for the main activity (MainActivity.java):
java
import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText getnum; Button checkButton; TextView resultTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getnum = findViewById(R.id.getnum); checkButton = findViewById(R.id.checkButton); resultTextView = findViewById(R.id.resultTextView); checkButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkPalindrome(); } }); // Add a TextWatcher to check if the input changes getnum.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Clear the result text view when the input changes resultTextView.setText(""); } @Override public void afterTextChanged(Editable s) {} }); } private void checkPalindrome() { String input = getnum.getText().toString().trim(); if (!TextUtils.isEmpty(input)) { int number = Integer.parseInt(input); if (isPalindrome(number)) { resultTextView.setText(number + " is a palindrome"); } else { resultTextView.setText(number + " is not a palindrome"); } } else { resultTextView.setText("Please enter a number"); } } // Function to check if a number is palindrome or not private boolean isPalindrome(int num) { int originalNum = num; int reversedNum = 0; while (num != 0) { int digit = num % 10; reversedNum = reversedNum * 10 + digit; num /= 10; } return originalNum == reversedNum; } }



 Java android program to create simple calculator


  1. Layout XML file (activity_main.xml):
xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/resultTextView" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:layout_marginBottom="24dp" android:gravity="end" android:text="" android:textSize="24sp" app:layout_constraintBottom_toTopOf="@id/guideline" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.4" /> <GridLayout android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="16dp" android:alignmentMode="alignMargins" android:columnCount="4" android:rowCount="5" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/guideline"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:onClick="onNumberClick" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2" android:onClick="onNumberClick" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="3" android:onClick="onNumberClick" /> <Button android:id="@+id/buttonAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:onClick="onOperatorClick" /> <!-- More buttons for numbers and operators --> <Button android:id="@+id/buttonEquals" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="=" android:onClick="onEqualsClick" android:layout_columnSpan="2" /> <Button android:id="@+id/buttonClear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C" android:onClick="onClearClick" /> </GridLayout> </androidx.constraintlayout.widget.ConstraintLayout>
  1. Java code for the main activity (MainActivity.java):
java
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 resultTextView; private String currentNumber = ""; private double firstOperand = Double.NaN; private String pendingOperator = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); resultTextView = findViewById(R.id.resultTextView); } public void onNumberClick(View view) { String digit = ((Button) view).getText().toString(); currentNumber += digit; updateResultTextView(); } public void onOperatorClick(View view) { String operator = ((Button) view).getText().toString(); if (!currentNumber.isEmpty()) { if (!Double.isNaN(firstOperand)) { calculateResult(); } else { firstOperand = Double.parseDouble(currentNumber); } pendingOperator = operator; currentNumber = ""; updateResultTextView(); } } public void onEqualsClick(View view) { if (!currentNumber.isEmpty() && !Double.isNaN(firstOperand)) { calculateResult(); pendingOperator = ""; } } public void onClearClick(View view) { currentNumber = ""; firstOperand = Double.NaN; pendingOperator = ""; updateResultTextView(); } private void calculateResult() { double secondOperand = Double.parseDouble(currentNumber); double result = Double.NaN; switch (pendingOperator) { case "+": result = firstOperand + secondOperand; break; // Add more cases for other operators } currentNumber = Double.toString(result); firstOperand = result; updateResultTextView(); } private void updateResultTextView() { resultTextView.setText(currentNumber); } }


Slip 10

Create an application that allows the user to enter a number in the textbox named getnum. Check whether the number in the textbox getnum is Armstrong or not. Print the message using Toast control when the user clicks on the button Check


  1. Layout XML file (activity_main.xml):
xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/getnum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="Enter a number" android:inputType="number" app:layout_constraintBottom_toTopOf="@id/checkButton" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/checkButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Check" app:layout_constraintBottom_toTopOf="@id/guideline" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" android:layout_marginTop="16dp" android:onClick="onCheckClick" /> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.4" /> </androidx.constraintlayout.widget.ConstraintLayout>
  1. Java code for the main activity (MainActivity.java):
java
import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private EditText getnum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getnum = findViewById(R.id.getnum); } public void onCheckClick(View view) { String numberStr = getnum.getText().toString().trim(); if (numberStr.isEmpty()) { Toast.makeText(this, "Please enter a number", Toast.LENGTH_SHORT).show(); return; } int number = Integer.parseInt(numberStr); if (isArmstrong(number)) { Toast.makeText(this, number + " is an Armstrong number", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, number + " is not an Armstrong number", Toast.LENGTH_SHORT).show(); } } private boolean isArmstrong(int number) { int originalNumber, remainder, result = 0, n = 0; originalNumber = number; // Count number of digits while (originalNumber != 0) { originalNumber /= 10; ++n; } originalNumber = number; // Calculate result while (originalNumber != 0) { remainder = originalNumber % 10; result += Math.pow(remainder, n); originalNumber /= 10; } return result == number; } }

This application checks whether the entered number in the EditText named "getnum" is an Armstrong number or not when the user clicks on the Button named "Check". A Toast message is displayed to show the result.



Write a program to draw GUI by using Spinner, Buttons.



  1. Layout XML file (activity_main.xml):

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:padding="16dp"

    tools:context=".MainActivity">


    <Spinner

        android:id="@+id/spinner"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:entries="@array/spinner_options" />


    <Button

        android:id="@+id/button1"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Button 1" />


    <Button

        android:id="@+id/button2"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Button 2" />


    <!-- Add more buttons or other views as needed -->


</LinearLayout>




  1. Array resource file (res/values/arrays.xml):


<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string-array name="spinner_options">

        <item>Option 1</item>

        <item>Option 2</item>

        <item>Option 3</item>

        <!-- Add more options as needed -->

    </string-array>

</resources>




  1. Java code for the main activity (MainActivity.java):
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
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);

        Spinner spinner = findViewById(R.id.spinner);
        Button button1 = findViewById(R.id.button1);
        Button button2 = findViewById(R.id.button2);

        // Set up the spinner with options from the string array resource
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.spinner_options, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        // Set up item selection listener for the spinner
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = parent.getItemAtPosition(position).toString();
                Toast.makeText(MainActivity.this, "Selected: " + selectedItem, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });

        // Set up click listeners for the 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();
            }
        });
    }
}


Slip 11

  1. Design the User Interface (XML Layout): Create activity_main.xml layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

    <EditText
        android:id="@+id/editTextNum2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextNum1"
        android:hint="Enter Number 2"
        android:inputType="numberDecimal"/>

    <Button
        android:id="@+id/buttonPower"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextNum2"
        android:layout_marginTop="16dp"
        android:text="Calculate Power"/>

    <Button
        android:id="@+id/buttonAverage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/buttonPower"
        android:layout_marginTop="16dp"
        android:text="Calculate Average"/>

</RelativeLayout>






  1. Implement the Logic (Java Code): Create MainActivity.java file:



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 { EditText editTextNum1, editTextNum2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextNum1 = findViewById(R.id.editTextNum1); editTextNum2 = findViewById(R.id.editTextNum2); Button buttonPower = findViewById(R.id.buttonPower); Button buttonAverage = findViewById(R.id.buttonAverage); buttonPower.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double num1 = Double.parseDouble(editTextNum1.getText().toString()); double num2 = Double.parseDouble(editTextNum2.getText().toString()); double result = Math.pow(num1, num2); openResultActivity(result); } }); buttonAverage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double num1 = Double.parseDouble(editTextNum1.getText().toString()); double num2 = Double.parseDouble(editTextNum2.getText().toString()); double result = (num1 + num2) / 2; openResultActivity(result); } }); } private void openResultActivity(double result) { Intent intent = new Intent(MainActivity.this, ResultActivity.class); intent.putExtra("result", result); startActivity(intent); } }



  1. Create the Result Activity: Create ResultActivity.java file:

import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class ResultActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); TextView textViewResult = findViewById(R.id.textViewResult); double result = getIntent().getDoubleExtra("result", 0); textViewResult.setText("Result: " + result); } }




  1. Create Result Activity Layout: Create activity_result.xml layout file:

<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textViewResult" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:textSize="24sp"/>





Create an Android Application to perform following string operation according to user selection of radio button


  1. Design the User Interface (XML Layout): Create activity_main.xml layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/editTextInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter a string" android:layout_marginTop="20dp"/> <RadioGroup android:id="@+id/radioGroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/editTextInput" android:orientation="vertical"> <RadioButton android:id="@+id/radioButtonReverse" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Reverse String" /> <RadioButton android:id="@+id/radioButtonUpperCase" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Convert to Uppercase" /> <RadioButton android:id="@+id/radioButtonLowerCase" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Convert to Lowercase" /> </RadioGroup> <Button android:id="@+id/buttonApply" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/radioGroup" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:text="Apply Operation"/> <TextView android:id="@+id/textViewResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/buttonApply" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:textSize="20sp" /> </RelativeLayout>




  1. Implement the Logic (Java Code): Create MainActivity.java file:

import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText editTextInput; RadioGroup radioGroup; Button buttonApply; TextView textViewResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextInput = findViewById(R.id.editTextInput); radioGroup = findViewById(R.id.radioGroup); buttonApply = findViewById(R.id.buttonApply); textViewResult = findViewById(R.id.textViewResult); buttonApply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { performOperation(); } }); } private void performOperation() { String input = editTextInput.getText().toString(); int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { // No radio button selected textViewResult.setText("Please select an operation"); return; } RadioButton radioButton = findViewById(selectedId); String operation = radioButton.getText().toString(); switch (operation) { case "Reverse String": textViewResult.setText(reverseString(input)); break; case "Convert to Uppercase": textViewResult.setText(input.toUpperCase()); break; case "Convert to Lowercase": textViewResult.setText(input.toLowerCase()); break; default: textViewResult.setText("Invalid operation"); break; } } private String reverseString(String input) { return new StringBuilder(input).reverse().toString(); } }





  1. Run the Application: After creating the layout and the Java code, run the application on an emulator or a real device to see how it works. You should be able to enter a string, select an operation using radio buttons, and see the result displayed below.

This application allows users to input a string and select one of three operations (reverse string, convert to uppercase, or convert to lowercase) using radio buttons. It then displays the result of the selected operation.







Slip 12

Construct an Android app that toggles a light bulb ON and OFF when the user clicks on toggle button.

  1. Design the User Interface (XML Layout): Create activity_main.xml layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="OFF"
        android:textOn="ON"
        android:layout_centerInParent="true"/>

    <ImageView
        android:id="@+id/imageViewBulb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/toggleButton"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:src="@drawable/ic_light_off"/>

</RelativeLayout>




  1. Implement the Logic (Java Code): Create MainActivity.java file:

import android.os.Bundle; import android.view.View; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ToggleButton; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ImageView imageViewBulb; ToggleButton toggleButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageViewBulb = findViewById(R.id.imageViewBulb); toggleButton = findViewById(R.id.toggleButton); toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // Toggle is ON imageViewBulb.setImageResource(R.drawable.ic_light_on); } else { // Toggle is OFF imageViewBulb.setImageResource(R.drawable.ic_light_off); } } }); } }




  1. Design the User Interface (XML Layout): Create activity_main.xml layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="16dp"/>

    <RadioGroup
        android:id="@+id/radioGroupFormat"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextName"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

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

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

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

    </RadioGroup>

    <CheckBox
        android:id="@+id/checkBoxColor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change color"
        android:layout_below="@id/radioGroupFormat"
        android:layout_marginTop="20dp"
        android:layout_marginHorizontal="16dp"/>

    <Button
        android:id="@+id/buttonDisplayMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Message"
        android:layout_below="@id/checkBoxColor"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"/>

    <Button
        android:id="@+id/buttonClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear"
        android:layout_below="@id/buttonDisplayMessage"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="16dp"
        android:layout_alignParentEnd="true"/>

    <Button
        android:id="@+id/buttonExit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Exit"
        android:layout_below="@id/buttonDisplayMessage"
        android:layout_marginTop="20dp"
        android:layout_marginStart="16dp"
        android:layout_alignParentStart="true"/>

    <TextView
        android:id="@+id/textViewMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/buttonDisplayMessage"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:textSize="20sp"/>

</RelativeLayout>



  1. Implement the Logic (Java Code): Create MainActivity.java file:

import android.graphics.Color;

import android.os.Bundle;

import android.text.SpannableString;

import android.text.Spanned;

import android.text.style.ForegroundColorSpan;

import android.text.style.StyleSpan;

import android.text.style.UnderlineSpan;

import android.view.View;

import android.widget.Button;

import android.widget.CheckBox;

import android.widget.EditText;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.TextView;


import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {


    EditText editTextName;

    RadioGroup radioGroupFormat;

    RadioButton radioButtonBold, radioButtonItalic, radioButtonUnderline;

    CheckBox checkBoxColor;

    Button buttonDisplayMessage, buttonClear, buttonExit;

    TextView textViewMessage;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        editTextName = findViewById(R.id.editTextName);

        radioGroupFormat = findViewById(R.id.radioGroupFormat);

        radioButtonBold = findViewById(R.id.radioButtonBold);

        radioButtonItalic = findViewById(R.id.radioButtonItalic);

        radioButtonUnderline = findViewById(R.id.radioButtonUnderline);

        checkBoxColor = findViewById(R.id.checkBoxColor);

        buttonDisplayMessage = findViewById(R.id.buttonDisplayMessage);

        buttonClear = findViewById(R.id.buttonClear);

        buttonExit = findViewById(R.id.buttonExit);

        textViewMessage = findViewById(R.id.textViewMessage);


        buttonDisplayMessage.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                displayMessage();

            }

        });


        buttonClear.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                clearInputs();

            }

        });


        buttonExit.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                finish(); // Close the app

            }

        });

    }


    private void displayMessage() {

        String name = editTextName.getText().toString();

        SpannableString formattedText = new SpannableString(name);


        // Apply formatting based on radio button selection

        if (radioButtonBold.isChecked()) {

            formattedText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        if (radioButtonItalic.isChecked()) {

            formattedText.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        if (radioButtonUnderline.isChecked()) {

            formattedText.setSpan(new UnderlineSpan(), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }


        // Apply color if checkbox is checked

        if (checkBoxColor.isChecked()) {

            formattedText.setSpan(new ForegroundColorSpan(Color.RED), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }


        textViewMessage.setText(formattedText);

    }


    private void clearInputs() {

        editTextName.getText().clear();

        textViewMessage.setText("");

    }

}









Slip 13


Java android program to demonstrate Registration form with validation


  1. Design the User Interface (XML Layout): Create activity_registration.xml layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".RegistrationActivity">

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

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextName"
        android:layout_marginTop="16dp"
        android:hint="Email"/>

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

    <Button
        android:id="@+id/buttonRegister"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextPassword"
        android:layout_marginTop="24dp"
        android:text="Register"/>

</RelativeLayout>



  1. Implement the Logic (Java Code): Create RegistrationActivity.java file:

import android.os.Bundle; 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 RegistrationActivity extends AppCompatActivity { EditText editTextName, editTextEmail, editTextPassword; Button buttonRegister; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); editTextName = findViewById(R.id.editTextName); editTextEmail = findViewById(R.id.editTextEmail); editTextPassword = findViewById(R.id.editTextPassword); buttonRegister = findViewById(R.id.buttonRegister); buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registerUser(); } }); } private void registerUser() { String name = editTextName.getText().toString().trim(); String email = editTextEmail.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); if (name.isEmpty()) { editTextName.setError("Name is required"); editTextName.requestFocus(); return; } if (email.isEmpty()) { editTextEmail.setError("Email is required"); editTextEmail.requestFocus(); return; } if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { editTextEmail.setError("Please enter a valid email"); editTextEmail.requestFocus(); return; } if (password.isEmpty()) { editTextPassword.setError("Password is required"); editTextPassword.requestFocus(); return; } if (password.length() < 6) { editTextPassword.setError("Password should be at least 6 characters long"); editTextPassword.requestFocus(); return; } // Here, you can write code to register the user (e.g., send data to server or store locally) // For demonstration, just showing a Toast message Toast.makeText(this, "Registration successful", Toast.LENGTH_SHORT).show(); } }





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

  1. Create the Layout (XML): Create activity_main.xml layout file:

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter item to add" android:layout_margin="16dp" android:imeOptions="actionDone"/> <Button android:id="@+id/btnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/editText" android:layout_centerHorizontal="true" android:text="Add Item"/> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/btnAdd" android:layout_marginTop="16dp"/> </RelativeLayout>


  1. Create the Adapter: We'll need a custom ArrayAdapter to bind data to the ListView. Create a new Java class named CustomAdapter.java:
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; public class CustomAdapter extends ArrayAdapter<String> { private ArrayList<String> dataSet; private Context mContext; private static class ViewHolder { TextView textView; } public CustomAdapter(ArrayList<String> data, Context context) { super(context, R.layout.item_row, data); this.dataSet = data; this.mContext = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { String dataModel = getItem(position); ViewHolder viewHolder; final View result; if (convertView == null) { viewHolder = new ViewHolder(); LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(R.layout.item_row, parent, false); viewHolder.textView = convertView.findViewById(R.id.textView); result = convertView; convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); result = convertView; } viewHolder.textView.setText(dataModel); return result; } }


  1. Create the Item Row Layout: Create item_row.xml layout file under the res/layout directory:
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp"/>


  1. Implement the Logic: Now, in your MainActivity.java, you can implement the logic for adding, deleting, and searching items:

import android.os.Bundle; import android.view.View; 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; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { EditText editText; Button btnAdd; ListView listView; ArrayList<String> arrayList; ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.editText); btnAdd = findViewById(R.id.btnAdd); listView = findViewById(R.id.listView); arrayList = new ArrayList<>(); adapter = new CustomAdapter(arrayList, this); listView.setAdapter(adapter); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String item = editText.getText().toString(); if (!item.isEmpty()) { arrayList.add(item); adapter.notifyDataSetChanged(); editText.getText().clear(); } else { Toast.makeText(MainActivity.this, "Please enter an item", Toast.LENGTH_SHORT).show(); } } }); } }





Slip 14


Construct an Android application to accept a number and calculate and display Factorial of a given number in TextView.


  1. Design the User Interface (XML Layout): Create activity_main.xml layout file:

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">


    <EditText

        android:id="@+id/editTextNumber"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Enter a number"

        android:inputType="number"/>


    <Button

        android:id="@+id/buttonCalculate"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/editTextNumber"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="16dp"

        android:text="Calculate Factorial"/>


    <TextView

        android:id="@+id/textViewResult"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/buttonCalculate"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="16dp"

        android:textSize="18sp"/>


</RelativeLayout>






  1. Implement the Logic (Java Code): Create MainActivity.java file:
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.math.BigInteger;

public class MainActivity extends AppCompatActivity {

    EditText editTextNumber;
    Button buttonCalculate;
    TextView textViewResult;

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

        editTextNumber = findViewById(R.id.editTextNumber);
        buttonCalculate = findViewById(R.id.buttonCalculate);
        textViewResult = findViewById(R.id.textViewResult);

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

    private void calculateFactorial() {
        String input = editTextNumber.getText().toString().trim();

        if (input.isEmpty()) {
            textViewResult.setText("Please enter a number");
            return;
        }

        int number = Integer.parseInt(input);

        if (number < 0) {
            textViewResult.setText("Factorial is not defined for negative numbers");
            return;
        }

        BigInteger factorial = BigInteger.ONE;
        for (int i = 1; i <= number; i++) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }

        textViewResult.setText("Factorial of " + number + " is:\n" + factorial.toString());
    }
}



2. Create an Android application, which show Login Form. After clicking LOGIN button display the “Login Successful…” message if username and password is same else display “Invalid Login” message in Toast Control

  1. Design the User Interface (XML Layout): Create activity_main.xml layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/editTextUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Username" android:inputType="text"/> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/editTextUsername" android:layout_margin="16dp" android:hint="Password" android:inputType="textPassword"/> <Button android:id="@+id/buttonLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/editTextPassword" android:layout_centerHorizontal="true" android:layout_marginTop="24dp" android:text="LOGIN"/> </RelativeLayout>


  1. Implement the Logic (Java Code): Create MainActivity.java file:

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 editTextUsername, editTextPassword; Button buttonLogin; // Predefined username and password private static final String USERNAME = "user"; private static final String PASSWORD = "password"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextUsername = findViewById(R.id.editTextUsername); editTextPassword = findViewById(R.id.editTextPassword); buttonLogin = findViewById(R.id.buttonLogin); buttonLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { login(); } }); } private void login() { String username = editTextUsername.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); if (username.equals(USERNAME) && password.equals(PASSWORD)) { showToast("Login Successful"); } else { showToast("Invalid Login"); } } private void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }






Slip 15


Slip 16

Slip 17


Slip 18

Slip 19


Slip 20


Slip 21

Slip 22



Slip 23


Slip 24


Slip 25




Slip 26



Slip 27


Slip 28



Slip 29


Slip 30



Comments

Popular posts from this blog

Practical slips programs : Machine Learning

Full Stack Developement Practical Slips Programs