0% found this document useful (0 votes)
21 views

Lab 2

Uploaded by

carterwes92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Lab 2

Uploaded by

carterwes92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1.

Android Programming Lab Session (Java): Building a Simple Counter App

Lab Overview:

In this lab session, students will build a simple Counter App using Java in Android Studio. The
app will have a button, and every time the button is clicked, the counter will increment by one,
and the updated count will be displayed on the screen. This exercise is designed for beginners
and assumes that students have already created a "Hello World" app.

Objective:

 Understand the basics of UI components (TextView and Button).


 Learn how to use event listeners (OnClickListener) to respond to user actions.
 Practice working with variables and updating the UI dynamically.

Step-by-Step Instructions:

Step 1: Create a New Project

1. Open Android Studio and click on "New Project".


2. Select "Empty Activity" and click Next.
3. Name the project: CounterApp.
4. Set the Language to Java.
5. Click Finish.

Step 2: Modify the Layout (activity_main.xml)

 Navigate to the res/layout/activity_main.xml file. This file defines the User


Interface (UI) of your app.

1. Open activity_main.xml:
o Replace the default content with the following XML code. This creates a layout
with a TextView to display the counter and a Button to increment it.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<!-- TextView to display the counter value -->


<TextView
android:id="@+id/textViewCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

1|Page
android:text="Counter: 0"
android:textSize="30sp"
android:layout_marginBottom="20dp"/>

<!-- Button to increment the counter -->


<Button
android:id="@+id/buttonIncrement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Increment Counter"
android:textSize="18sp"/>
</LinearLayout>

Explanation:

 The LinearLayout arranges the UI components (TextView and Button) in a vertical


manner.
 The TextView with id=textViewCounter will display the current value of the counter.
 The Button with id=buttonIncrement will be used to increment the counter when
clicked.

Step 3: Modify the MainActivity.java File

 Open the MainActivity.java file. This is where the logic of your app will be
implemented.

1. Open MainActivity.java and add the following code inside the onCreate() method:

package com.example.counterapp;

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

public class MainActivity extends AppCompatActivity {

// Declare a variable to hold the counter value


private int counter = 0;

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

// Link the TextView and Button from the layout


TextView textViewCounter = findViewById(R.id.textViewCounter);
Button buttonIncrement = findViewById(R.id.buttonIncrement);

2|Page
// Set an OnClickListener on the button to respond to user clicks
buttonIncrement.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Increment the counter variable
counter++;

// Update the TextView with the new counter value


textViewCounter.setText("Counter: " + counter);
}
});
}
}

Explanation:

 Counter Variable: The integer counter keeps track of how many times the button has
been clicked.
 TextView and Button: We use findViewById() to get references to the TextView and
Button defined in the layout XML file.
 OnClickListener: We attach an OnClickListener to the button, which is triggered
whenever the button is clicked. Inside the listener, the counter is incremented, and the
TextView is updated with the new value.

Step 4: Build and Run the App

1. Connect an Emulator or a Physical Device:


o If using an emulator, make sure you have one running. If using a physical device,
ensure it's connected and USB debugging is enabled.
2. Build the Project:
o Click on Build > Make Project (or use the shortcut Ctrl+F9) to build the app
and check for errors.
3. Run the App:
o Click on the Run button (green play icon), or use Shift+F10 to run the app on the
connected emulator or device.

Step 5: Testing the App

1. Launch the App on the emulator or your device.


2. Click the Button labeled "Increment Counter". Each click should increase the number
displayed in the TextView by one.
3. Observe how the counter updates every time the button is clicked.

3|Page
Summary of Concepts Covered:

1. UI Components:
o TextView: Used to display text (the counter value).
o Button: Used to allow user interaction (incrementing the counter).
2. Event Handling:
o OnClickListener: Responds to button clicks and updates the counter value.
3. Java Logic:
o Variables: We used an int variable (counter) to store the current count.
o Updating the UI: We dynamically changed the TextView text using setText()
to show the updated counter.

Further Exploration:

