You are on page 1of 36

Practical Journal on

Android Programming
PRN
2020017001761336
T.Y.B.C.A.
(SEM VI)
Student Name
Suraj Dayashankar Pal
Academic Year
(2022-23)
College
L.N. College of Management & Technology
University
Yashwantrao Chavan Maharashtra Open
University

1
Yashwantrao Chavan Maharashtra Open University
DnyaGangotri, Govardhan, Near Gangapur Dam, Nashik - 422222

School of Computer Science


(Bachelor of Computer Application)
Study Centre: LN College of Management and Technology [31272]

B.C.A P131
Session: May 2023
Class: - T.Y.B.C.A. (Semester – VI)
Subject: - Android Programming
Name: - Suraj Dayashankar Pal
P.R.N No: - 2020017001761336
Academic Year: - 2022-23 (May)

_________________ __________________ ________________


Subject Teacher External Examiner Principal

2
LN COLLEGE OF MANAGEMENT AND TECHNOLOGY
CLASS: - T.Y.B.C.A.
ACADEMIC YEAR: - 2022-23
P.R.N No: -2020017001761336
This certificate serves as confirmation that Suraj Dayashankar Pal has
successfully completed the Android Programming Semester VI - Practical
as part of his T.Y.B.C.A. coursework for the academic year 2022-23. The
practical work has been reviewed and evaluated by the subject teacher and external
examiner, meeting all academic standards and requirements.

________________ ___________________ ________________


Subject Teacher External Examiner Principal

3
INDEX
Practical No. Practical Name Page. No

1. Create an application with following functionalities: Print and show a simple 5


message e.g., Hello Word

2. Android button & Toggle button from this create application 6

3. Use of Toast & Custom Toast creates android application. 8

4. Create Android application using CheckBox & AlertDiaglogBox 10

5. Create Android application using Spinner & Auto complete test view 13

6. Create an application with following functionalities: Calculator for Basic 15


mathematical operations.

7. Create Android application using Rating Bar, Web view, Seek Bar 18

8. Design an android application for “Registration Form” using different layout 20


such as table layout, linear layout etc. Use Drawable Resources, option menu,
List Views and Adapters.
9. Create Android application using Date picker & Time Picker 24

10. Create Android application using Progress Bar, Implicit Intend 27

11. Create Android application using fragments 30

12. Design and Implement a Registration Form using SQLite Database. 33

PRACTICAL NO. 1
4
AIM: Create an application with following functionalities: Print and show
a simple message e.g., Hello Word
Solution)
Step 1: Open Android Studio and create a new project by selecting "Empty Activity" template.
Step 2: Choose a name and location for your project and click "Finish".
Step 3: In the MainActivity.java file, add the following code in the onCreate() method:

MainActivity.java
package com.example.helloworld;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

// Print "Hello World" to the console


System.out.println("Hello World");

// Show "Hello World" in a toast message


Toast.makeText(getApplicationContext(), "Hello World", Toast.LENGTH_SHORT).show();
}
}
activity_main.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/hello_world_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />

</androidx.constraintlayout.widget.ConstraintLayout>

5
Output:

PRACTICAL NO. 2
AIM: Android button & Toggle button from this create application
SOLUTION)
MainActivity.java
package com.example.button;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

6
public class MainActivity extends AppCompatActivity {

private Button button;


private ToggleButton toggleButton;

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

button = findViewById(R.id.button);
toggleButton = findViewById(R.id.toggleButton);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Button clicked!",
Toast.LENGTH_SHORT).show();
}
});

toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
Toast.makeText(getApplicationContext(), "Toggle on!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Toggle off!",
Toast.LENGTH_SHORT).show();
}
}
});
}
}

activity_main.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">

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

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:layout_centerInParent="true"/>

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle me!"
android:layout_below="@id/button"
android:layout_centerHorizontal="true"/>
</RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

7
Output:

Button Clicked Toggle on


Toggle Off
PRACTICAL NO. 3
AIM: Use of Toast & Custom Toast creates android application.
SOLUTION)
1. Create a new Android project in Android Studio.
2. Open the activity_main.xml layout file and add a button with the id "btn_show_toast".
<?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">