After completing this lab, students can try:

 Adding a "Reset" button to reset the counter to zero.


 Modifying the app to include decrement functionality.
 Customizing the UI with different styles and colors.

This lab provides a simple yet practical introduction to handling user input and updating the UI
dynamically in Android apps using Java.

4|Page
2. Android Programming Lab Session (Java): Building a Simple Calculator App

Lab Overview:

In this lab, students will create a basic Calculator App using Java in Android Studio. The app
will allow users to perform simple arithmetic operations (addition, subtraction, multiplication,
and division) between two numbers. This exercise is designed for beginners and builds upon
their knowledge from the "Hello World" and Counter app projects.

Objective:

 Familiarize students with UI components like EditText, Button, and TextView.


 Learn how to handle user input and display output.
 Understand the basics of event listeners and performing simple calculations.

Step-by-Step Instructions:

Step 1: Create a New Project

1. Open Android Studio and click on "New Project".


2. Select "Empty Activity" and click Next.
3. Name the project: CalculatorApp.
4. Set the Language to Java.
5. Click Finish.

Step 2: Modify the Layout (activity_main.xml)

 Navigate to the res/layout/activity_main.xml file. This is where you'll define the


layout of your calculator (two input fields, four buttons for the operations, and a
TextView for displaying the result).

1. Open activity_main.xml and replace the default content with the following code:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">

<!-- Input field for first number -->


<EditText
android:id="@+id/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"

5|Page
android:hint="Enter First Number"
android:inputType="numberDecimal"/>

<!-- Input field for second number -->


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

<!-- Buttons for different operations -->


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginTop="20dp">

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

<Button
android:id="@+id/buttonSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subtract"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiply"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Divide"
android:layout_marginStart="10dp"/>

</LinearLayout>

<!-- TextView to display the result -->


<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result: "
android:textSize="18sp"
android:layout_marginTop="30dp"/>

6|Page
</LinearLayout>

Explanation:

 EditText: Used to take input from the user. The inputType="numberDecimal" ensures
that only numbers can be entered.
 Button: Four buttons (Add, Subtract, Multiply, Divide) to perform arithmetic
operations.
 TextView: Displays the result after the user presses one of the operation buttons.

Step 3: Modify the MainActivity.java File

1. Open MainActivity.java and add the following code to handle the calculator logic:

package com.example.calculatorapp;

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;

public class MainActivity extends AppCompatActivity {

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

// Link UI components from the layout to the Java code


EditText editTextNumber1 = findViewById(R.id.editTextNumber1);
EditText editTextNumber2 = findViewById(R.id.editTextNumber2);
Button buttonAdd = findViewById(R.id.buttonAdd);
Button buttonSubtract = findViewById(R.id.buttonSubtract);
Button buttonMultiply = findViewById(R.id.buttonMultiply);
Button buttonDivide = findViewById(R.id.buttonDivide);
TextView textViewResult = findViewById(R.id.textViewResult);

// Set OnClickListener for the Add button


buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the input numbers
double number1 =
Double.parseDouble(editTextNumber1.getText().toString());
double number2 =
Double.parseDouble(editTextNumber2.getText().toString());

// Calculate the result (addition)

7|Page
double result = number1 + number2;

// Display the result in the TextView


textViewResult.setText("Result: " + result);
}
});

// Set OnClickListener for the Subtract button


buttonSubtract.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double number1 =
Double.parseDouble(editTextNumber1.getText().toString());
double number2 =
Double.parseDouble(editTextNumber2.getText().toString());
double result = number1 - number2;
textViewResult.setText("Result: " + result);
}
});

// Set OnClickListener for the Multiply button


buttonMultiply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double number1 =
Double.parseDouble(editTextNumber1.getText().toString());
double number2 =
Double.parseDouble(editTextNumber2.getText().toString());
double result = number1 * number2;
textViewResult.setText("Result: " + result);
}
});

// Set OnClickListener for the Divide button


buttonDivide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double number1 =
Double.parseDouble(editTextNumber1.getText().toString());
double number2 =
Double.parseDouble(editTextNumber2.getText().toString());

// Check for division by zero


if (number2 != 0) {
double result = number1 / number2;
textViewResult.setText("Result: " + result);
} else {
textViewResult.setText("Error: Division by zero");
}
}
});
}
}

Explanation:

8|Page
 EditText Parsing: We use Double.parseDouble() to convert the text input from
EditText fields into double values for calculation.
 Button Click Events: Each button has an OnClickListener that defines the action when
clicked. For example, the Add button adds two numbers and updates the TextView to
show the result.
 Division Error Handling: The division operation includes a check to prevent division by
zero, which would otherwise cause a runtime error.

Step 4: Build and Run the App

1. Connect an Emulator or Device:


o Ensure your emulator is running or your device is connected (with USB
debugging enabled).
2. Build the Project:
o Click on Build > Make Project or use the shortcut Ctrl+F9 to compile the
project and check for errors.
3. Run the App:
o Click the Run button (green play icon) or press Shift+F10 to launch the app on
the emulator or device.

Step 5: Testing the App

1. Launch the App on your emulator or device.


2. Enter two numbers in the input fields.
3. Press one of the buttons (Add, Subtract, Multiply, or Divide).
4. The result will be displayed below the buttons in the TextView.

Summary of Concepts Covered:

1. UI Components:
o EditText: To take numerical input from the user.
o Button: To trigger arithmetic operations.
o TextView: To display the result.
2. Event Handling:
o We used OnClickListener to handle user interactions (button clicks).
3. User Input & Output:
o EditText values were converted to double for mathematical calculations, and the
result was displayed dynamically in the TextView.
4. Error Handling:
o We demonstrated basic error handling by preventing

9|Page
3. Android Programming Lab Session (Java): Extending the Calculator with
Memory Functions

Lab Overview:

In this lab session, students will extend their existing calculator app by adding memory
functions (M+, M-, MC, MR). These memory functions will allow users to store and recall a
value in memory, clear the memory, and add/subtract the current result to/from memory. This
exercise is designed as a follow-up to the basic calculator app (example 2).

Objective:

 Learn to manage persistent data using memory in a simple way.


 Enhance knowledge of UI components like Buttons and TextView.
 Understand how to use global variables to store data.
 Implement multiple event listeners.

Step-by-Step Instructions:

Step 1: Modify the Layout (activity_main.xml)

 Open the activity_main.xml file and update the UI to include memory function
buttons (M+, M-, MC, MR). Below the arithmetic operation buttons, we will add a row
of memory function buttons.

1. Replace your existing activity_main.xml file with the following code:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">

<!-- Input field for first number -->


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

<!-- Input field for second number -->


<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"

10 | P a g e
android:hint="Enter Second Number"
android:inputType="numberDecimal"
android:layout_marginTop="10dp"/>

<!-- Buttons for basic arithmetic operations -->


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginTop="20dp">

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

<Button
android:id="@+id/buttonSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subtract"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiply"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Divide"
android:layout_marginStart="10dp"/>

</LinearLayout>

<!-- Buttons for memory functions -->


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginTop="20dp">

<Button
android:id="@+id/buttonMC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MC"/>

<Button
android:id="@+id/buttonMR"

11 | P a g e
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MR"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonMPlus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M+"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonMMinus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M-"
android:layout_marginStart="10dp"/>

</LinearLayout>

<!-- TextView to display the result -->


<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result: "
android:textSize="18sp"
android:layout_marginTop="30dp"/>

</LinearLayout>

Explanation:

 In addition to the original buttons, we’ve added a new row of buttons for memory
functions (M+, M-, MC, MR):
o M+: Adds the current result to the memory.
o M-: Subtracts the current result from the memory.
o MC: Clears the memory.
o MR: Recalls the memory value and displays it as the result.

Step 2: Modify the MainActivity.java File

1. Open MainActivity.java and modify the Java code to implement memory


functionality.

package com.example.calculatorapp;

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

12 | P a g e
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

// Variable to store the memory value


double memoryValue = 0;

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

// Link UI components from the layout to the Java code