<Button
android:id="@+id/btn_show_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Custom Toast" />

8
</androidx.constraintlayout.widget.ConstraintLayout>

3. Create a new layout file named "custom_toast.xml" in the "res/layout" folder. This file
will contain the layout for the custom toast.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:background="#ff5722"
android:orientation="horizontal">

<ImageView
android:id="@+id/toast_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_info"
android:layout_marginEnd="16dp"/>

<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:text="This is a custom toast message"/>

</LinearLayout>

4. In MainActivity.java, add the following code to show the custom toast when the button
is clicked:
package com.example.toast;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
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);

Button btnShowToast = findViewById(R.id.btn_show_toast);


btnShowToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
9
// Inflate the custom layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_container));

// Set the icon and text


ImageView toastIcon = layout.findViewById(R.id.toast_icon);
toastIcon.setImageResource(R.drawable.ic_check);
TextView toastText = layout.findViewById(R.id.toast_text);
toastText.setText("Hi!..Custom Toast Applied!.");

// Create and show the custom toast


Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 64);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
});
}
}
OUTPUT:

PRACTICAL NO. 4
AIM: Create Android application using CheckBox & AlertDiaglogBox
SOLUTION)
1. Create a new Android project in Android Studio and give it a suitable name.
2. In the activity_main.xml file, add a CheckBox and a Button. Set the id of the CheckBox
to chkBox and the id of the Button to btnShowDialog.

10
<?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">

<CheckBox
android:id="@+id/chkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check me" />

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

</androidx.constraintlayout.widget.ConstraintLayout>
3. In the MainActivity.java file, add the following code to initialize the CheckBox and
Button and set an onClickListener for the Button:
package com.example.box;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private CheckBox mCheckBox;


private Button mButton;

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

mCheckBox = findViewById(R.id.chkBox);
mButton = findViewById(R.id.btnShowDialog);

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

private void showAlertDialog() {


AlertDialog.Builder builder = new AlertDialog.Builder(this);

11
builder.setTitle("Dialog Title");
builder.setMessage("This is the message of the dialog.");

// Set the checkbox view


final View checkBoxView = View.inflate(this, R.layout.dialog_checkbox, null);
builder.setView(checkBoxView);

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


@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when the user clicks OK
CheckBox checkBox = checkBoxView.findViewById(R.id.dialog_chkBox);
if (checkBox.isChecked()) {
Toast.makeText(MainActivity.this, "The checkbox is checked",
Toast.LENGTH_SHORT).show();
}
}
});

builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when the user clicks Cancel
dialog.cancel();
}
});

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

4. In Create a new layout file called dialog_checkbox.xml and add a CheckBox to it. Set
the id of the CheckBox to dialog_chkBox.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<CheckBox
android:id="@+id/dialog_chkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check this box" />

</androidx.constraintlayout.widget.ConstraintLayout>
OUTPUT:

12
Show Dialog
Button CheckBox AlertDialogBox

PRACTICAL NO. 5
AIM: Create Android application using Spinner & Auto complete test
view
SOLUTION)
1. Create a new Android Studio project with an empty activity.
2. Open the activity_main.xml file and add the following code:
<?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">

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

<!-- Spinner -->


<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"

13
android:entries="@array/cities"
android:prompt="@string/select_city"/>

<!-- AutoCompleteTextView -->


<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="@string/search_hint"
android:completionThreshold="1"
android:completionHint=""
android:popupBackground="@color/black"/>

</LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
3. Open the MainActivity.java file and add the following code:
package com.example.spinnerauto;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.spinnerauto.R;

public class MainActivity extends AppCompatActivity {

private Spinner spinner;


private AutoCompleteTextView autoCompleteTextView;

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

spinner = findViewById(R.id.spinner);
autoCompleteTextView = findViewById(R.id.autoCompleteTextView);

// Set up the spinner


ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.cities,
android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedCity = parent.getItemAtPosition(position).toString();
Toast.makeText(MainActivity.this, "Selected city: " + selectedCity, Toast.LENGTH_SHORT).show();
}

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

// Set up the AutoCompleteTextView