EditText editTextNumber1 = findViewById(R.id.editTextNumber1);
EditText editTextNumber2 = findViewById(R.id.editTextNumber2);
Button buttonAdd = findViewById(R.id.buttonAdd);
Button buttonSubtract = findViewById(R.id.buttonSubtract);
Button buttonMultiply = findViewById(R.id.buttonMultiply);
Button buttonDivide = findViewById(R.id.buttonDivide);
Button buttonMC = findViewById(R.id.buttonMC);
Button buttonMR = findViewById(R.id.buttonMR);
Button buttonMPlus = findViewById(R.id.buttonMPlus);
Button buttonMMinus = findViewById(R.id.buttonMMinus);
TextView textViewResult = findViewById(R.id.textViewResult);

// Event listener for basic arithmetic operations (Add)


buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double number1 =
Double.parseDouble(editTextNumber1.getText().toString());
double number2 =
Double.parseDouble(editTextNumber2.getText().toString());
double result = number1 + number2;
textViewResult.setText("Result: " + result);
}
});

// Other arithmetic operations (Subtract, Multiply, Divide) here


(similar to previous code)

// Event listener for memory functions

// MC: Memory Clear


buttonMC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
memoryValue = 0; // Clear memory
textViewResult.setText("Memory Cleared");
}
});

// MR: Memory Recall


buttonMR.setOnClickListener(new View.OnClickListener() {
@Override

13 | P a g e
public void onClick(View v) {
textViewResult.setText("Result: " + memoryValue); // Recall
and display memory value
}
});

// M+: Memory Add


buttonMPlus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double result =
Double.parseDouble(textViewResult.getText().toString().replace("Result: ",
""));
memoryValue += result; // Add result to memory
textViewResult.setText("Result: " + result + " (Added to
Memory)");
}
});

// M-: Memory Subtract


buttonMMinus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double result =
Double.parseDouble(textViewResult.getText().toString().replace("Result: ",
""));
memoryValue -= result; // Subtract result from memory
textViewResult.setText("Result: " + result + " (Subtracted
from Memory)");
}
});
}
}

Explanation:

 Memory Variables: We declare a global variable memoryValue to store the memory


value. This value will persist between calculations until the user clears it with the MC
button.
 Event Listeners:
o MC: Clears the memory by setting memoryValue to 0.
o MR: Recalls the memory value and displays it in the TextView.
o M+: Adds the current result to memoryValue.
o M-: Subtracts the current result from memoryValue.

Step 3: Build and Run the App

1. Connect an Emulator or Device:


o Ensure your emulator is running or your device is connected with USB debugging
enabled.

14 | P a g e
2. Build the Project:
o Click on Build > Make Project or use the shortcut Ctrl + F9.
3. Run the App:
o Click on the Run button or use the shortcut Shift + F10.
4. Test the Memory Functions:
o Enter two numbers and perform basic arithmetic operations.
o Use the memory buttons (M+, M-, MC, MR) to store, recall, and manipulate the
memory value.

Expected Output:

 The app should allow users to perform standard arithmetic calculations as before.
 In addition, users should be able to:
o Store a value in memory with M+ and M-.
o Recall the stored value with MR.
o Clear the memory with MC.

Conclusion:

In this lab exercise, you have extended the calculator app with useful memory functions. This
introduces the concept of global variables, allows you to manage state between calculations, and
provides more interactive functionality to the calculator app.

15 | P a g e
4. Android Programming Lab Session (Java): Adding a History Feature to the
Calculator App

Lab Overview:

In this lab session, students will extend the existing calculator app by adding a history feature.
This feature will keep track of the user's past calculations and display them in a list format. The
calculations will be displayed in a new activity, allowing students to practice using multiple
activities, passing data between activities, and displaying lists in Android.

Objective:

 Learn how to implement multiple activities in an Android app.


 Pass data between activities using Intents.
 Display a list of items using a ListView.
 Continue improving your understanding of Android UI components.

Step-by-Step Instructions:

Step 1: Modify the Layout (activity_main.xml)

1. In the activity_main.xml file, add a new button to view the calculation history. Below
the memory function buttons, add a button labeled "View History."

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">

<!-- Input field for first number -->


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