ArrayAdapter<CharSequence> autoCompleteAdapter = ArrayAdapter.createFromResource(this, R.array.cities,
android.R.layout.simple_dropdown_item_1line);
autoCompleteTextView.setAdapter(autoCompleteAdapter);
}
}
4. Open the strings.xml file and add the following code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SpinnerAuto</string>

14
<string name="select_city">Select a city</string>
<string name="search_hint">Type to search</string>
<string-array name="cities">
<item>Mumbai</item>
<item>New Delhi</item>
<item>Pune</item>
<item>Bangalore</item>
<item>Kolkata</item>
<item>Agra</item>
<item>Jaipur</item>
<item>Surat</item>
<item>Chandigarh</item>
<item>Indore</item>
</string-array>
</resources>
OUTPUT:

Using Spinner
Using Autocomplete
PRACTICAL NO. 6
AIM: Create an application with following functionalities: Calculator for
Basic mathematical operations.

15
SOLUTION)
MainActivity.java
package com.example.calculator;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private EditText editTextNumber1, editTextNumber2;


private Button buttonAdd, buttonSubtract, buttonMultiply, buttonDivide;
private TextView textViewResult;

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

// Initialize views
editTextNumber1 = findViewById(R.id.editTextNumber1);
editTextNumber2 = findViewById(R.id.editTextNumber2);
buttonAdd = findViewById(R.id.buttonAdd);
buttonSubtract = findViewById(R.id.buttonSubtract);
buttonMultiply = findViewById(R.id.buttonMultiply);
buttonDivide = findViewById(R.id.buttonDivide);
textViewResult = findViewById(R.id.textViewResult);

// Set onClickListener for buttons


buttonAdd.setOnClickListener(this);
buttonSubtract.setOnClickListener(this);
buttonMultiply.setOnClickListener(this);
buttonDivide.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// Get values from EditText fields
float num1 = Float.parseFloat(editTextNumber1.getText().toString());
float num2 = Float.parseFloat(editTextNumber2.getText().toString());

switch (v.getId()) {
case R.id.buttonAdd:
textViewResult.setText(String.valueOf(num1 + num2));
break;
case R.id.buttonSubtract:
textViewResult.setText(String.valueOf(num1 - num2));
break;
case R.id.buttonMultiply:
textViewResult.setText(String.valueOf(num1 * num2));
break;
case R.id.buttonDivide:
if (num2 == 0) {
textViewResult.setText("Cannot divide by zero");
} else {
textViewResult.setText(String.valueOf(num1 / num2));
}
break;
}
}
}

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"

16
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter number 1"
android:inputType="numberDecimal"
android:padding="8dp"
android:textSize="18sp" />

<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter number 2"
android:inputType="numberDecimal"
android:padding="8dp"
android:textSize="18sp" />

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

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

<Button
android:id="@+id/buttonSubtract"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Subtract"
android:textSize="18sp" />

<Button
android:id="@+id/buttonMultiply"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Multiply"
android:textSize="18sp" />

<Button
android:id="@+id/buttonDivide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Divide"
android:textSize="18sp" />

</LinearLayout>

<TextView
android:id="@+id/textViewResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Result will be displayed here"
android:textSize="18sp" />

</LinearLayout>

17
Output:

Add Subtract Multiply Divide

PRACTICAL NO. 7
AIM: Create Android application using Rating Bar, Web view, Seek Bar
SOLUTION)
MaiActivity.java
package com.example.bar;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RatingBar;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {

private RatingBar ratingBar;


private WebView webView;
private SeekBar seekBar;

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

// Initialize Rating Bar


ratingBar = findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
18
// Do something with the rating
}
});

// Initialize Web View


webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com");

// Initialize Seek Bar


seekBar = findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Do something with the seek bar progress
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}
});
}
}

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

<!-- Rating Bar -->


<RatingBar
android:id="@+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:stepSize="1" />

<!-- Web View -->


<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ratingBar"
android:layout_marginTop="10dp" />

<!-- Seek Bar -->


<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/webView"
android:layout_marginTop="10dp"
android:max="100" />
</RelativeLayout>

OUTPUT:
19
PRACTICAL NO. 8
AIM: Design an android application for “Registration Form” using
different layout such as table layout, linear layout etc. Use Drawable
Resources, option menu, List Views and Adapters.
SOLUTION)
MainActivity.java
package com.example.registration;

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

public class MainActivity extends AppCompatActivity {

EditText editTextName, editTextEmail, editTextPassword;


Button buttonRegister;

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

// Get references to UI elements


editTextName = findViewById(R.id.editTextName);

20
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
buttonRegister = findViewById(R.id.buttonRegister);

// Set up click listener for the Register button


buttonRegister.setOnClickListener(v -> {
// Code for registering user goes here
// Show toast message to confirm registration
Toast.makeText(MainActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// Code for opening settings activity goes here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

activity_main.java
<?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">

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="@drawable/ic_launcher" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Registration Form"
android:textSize="24sp"
android:textStyle="bold" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="16dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:"
android:textStyle="bold" />

<EditText
android:id="@+id/editTextName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="textPersonName" />

</LinearLayout>

21
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="16dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email:"
android:textStyle="bold" />

<EditText
android:id="@+id/editTextEmail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="textEmailAddress" />

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="16dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:textStyle="bold" />

<EditText
android:id="@+id/editTextPassword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="textPassword" />

</LinearLayout>

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

</LinearLayout>

22
OUTPUT:

23
PRACTICAL NO. 9
AIM: Create Android application using Date picker & Time Picker
SOLUTION)
MainActivity.java
package com.example.datetime;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import com.example.datetime.R;

import java.text.DateFormat;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

private TextView textDate;


private TextView textTime;

private Button buttonPickDate;


private Button buttonPickTime;

private int year, month, dayOfMonth, hour, minute;

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

// Get references to UI elements


textDate = findViewById(R.id.text_date);
textTime = findViewById(R.id.text_time);
buttonPickDate = findViewById(R.id.button_pick_date);
buttonPickTime = findViewById(R.id.button_pick_time);

// Set up click listeners for the buttons


buttonPickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the current date
final Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

// Show the date picker dialog


DatePickerDialog datePickerDialog = new DatePickerDialog(
MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// Update the text view with the selected date
Calendar selectedDate = Calendar.getInstance();
selectedDate.set(year, month, dayOfMonth);
String formattedDate =
DateFormat.getDateInstance().format(selectedDate.getTime());
textDate.setText("Selected date: " + formattedDate);
}
},
year, month, dayOfMonth);
datePickerDialog.show();
}

24
});

buttonPickTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the current time
final Calendar calendar = Calendar.getInstance();
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);

// Show the time picker dialog


TimePickerDialog timePickerDialog = new TimePickerDialog(
MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Update the text view with the selected time
String selectedTime = String.format("%02d:%02d", hourOfDay, minute);
textTime.setText("Selected time: " + selectedTime);
}
},
hour, minute, true);
timePickerDialog.show();
}
});
}
}

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Date and Time"
android:textSize="24sp"
android:textStyle="bold"/>

<Button
android:id="@+id/button_pick_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Date"/>

<Button
android:id="@+id/button_pick_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Time"/>

<TextView
android:id="@+id/text_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Selected date: "/>

<TextView
android:id="@+id/text_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Selected time: "/>

</LinearLayout>

25
Output:

26
PRACTICAL NO. 10
AIM: Create Android application using Progress Bar, Implicit Intend
SOLUTION)
MainActivity.java
package com.example.intend;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private ProgressBar progressBar;


private Button downloadButton;

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

progressBar = findViewById(R.id.progressBar);
downloadButton = findViewById(R.id.downloadButton);

downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://www.google.co.in/url?sa=t&source=web&rct=j&url=https://www.africau.edu/
images/default/sample.pdf&ved=2ahUKEwjL5cXWhM_-AhX4RmwGHZ3OAo0QFnoECCkQAQ&usg=AOvVaw0B2jC3SIfJyqSsyBlwEi27";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("Downloading File");
request.setDescription("Downloading file...");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file-to-
download.pdf");

DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);


long downloadId = downloadManager.enqueue(request);

Intent intent = new Intent(MainActivity.this, DownloadReceiver.class);