<!-- Input field for second number -->


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

16 | P a g e
<!-- Buttons for basic arithmetic operations -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginTop="20dp">

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

<Button
android:id="@+id/buttonSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subtract"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiply"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Divide"
android:layout_marginStart="10dp"/>

</LinearLayout>

<!-- Buttons for memory functions -->


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginTop="20dp">

<Button
android:id="@+id/buttonMC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MC"/>

<Button
android:id="@+id/buttonMR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MR"

17 | P a g e
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonMPlus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M+"
android:layout_marginStart="10dp"/>

<Button
android:id="@+id/buttonMMinus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="M-"
android:layout_marginStart="10dp"/>

</LinearLayout>

<!-- TextView to display the result -->


<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result: "
android:textSize="18sp"
android:layout_marginTop="30dp"/>

<!-- Button to view calculation history -->


<Button
android:id="@+id/buttonHistory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View History"
android:layout_marginTop="20dp"/>

</LinearLayout>

Explanation:

 We've added a "View History" button to the bottom of the layout. When clicked, it will
open a new screen (activity) showing a list of previous calculations.

Step 2: Create a New Activity for Viewing History

1. Create a new Activity:


o Right-click on your app > java > com.example.calculatorapp folder, select
New > Activity > Empty Activity, and name it HistoryActivity.
2. Modify the layout (activity_history.xml):
o In the new activity_history.xml file, add a ListView to display the history of
calculations.

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

<!-- ListView to display the calculation history -->


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

</LinearLayout>

Explanation:

 The ListView will be used to display a list of past calculations stored during the app's
use.

Step 3: Update MainActivity.java to Pass Data

1. Modify MainActivity.java to save calculations to an ArrayList and pass this list to


the new HistoryActivity.

package com.example.calculatorapp;

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

public class MainActivity extends AppCompatActivity {

// Variable to store the memory value and history


double memoryValue = 0;
ArrayList<String> calculationHistory = new ArrayList<>();

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

// Link UI components
EditText editTextNumber1 = findViewById(R.id.editTextNumber1);
EditText editTextNumber2 = findViewById(R.id.editTextNumber2);
Button buttonAdd = findViewById(R.id.buttonAdd);
Button buttonHistory = findViewById(R.id.buttonHistory);

19 | P a g e
TextView textViewResult = findViewById(R.id.textViewResult);

// Event listener for adding numbers


buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double number1 =
Double.parseDouble(editTextNumber1.getText().toString());
double number2 =
Double.parseDouble(editTextNumber2.getText().toString());
double result = number1 + number2;
String calculation = number1 + " + " + number2 + " = " +
result;
calculationHistory.add(calculation);
textViewResult.setText("Result: " + result);
}
});

// Event listener for viewing calculation history


buttonHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
HistoryActivity.class);
intent.putStringArrayListExtra("history",
calculationHistory);
startActivity(intent);
}
});
}
}

Explanation:

 ArrayList<String> calculationHistory : This stores each calculation as a string in a


list.
 When a calculation is performed, it's added to the calculationHistory list.
 When the "View History" button is clicked, an Intent is used to open the
HistoryActivity, and the history list is passed to the new activity.

Step 4: Update HistoryActivity.java to Display History

1. Modify HistoryActivity.java to receive the list of calculations and display them in


the ListView.

package com.example.calculatorapp;

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

20 | P a g e
import java.util.ArrayList;

public class HistoryActivity extends AppCompatActivity {

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

// Get the passed calculation history from the Intent


ArrayList<String> calculationHistory =
getIntent().getStringArrayListExtra("history");

// Link the ListView and display the history


ListView listViewHistory = findViewById(R.id.listViewHistory);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, calculationHistory);
listViewHistory.setAdapter(adapter);
}
}

Explanation:

 The history is passed as an ArrayList<String> via the Intent.


 An ArrayAdapter is used to populate the ListView with the list of past calculations.

Step 5: Run and Test the App

1. Run the app:


o Click the Run button or use the shortcut Shift + F10 to start the emulator.
2. Test the history feature:
o Perform a few calculations using the calculator app.
o Click the "View History" button to see a list of your past calculations displayed in
a new screen.