intent.putExtra("downloadId", downloadId);
startActivity(intent);

Toast.makeText(MainActivity.this, "Downloading file...", Toast.LENGTH_LONG).show();


downloadButton.setEnabled(false);
}
});
}
}

27
DownloadReceiver.java
package com.example.intend;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class DownloadReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager downloadManager = (DownloadManager)
context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = downloadManager.getUriForDownloadedFile(downloadId);
String downloadedFilePath = downloadUri.getPath();

Toast.makeText(context, "File downloaded to " + downloadedFilePath, Toast.LENGTH_LONG).show();


Log.d("DownloadReceiver", "File downloaded to " + downloadedFilePath);
} else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
Toast.makeText(context, "Notification clicked", Toast.LENGTH_LONG).show();
Log.d("DownloadReceiver", "Notification clicked");
}
}
}

activity_main.xml
<?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”>

<ProgressBar
android:id=”@+id/progressBar”
style=”@style/Widget.AppCompat.ProgressBar.Horizontal”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”32dp”
android:layout_marginLeft=”32dp”
android:layout_marginRight=”32dp”
android:visibility=”invisible”/>

<Button
android:id=”@+id/downloadButton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Download File”
android:layout_centerInParent=”true”/>

</RelativeLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"

28
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Intend"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>

<receiver
android:name=".DownloadReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
</application>

</manifest>

OUTPUT:

29
PRACTICAL NO. 11
AIM: Create Android application using fragments
SOLUTION)
1. Create a new Android project in Android Studio.
2. In the "Create New Project" dialog, select "Empty Activity" and click "Next".
3. Give your project a name, choose a package name and a location to save it in, and click
"Finish".
4. In the project structure on the left side of the screen, right-click on the "app" folder and
select "New > Fragment > Fragment (Blank)".
5. Give your fragment a name, for example "MyFragment", and click "Finish".
6. In the "MyFragment.java" file that was just created, extend the Fragment class and
override the onCreateView() method. This method should return a View that will be
displayed as the content of the fragment.
7. In the "fragment_my.xml" file that was created alongside "MyFragment.java", add
some UI elements that you want to display in the fragment.
8. In your MainActivity.java file, you can now use a FragmentManager to add the
fragment to the activity.
9. In the "activity_main.xml" layout file, add a container where the fragment will be
displayed.

myFragment.java
package com.example.fragments;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
* A simple {@link Fragment} subclass.
* Use the {@link myFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class myFragment extends Fragment {

// TODO: Rename parameter arguments, choose names that match


// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters


private String mParam1;
private String mParam2;

30
public myFragment() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment myFragment.
*/
// TODO: Rename and change types and number of parameters
public static myFragment newInstance(String param1, String param2) {
myFragment fragment = new myFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

public static class MyFragment extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my, container, false);
}
}
}

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello from MyFragment!"/>
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

MainActivity.java
package com.example.fragments;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
31
// Create a new instance of MyFragment
myFragment.MyFragment fragment = new myFragment.MyFragment();

// Get the FragmentManager and start a transaction


FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

// Add the fragment to the transaction and commit it


fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}

activity_main.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Output:

32
PRACTICAL NO. 12
AIM: Design and Implement a Registration Form using SQLite Database.
SOLUTION)
Step 1) Update build.gradle file.
Before you can use Material Design in your projects you need to add the following compile line
to your Gradle dependencies block in your build.gradle file and rebuilt the project.
dependencies {

implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.cardview:cardview:1.0.0'

implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.core:core:1.7.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

Step 2) Update strings.xml.


Add the below string values to the string.xml located in res => values => strings.xml.
<resources>
<string name="app_name">Login Register</string>
<string name="text_accounts">All Accounts</string>
<string name="hint_name">Name</string>
<string name="hint_email">Email</string>
<string name="hint_password">Password</string>
<string name="hint_confirm_password">Confirm Password</string>
<string name="text_login">Login</string>
<string name="text_register">Register</string>
<string name="error_message_name">Enter Full Name</string>
<string name="error_message_email">Enter Valid Email</string>
<string name="error_message_age">Enter Age</string>
<string name="error_message_password">Enter Password</string>
<string name="success_message">Registration Successful</string>
<string name="text_not_member">No account yet? Create one</string>
<string name="text_already_member">Already a member? Login</string>
<string name="error_email_exists">Email Already Exists</string>
<string name="error_password_match">Password Does Not Matches</string>
<string name="error_valid_email_password">Wrong Email or Password</string>
<string name="action_settings">Settings</string>
<string name="text_hello">Hello,</string>
<string name="text_title">RegisterDB</string>
</resources>
Step 3) Update colors.xml.
Add the below color values to the colors.xml located in res => values => colors.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#51d8c7</color>
<color name="colorPrimaryDark">#51d8c7</color>
<color name="colorAccent">#FFFFFF</color>
<color name="colorBackground">#413e4f</color>
<color name="colorText">#FFFFFF</color>

33
<color name="colorTextHint">#51d8c7</color>
<color name="purple_500">#9c27b0</color>
<color name="purple_700">#7b1fa2</color>
<color name="teal_200">#80cbc4</color>
<color name="teal_700">#00796b</color>
<color name="white">#FFFFFF</color>
<color name="black">#000000</color>
<color name="purple_200">#ce93d8</color>
</resources>
Step 4) Update styles.xml.
Add the below style values to the styles.xml located in res => values => styles.xml.
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textColor">@color/colorText</item>
<item name="android:textColorHint">@color/colorText</item>
<item name="colorControlNormal">@color/colorText</item>
<item name="colorControlActivated">@color/colorText</item>
</style>
</resources>
Step 5) Add Logo Image.
Download the below logo image and add it to the drawable folder located in res => drawable.

Step 6) Create a User model class.


Create a new package named model and create a User class with all getter and setter methods to maintain single
contact as an object.
Step 7) Create a DatabaseHelper class.
Create a new package named SQL and create a DatabaseHelper class. Extend this class
with SQLiteOpenHelper to manage database creation and version management.
Step 8) Create activity_login.xml.
Now create a layout file for the LoginActivity.java i.e activity_login.xml and add the below code in your layout
file. The code will create a simple login form containing logo on the top, 2 input fields email and password,
login button, and registration screen navigation link.

Step 8) Create InputValidation class.


Create a package named helpers and create a class in it named InputValidation.java and add below code in it.
The code will create validation methods for the input field. Validation like empty input, valid email and etc.

34
Step 9) Create a LoginActivity class.
Now create a package named activities and create a class named LoginActivity and add below code. Here i have
written the code to validate the input fields Email and Password using the InputValidation class which I
described above. Also, code for navigation to registration screen on the click of registration link and to user list
screen after clicking on the login button if credentials are valid.
Step 10) Create activity_register.xml.
Now create a layout file for the RegisterActivity.java i.e activity_register.xml and add the below code in your
layout file. The code will create a simple registration form containing a logo on the top, 4 input fields name,
email, password, and confirm password, register button, and login screen navigation link.
Step 11) Create RegisterActivity class.
Now create a package named activities and create a class named RegisterActivity and add below code. Here I
have written the code to validate the input fields Name, Email, Password, and Confirm Password using the
InputValidation class which I described above. Also, code for navigation to the login screen on the click of
login link and shows snackbar with success message for registration.
Step 12) Create activity_users_list.xml.
Now create a layout file for the UsersListActivity.java i.e activity_users_list.xml and add the below code in
your layout file. The code will create a simple view containing two views one view i.e LinearLayout shows the
welcome message with email id of the logged in user and another view i.e RecyclerView shows the list of
registered users in the app.
Step 13) Writing the Adapter Class.
Now create a package named adapters and create a class named UsersRecyclerAdapter and add below code.
Here onCreateViewHolder() method inflates item_user_recycler.xml. In onBindViewHolder() method the
appropriate User data (name, email, and password) set to each row.
Step 15) Update AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="activities.LoginActivity"
android:screenOrientation="fullSensor"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name="activities.RegisterActivity"
android:screenOrientation="fullSensor" />
<activity
android:name="activities.UsersListActivity"
android:screenOrientation="fullSensor" />
</application>

</manifest>

35
Full Code Files:

OUTPUT

36

You might also like