Expected Output:

 The app should now allow the user to:


o Perform basic arithmetic operations.
o View the history of previous calculations in a new activity.

Conclusion:

21 | P a g e
In this lab, you've extended the calculator app by adding a history feature that displays past
calculations. You learned how to create multiple activities, pass data between them using
Intents, and display lists with a ListView. This exercise introduces important concepts like state
management and data persistence, which are essential in Android development.

22 | P a g e
5. Android Programming Lab Session (Java): Creating a Simple To-Do List
App

Lab Overview:

In this lab session, students will create a simple To-Do List app. This exercise will teach
students how to handle user input, manage a dynamic list of items, and work with ListView to
display data. The focus is on developing skills in managing user interaction, storing items in a
list, and using ArrayAdapter to populate the list.

Objective:

 Understand how to handle user input through EditText and Buttons.


 Learn how to dynamically add items to a list and display them using ListView.
 Develop a basic understanding of using ArrayAdapter to manage lists.

Step-by-Step Instructions:

Step 1: Design the Layout (activity_main.xml)

1. Open the res/layout/activity_main.xml file.


2. Add the necessary UI elements for the app, such as:
o An EditText for inputting the to-do items.
o A Button to add the inputted item to the list.
o A ListView to display the list of to-do items.

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


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

<!-- EditText to input the to-do item -->


<EditText
android:id="@+id/editTextTask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a new task"
android:inputType="text"
android:layout_marginBottom="10dp"/>

<!-- Button to add the task to the list -->


<Button
android:id="@+id/buttonAddTask"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Task"

23 | P a g e
android:layout_gravity="center_horizontal"/>

<!-- ListView to display the list of tasks -->


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

</LinearLayout>

Explanation:

 EditText: Allows the user to input text that represents a task.


 Button: When clicked, it will add the task to the list.
 ListView: Displays the list of tasks entered by the user.

Step 2: Set up the MainActivity (MainActivity.java)

1. Open the MainActivity.java file.


2. Write the Java code to handle user interaction, adding tasks to the list, and updating the
ListView.

package com.example.todolistapp;

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 androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

// List to store the tasks


ArrayList<String> taskList;
ArrayAdapter<String> adapter;

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

// Link UI components
EditText editTextTask = findViewById(R.id.editTextTask);
Button buttonAddTask = findViewById(R.id.buttonAddTask);
ListView listViewTasks = findViewById(R.id.listViewTasks);

// Initialize the task list and adapter

24 | P a g e
taskList = new ArrayList<>();
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, taskList);
listViewTasks.setAdapter(adapter);

// Event listener for the Add Task button


buttonAddTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the task from the EditText
String task = editTextTask.getText().toString();

// Check if input is not empty


if (!task.isEmpty()) {
// Add the task to the list and notify the adapter
taskList.add(task);
adapter.notifyDataSetChanged();

// Clear the EditText for the next task


editTextTask.setText("");
}
}
});
}
}

Explanation:

 taskList: An ArrayList used to store the to-do tasks.


 ArrayAdapter: Binds the ArrayList of tasks to the ListView.
 EditText: Captures user input, which is added to the taskList when the Button is
clicked.
 notifyDataSetChanged(): Refreshes the ListView when a new task is added.

Step 3: Run the App

1. Build the app: Click on the Build menu and select Make Project or press Ctrl + F9.
2. Run the app: Click the Run button or press Shift + F10 to launch the app on an
emulator or physical device.

Expected Output:

 The app allows users to:


o Enter a task in the input field.
o Click the Add Task button to add the task to the list.
o View all added tasks in the ListView.
o The input field should be cleared after each task is added.

25 | P a g e
Conclusion:

In this lab, you created a simple To-Do List app that allows users to add tasks to a list and view
them dynamically. This exercise introduced key concepts such as handling user input with
EditText, updating UI components with ArrayAdapter, and dynamically managing a list of
items.

This concludes Lab 2 of your Android Java programming course.

26 | P a g e

You might also like