0% found this document useful (0 votes)
59 views55 pages

Rohit 101 MA File

Uploaded by

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

Rohit 101 MA File

Uploaded by

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

VIVEKANANDA INSTITUTE OF PROFESSIONAL STUDIES

VIVEKANANDA SCHOOL OF INFORMATION TECHNOLOGY

BACHELOR OF COMPUTER APPLICATION


PRACTICAL FILE – Mobile Applications
Development

BCA 318

Guru Gobind Singh Indraprastha


University Sector - 16C Dwarka, Delhi –
110078

SUBMITTED TO: SUBMITTED BY:


Ms. Dimple Chawla ROHIT GHOSH
Assistant Professor 10117702021

VSIT BCA 6-B

10117702021 ROHIT GHOSH BCA 6 – B


INDEX
S.No. Particulars Date Sign.
1. Create "hello world" application to display "hello world" in the middle of 6/2/24
the screen in the emulator as well as android phone
2. Create an android app to display various android lifecycle phases. 13/2/24

3. Create a calculator app that performs addition, subtraction, division and 27/2/24
multiplication operation on numbers.
4. Write an Android application to convert into different currencies for 28/2/24
example, Rupees to dollar
5. Write an android application to convert a ball from size of radius 2(colour 5/3/24
red) to radius 4(colour blue) to radius 6 (colour green). The ball must
rotate in circle for 1 minute before changing size and colour.

6. Write an application to mark the daily route of travel in map. 11/3/24


7. Write an application to record video and audio on topic “Intent” and play 14/3/24
the audio and video.
8. Create a spinner application with strings taken from resource directory 9/4/24
res/values/strings.xml and on changing the spinner value, image will
change. Image is saved in the drawable directory.
9. Create an app that uses radio button group which calculates discount on 18/3/24
shopping bill amount. Use ediitext to enter bill amount and select one of
three radio buttons to determine a discount for 10, 15, or 20 percent.the
discount is calculated upon selection of one of the buttons and displayed
in a textview control.

10. Create an application that uses checkbox for construction of a shopping 23/4/24
list so the user can check off items as they are picked up. The checked
items should be displayed in a textview control.
11. Create a login application to verify username and password. On 25/4/24
successful login, redirect to another activity that has a textview to
display "welcome user" with logout button. On click of logout button, a
dialog should appear with ok and cancel buttons. On click of oK button,
go back to the login activity and on click of cancel button, stay on the
same
activity.
12. Create an application to perform the operations of create, insert, delete, 28/4/24
view and update, using sqlite database.
13. Create an application to pick up any image from the native application 30/4/24
gallery and display it on the screen.
14. Read phonebook contacts using content providers and display in list. 2/5/24
15. Create an application to take picture using native application. 2/5/24

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 1

Create "hello world" application to display "hello world" in the middle of the screen in the emulator as
well as android phone

CODE

MainActivity.java

package com.example.practice;

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

public class MainActivity extends AppCompatActivity {

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

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

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="24sp"
android:layout_centerInParent="true"/>

</RelativeLayout>

10117702021 ROHIT GHOSH BCA 6 – B


OUTPUT

Emulator Output : Android Device Output :

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 2

Create an android app to display various android lifecycle phases.

CODE

MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
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);
Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
}

@Override
protected void onStart()
{ super.onStart();
Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show();
}

@Override
protected void onRestart()
{ super.onRestart();
Toast.makeText(getApplicationContext(), "onRestart Called", Toast.LENGTH_LONG).show();
}

@Override
protected void onPause()
{ super.onPause();
Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show();
}

@Override
protected void onResume()
{ super.onResume();
Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show();
}

@Override

10117702021 ROHIT GHOSH BCA 6 – B


protected void onStop()
{ super.onStop();
Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show();
}

@Override
protected void onDestroy()
{ super.onDestroy();
Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show();
}
}

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"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lifecycle Activity"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>

10117702021 ROHIT GHOSH BCA 6 – B


OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 3

Create a calculator app that performs addition, subtraction, division and multiplication operation on
numbers.

CODE

MainActivity.java

package com.example.caculaterr;

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity

private EditText editTextNumber1;


private EditText editTextNumber2;
private TextView textViewResult;

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

editTextNumber1 = findViewById(R.id.editTextNumber1);
editTextNumber2 = findViewById(R.id.editTextNumber2);
textViewResult = findViewById(R.id.textViewResult);
}

public void add(View view) {


calculate(Operation.ADD);
}

public void subtract(View view) {


calculate(Operation.SUBTRACT);
}

public void multiply(View view) {


calculate(Operation.MULTIPLY);
}

public void divide(View view) {


10117702021 ROHIT GHOSH BCA 6 – B
calculate(Operation.DIVIDE);
}

10117702021 ROHIT GHOSH BCA 6 – B


private void calculate(Operation operation)
{ try {
double number1 = Double.parseDouble(editTextNumber1.getText().toString());
double number2 = Double.parseDouble(editTextNumber2.getText().toString());
double result;

switch (operation) {
case ADD:
result = number1 +
number2; break;
case SUBTRACT:
result = number1 - number2;
break;
case MULTIPLY:
result = number1 *
number2; break;
case DIVIDE:
result = number1 / number2;
break;
default:
throw new IllegalStateException("Unexpected value: " + operation);
}

// Set the result using resource string with placeholders


textViewResult.setText(getString(R.string.result_label, String.valueOf(result)));
} catch (NumberFormatException e) {
Toast.makeText(this, "Invalid input. Please enter valid numbers.", Toast.LENGTH_SHORT).show();
} catch (ArithmeticException e) {
Toast.makeText(this, "Cannot divide by zero.", Toast.LENGTH_SHORT).show();
}
}

private enum Operation {


ADD, SUBTRACT, MULTIPLY, DIVIDE
}
}

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"
android:background="#F0F0F0"
android:padding="16dp"
tools:context=".MainActivity">

10117702021 ROHIT GHOSH BCA 6 – B


<EditText
android:id="@+id/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/enter_number_1"
android:inputType="numberDecimal"
android:background="#FFFFFF"
android:padding="10dp"
android:textColor="#000000"
android:layout_marginBottom="8dp"
android:autofillHints="number" />

<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/enter_number_2"
android:inputType="numberDecimal"
android:background="#FFFFFF"
android:padding="10dp"
android:textColor="#000000"
android:layout_below="@id/editTextNumber1"
android:layout_marginBottom="8dp"
android:autofillHints="number" />

<Button
android:id="@+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/add_button_text"
android:onClick="add"
android:background="#2196F3"
android:textColor="#FFFFFF"
android:layout_below="@id/editTextNumber2"/>

<Button
android:id="@+id/buttonSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/subtract_button_text"
android:onClick="subtract"
android:background="#FF5722"
android:textColor="#FFFFFF"
android:layout_below="@id/buttonAdd"
android:layout_marginTop="8dp"/>

10117702021 ROHIT GHOSH BCA 6 – B


<Button
android:id="@+id/buttonMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/multiply_button_text"
android:onClick="multiply"
android:background="#4CAF50"
android:textColor="#FFFFFF"
android:layout_below="@id/buttonSubtract"
android:layout_marginTop="8dp"/>

<Button
android:id="@+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/divide_button_text"
android:onClick="divide"
android:background="#FFC107"
android:textColor="#FFFFFF"
android:layout_below="@id/buttonMultiply"
android:layout_marginTop="8dp"/>

<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/result_label"
android:textSize="18sp"
android:textStyle="bold"
android:layout_below="@id/buttonDivide"
android:layout_marginTop="16dp"/>

</RelativeLayout>

10117702021 ROHIT GHOSH BCA 6 – B


OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 4

Write an Android application to convert into different currencies for example, Rupees to dollar.

CODE

MainActivity.java

package com.example.currency;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText
etAmount;
TextView tvResult;
RadioButton rbUSD, rbEUR;

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

etAmount = findViewById(R.id.et_amount);
tvResult = findViewById(R.id.tv_result);
rbUSD = findViewById(R.id.rb_usd);
rbEUR = findViewById(R.id.rb_eur);
}

public void convertCurrency(View view) {


double amount = Double.parseDouble(etAmount.getText().toString());
double conversionRate = 0;

if (rbUSD.isChecked()) {
// Conversion rate: 1 USD = 74.89 INR (change this to your desired conversion rate)
conversionRate = 74.89;
} else if (rbEUR.isChecked()) {
// Conversion rate: 1 EUR = 88.22 INR (change this to your desired conversion rate)
conversionRate = 88.22;
}

10117702021 ROHIT GHOSH BCA 6 – B


double convertedAmount = amount / conversionRate;

10117702021 ROHIT GHOSH BCA 6 – B


tvResult.setText(String.format("%.2f", convertedAmount));
}
}

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"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/et_amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter amount in Rupees"
android:inputType="numberDecimal"
android:layout_marginBottom="16dp"/>

<RadioButton
android:id="@+id/rb_usd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/et_amount"
android:layout_marginTop="16dp"
android:text="USD"
android:checked="true"/>

<RadioButton
android:id="@+id/rb_eur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/rb_usd"
android:layout_marginTop="8dp"
android:text="EUR"/>

<Button
android:id="@+id/btn_convert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/rb_eur"
android:layout_marginTop="16dp"
android:text="Convert"

10117702021 ROHIT GHOSH BCA 6 – B


android:onClick="convertCurrency"/>

<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btn_convert"
android:layout_marginTop="16dp"
android:textSize="20sp"
android:textStyle="bold"/>

</RelativeLayout>

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 5

Write an android application to convert a ball from size of radius 2(colour red) to radius 4(colour blue) to
radius 6 (colour green). The ball must rotate in circle for 1 minute before changing size and colour.

CODE

MainActivity.java
package com.example.ballcoloringrotate;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

private ImageView ball;


private final int rotationDuration = 60000; // Rotation duration in milliseconds

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

ball = findViewById(R.id.ball);

// Set circular shape background


setCircularShapeBackground();

// Start the rotation


animation startRotation();

// Change ball size and color after 1 minute


new Handler().postDelayed(this::changeBall, rotationDuration);
}

private void startRotation() {


RotateAnimation rotateAnimation = new RotateAnimation(0, 360,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation.setDuration(rotationDuration);
rotateAnimation.setRepeatCount(Animation.INFINITE);
ball.startAnimation(rotateAnimation);

10117702021 ROHIT GHOSH BCA 6 – B


// Set circular shape background
setCircularShapeBackground();
}

private void setCircularShapeBackground() {


GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.OVAL); // Change shape to rectangle
drawable.setColor(Color.parseColor("#80000000")); // Set semi-transparent black color
ball.setBackground(drawable);
}
private void changeBall() {
// Change ball size and color after rotation
int[] colors = {Color.RED, Color.BLUE,
Color.GREEN}; int[] radiusValues = {200, 400, 600};

// Create a ValueAnimator for color change


ValueAnimator colorAnimator = ValueAnimator.ofArgb(colors);
colorAnimator.setDuration(rotationDuration);
colorAnimator.addUpdateListener(animation -> {
int color = (int)
animation.getAnimatedValue();
ball.setBackgroundColor(color);
});

// Create a ValueAnimator for size change


ValueAnimator sizeAnimator = ValueAnimator.ofInt(radiusValues);
sizeAnimator.setDuration(rotationDuration);
sizeAnimator.addUpdateListener(animation -> {
int radius = (int)
animation.getAnimatedValue();
// Update the size of the ball
ball.getLayoutParams().width = radius;
ball.getLayoutParams().height = radius;
ball.requestLayout();
});

// Start both
animators
colorAnimator.start();
sizeAnimator.start();
}
}

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"

10117702021 ROHIT GHOSH BCA 6 – B


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

10117702021 ROHIT GHOSH BCA 6 – B


<ImageView
android:id="@+id/ball"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@drawable/circle_shape"
android:layout_centerInParent="true"
android:contentDescription="@string/ball_description"
android:scaleType="centerCrop" />

</RelativeLayout>

Circle_shape.xml

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


<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@android:color/holo_red_light" />
</shape>

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 7

Write an application to record video and audio on topic “Intent” and play the audio and video.

CODE

AudioActivity.java

package com.example.videoaudplayer;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class AudioActivity extends AppCompatActivity {

private static final int REQUEST_AUDIO_CAPTURE = 102;

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

dispatchTakeAudioIntent();
}

private void dispatchTakeAudioIntent() {


Intent takeAudioIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
if (takeAudioIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeAudioIntent, REQUEST_AUDIO_CAPTURE);
} else {
Toast.makeText(this, "No app to handle audio recording", Toast.LENGTH_SHORT).show();
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == REQUEST_AUDIO_CAPTURE && resultCode == RESULT_OK) {


Uri audioUri = data.getData();
// Play the recorded audio using audioUri
} else {
Toast.makeText(this, "Audio recording cancelled", Toast.LENGTH_SHORT).show();
}
}
}
10117702021 ROHIT GHOSH BCA 6 – B
activity_audio.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"
android:gravity="center">

</RelativeLayout>

package com.example.videoaudplayer;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

public void recordVideo(View view) {


Intent intent = new Intent(this, VideoActivity.class);
startActivity(intent);
}

public void recordAudio(View view) {


Intent intent = new Intent(this, AudioActivity.class);
startActivity(intent);
}
}

MainActivity.java

package com.example.videoaudplayer;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

10117702021 ROHIT GHOSH BCA 6 – B


setContentView(R.layout.activity_main);
}

public void recordVideo(View view) {


Intent intent = new Intent(this, VideoActivity.class);
startActivity(intent);
}

public void recordAudio(View view) {


Intent intent = new Intent(this, AudioActivity.class);
startActivity(intent);
}
}

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 8

Create a spinner application with strings taken from resource directory res/values/strings.xml and on
changing the spinner value, image will change. Image is saved in the drawable directory.

CODE

MainActivity.java

package com.example.somespinner;

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

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);


ImageView imageView = findViewById(R.id.imageView);

// Load spinner values from strings.xml


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);

// Set the adapter to the


spinner
spinner.setAdapter(adapter);

// Handle spinner item selection


spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Handle item selection
String selectedItem = parent.getItemAtPosition(position).toString();
switch (selectedItem) {
case "Option 1":
10117702021 ROHIT GHOSH BCA 6 – B
imageView.setImageResource(R.drawable.image_option1);

10117702021 ROHIT GHOSH BCA 6 – B


break;
case "Option 2":
imageView.setImageResource(R.drawable.image_option2);
break;
case "Option 3":
imageView.setImageResource(R.drawable.image_option3);
break;
default:
imageView.setImageResource(R.drawable.image_default);
}
}

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

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"
android:padding="16dp"
tools:context=".MainActivity">

<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />

<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_below="@id/spinner"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:src="@drawable/image_default"
android:contentDescription="@string/image_description" />

</RelativeLayout>

10117702021 ROHIT GHOSH BCA 6 – B


Strings.xml

<resources>
<string name="app_name">SomeSpinner</string>
<string-array name="spinner_options">
<item>Option 1</item>
<item>Option 2</item>
<item>Option 3</item>
</string-array>
<string name="image_description">Description of your image</string>
</resources>

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 9

Create an app that uses radio button group which calculates discount on shopping bill amount. Use
ediitext to enter bill amount and select one of three radio buttons to determine a discount for 10, 15,
or 20 percent.the discount is calculated upon selection of one of the buttons and displayed in a
textview control.

CODE

MainActivity.java

package com.example.billinging;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.Locale;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextBillAmount;


private RadioGroup radioGroupDiscount;
private TextView textViewDiscount;

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

editTextBillAmount = findViewById(R.id.editTextBillAmount);
radioGroupDiscount = findViewById(R.id.radioGroupDiscount);
textViewDiscount = findViewById(R.id.textViewDiscount);
}

public void calculateDiscount(View view) {


double billAmount = Double.parseDouble(editTextBillAmount.getText().toString());

int discountPercentage = 0;
int checkedRadioButtonId = radioGroupDiscount.getCheckedRadioButtonId();
if (checkedRadioButtonId != -1) {
RadioButton radioButton = findViewById(checkedRadioButtonId);
String discountText = radioButton.getText().toString().replace("%", "");
discountPercentage = Integer.parseInt(discountText);
}

10117702021 ROHIT GHOSH BCA 6 – B


double discount = (billAmount * discountPercentage) / 100;

// Format the discount amount with rupee symbol


String formattedDiscount = String.format(Locale.getDefault(), "%s%.2f", getString(R.string.rupee_symbol),
discount);

// Update the text view with the formatted discount amount


textViewDiscount.setText(getString(R.string.discount_text, formattedDiscount));
}
}

activity_main.xml

<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=".MainActivity">

<EditText
android:id="@+id/editTextBillAmount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_enter_bill_amount"
android:inputType="numberDecimal"
android:autofillHints="price"
android:layout_marginBottom="16dp"/>

<RadioGroup
android:id="@+id/radioGroupDiscount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextBillAmount"
android:orientation="horizontal">

<RadioButton
android:id="@+id/radioButton10Percent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/discount_10_percent" />

<RadioButton
android:id="@+id/radioButton15Percent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/discount_15_percent" />

<RadioButton

10117702021 ROHIT GHOSH BCA 6 – B


android:id="@+id/radioButton20Percent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/discount_20_percent" />

</RadioGroup>

<Button
android:id="@+id/buttonCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/radioGroupDiscount"
android:layout_centerHorizontal="true"
android:text="@string/calculate_discount"
android:onClick="calculateDiscount" />

<TextView
android:id="@+id/textViewDiscount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonCalculate"
android:layout_centerHorizontal="true"
android:text="@string/discount_label"
android:textStyle="bold"
android:layout_marginTop="16dp"/>
</RelativeLayout>

Strings.xml

<resources>
<string name="app_name">billinging</string>
<string name="hint_enter_bill_amount">Enter Bill Amount</string>
<string name="discount_10_percent">10%</string>
<string name="discount_15_percent">15%</string>
<string name="discount_20_percent">20%</string>
<string name="calculate_discount">Calculate Discount</string>
<string name="discount_label">Discount: </string>
<string name="discount_text">Discount: %s</string>
<string name="rupee_symbol">\u20B9</string>

</resources>

10117702021 ROHIT GHOSH BCA 6 – B


OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 10

Create an application that uses checkbox for construction of a shopping list so the user can check off
items as they are picked up. The checked items should be displayed in a textview control.

CODE

MainActivity.java

package com.example.shoppinglist;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private TextView textViewCart;

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

textViewCart = findViewById(R.id.textview_cart);
}

public void addToCart(View view) {


StringBuilder selectedItems = new StringBuilder();
CheckBox checkBoxItem1 = findViewById(R.id.checkbox_item1);
CheckBox checkBoxItem2 = findViewById(R.id.checkbox_item2);
// Add more CheckBox references as needed

if (checkBoxItem1.isChecked()) {
selectedItems.append(checkBoxItem1.getText()).append(", ");
}
if (checkBoxItem2.isChecked()) {
selectedItems.append(checkBoxItem2.getText()).append(", ");
}
// Add more CheckBox conditions as needed

// Remove trailing comma and space


if (selectedItems.length() > 0) {
selectedItems.setLength(selectedItems.length() - 2);
}

String selectedItemsText = getString(R.string.selected_items, selectedItems.toString());


10117702021 ROHIT GHOSH BCA 6 – B
textViewCart.setText(selectedItemsText);
}
}

activity_main.xml

<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=".MainActivity">

<CheckBox
android:id="@+id/checkbox_item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/item1"
android:layout_marginBottom="8dp"/>

<CheckBox
android:id="@+id/checkbox_item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/item2"
android:layout_below="@id/checkbox_item1"
android:layout_marginBottom="8dp"/>

<Button
android:id="@+id/button_add_to_cart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/checkbox_item2"
android:layout_marginTop="138dp"
android:onClick="addToCart"
android:text="@string/add_to_cart" />

<TextView
android:id="@+id/textview_cart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button_add_to_cart"
android:layout_marginTop="31dp"
android:text="@string/selected_items" />

<CheckBox
android:id="@+id/checkbox_item3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

10117702021 ROHIT GHOSH BCA 6 – B


android:text="@string/item3"
android:layout_below="@id/checkbox_item2"
android:layout_marginBottom="8dp"/>
<CheckBox
android:id="@+id/checkbox_item4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/item4"
android:layout_below="@id/checkbox_item3"
android:layout_marginBottom="8dp"/>
</RelativeLayout>

Strings.xml

<resources>
<string name="app_name">Shopping List</string>
<string name="item1">Item 1</string>
<string name="item2">Item 2</string>
<!-- Add more string resources for additional items -->
<string name="add_to_cart">Add to Cart</string>
<string name="selected_items">Selected Items: %s</string>
<string name="item3">Item 3</string>
<string name="item4">Item 4</string>
</resources>

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 11

CODE

MainActivity.java

package com.example.pagelogin;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private static final String USERNAME = "admin";


private static final String PASSWORD = "1234";

private EditText editTextUsername;


private EditText editTextPassword;

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

editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
}

public void login(View view) {


String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();

if (username.equals(USERNAME) && password.equals(PASSWORD)) {


// Successful login, redirect to WelcomeActivity
Intent intent = new Intent(this, WelcomeActivity.class);
intent.putExtra("USERNAME", username);
startActivity(intent);
} else {
// Invalid credentials, display a toast message
Toast.makeText(this, "Invalid username or password", Toast.LENGTH_SHORT).show();
}
}

public void logout(View view) {

10117702021 ROHIT GHOSH BCA 6 – B


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to logout?")
.setPositiveButton("OK", (dialog, id) -> {
// Perform logout action here
})
.setNegativeButton("Cancel", (dialog, id) -> {
// User cancelled the dialog
});
// Create the AlertDialog object and return it
AlertDialog dialog = builder.create();
dialog.show();
}
}

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"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_username"
android:autofillHints="username"
android:inputType="text"
android:layout_marginBottom="8dp"/>

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:autofillHints="password"
android:inputType="textPassword"
android:layout_below="@id/editTextUsername"
android:layout_marginBottom="8dp"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_login"
android:onClick="login"
android:layout_below="@id/editTextPassword"/>

10117702021 ROHIT GHOSH BCA 6 – B


</RelativeLayout>

WelcomeActivity.java

package com.example.pagelogin;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class WelcomeActivity extends AppCompatActivity {

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

// Get the username from the intent extras


String username = getIntent().getStringExtra("USERNAME");

// Format the welcome message using the string resource


String welcomeMessage = getString(R.string.welcome_message, username);

TextView textViewWelcome = findViewById(R.id.textViewWelcome);


textViewWelcome.setText(welcomeMessage);
}

public void logout(View view) {


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to log out?")
.setPositiveButton("OK", (dialog, which) -> {
// Go back to MainActivity on OK click
Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Close WelcomeActivity
})
.setNegativeButton("Cancel", (dialog, which) -> {
// Stay on the same activity on Cancel click
dialog.dismiss();
});
AlertDialog dialog =
builder.create(); dialog.show();
}
}

activity_welcome.xml

10117702021 ROHIT GHOSH BCA 6 – B


<?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"
android:padding="16dp"
tools:context=".WelcomeActivity">

<TextView
android:id="@+id/textViewWelcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome_user"
android:textSize="24sp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/logout"
android:onClick="logout"
android:layout_below="@id/textViewWelcome"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"/>

</RelativeLayout>

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 12

Create an application to perform the operations of create, insert, delete, view and update, using sqlite
database.

CODE

MainActivity.java

package com.example.applicationforms;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

private EditText editTextName, editTextAge;


private DBHelper dbHelper;

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

editTextName = findViewById(R.id.editTextName);
editTextAge = findViewById(R.id.editTextAge);
Button buttonAdd = findViewById(R.id.buttonAdd);
Button buttonView = findViewById(R.id.buttonView);
Button buttonDelete = findViewById(R.id.buttonDelete);
Button buttonUpdate = findViewById(R.id.buttonUpdate);

dbHelper = new DBHelper(this);

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

buttonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
10117702021 ROHIT GHOSH BCA 6 – B
viewData(v);
}
});

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

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

public void addData(View view) {


String name = editTextName.getText().toString().trim();
String ageString = editTextAge.getText().toString().trim();

if (name.isEmpty() || ageString.isEmpty()) {
Toast.makeText(this, "Please enter name and age", Toast.LENGTH_SHORT).show();
return;
}

int age = Integer.parseInt(ageString);

SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, name);
values.put(DBHelper.COLUMN_AGE, age);

long newRowId = db.insert(DBHelper.TABLE_NAME, null, values);

if (newRowId == -1) {
Toast.makeText(this, "Failed to add data", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Data added successfully", Toast.LENGTH_SHORT).show();
}
}

public void viewData(View view) {


SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(
DBHelper.TABLE_NAME,
10117702021 ROHIT GHOSH BCA 6 – B
null,
null,
null,
null,
null,
null
);

StringBuilder data = new StringBuilder();


while (cursor.moveToNext()) {
int nameIndex = cursor.getColumnIndex(DBHelper.COLUMN_NAME);
int ageIndex = cursor.getColumnIndex(DBHelper.COLUMN_AGE);

if (nameIndex != -1 && ageIndex != -1) {


String name = cursor.getString(nameIndex);
int age = cursor.getInt(ageIndex);
data.append("Name: ").append(name).append(", Age: ").append(age).append("\n");
} else {
// Handle the case where the column index is not found
data.append("Invalid data in cursor").append("\n");
}
}

cursor.close();

if (data.length() == 0) {
Toast.makeText(this, "No data found", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, data.toString(), Toast.LENGTH_SHORT).show();
}
}

public void deleteData(View view) {


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

SQLiteDatabase db = dbHelper.getWritableDatabase();
int deletedRows = db.delete(DBHelper.TABLE_NAME, DBHelper.COLUMN_NAME + " = ?", new String[]{name});

if (deletedRows > 0) {
Toast.makeText(this, "Data deleted successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No matching data found to delete", Toast.LENGTH_SHORT).show();
}
}

public void updateData(View view) {


String name = editTextName.getText().toString().trim();
String ageString = editTextAge.getText().toString().trim();
10117702021 ROHIT GHOSH BCA 6 – B
if (name.isEmpty() || ageString.isEmpty()) {
Toast.makeText(this, "Please enter name and age", Toast.LENGTH_SHORT).show();
return;
}

int age = Integer.parseInt(ageString);

SQLiteDatabase db = dbHelper.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(DBHelper.COLUMN_AGE, age);

int updatedRows = db.update(DBHelper.TABLE_NAME, values, DBHelper.COLUMN_NAME + " = ?", new String[]


{name});

if (updatedRows > 0) {
Toast.makeText(this, "Data updated successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No matching data found to update", Toast.LENGTH_SHORT).show();
}
}
}

activity_main.xml

package com.example.applicationforms;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

private EditText editTextName, editTextAge;


private DBHelper dbHelper;

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

editTextName = findViewById(R.id.editTextName);

10117702021 ROHIT GHOSH BCA 6 – B


editTextAge = findViewById(R.id.editTextAge);
Button buttonAdd = findViewById(R.id.buttonAdd);
Button buttonView = findViewById(R.id.buttonView);
Button buttonDelete = findViewById(R.id.buttonDelete);
Button buttonUpdate = findViewById(R.id.buttonUpdate);

dbHelper = new DBHelper(this);

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

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

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

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

public void addData(View view) {


String name = editTextName.getText().toString().trim();
String ageString = editTextAge.getText().toString().trim();

if (name.isEmpty() || ageString.isEmpty()) {
Toast.makeText(this, "Please enter name and age", Toast.LENGTH_SHORT).show();
return;
}

int age = Integer.parseInt(ageString);

10117702021 ROHIT GHOSH BCA 6 – B


SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, name);
values.put(DBHelper.COLUMN_AGE, age);

long newRowId = db.insert(DBHelper.TABLE_NAME, null, values);

if (newRowId == -1) {
Toast.makeText(this, "Failed to add data", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Data added successfully", Toast.LENGTH_SHORT).show();
}
}

public void viewData(View view) {


SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(
DBHelper.TABLE_NAME,
null,
null,
null,
null,
null,
null
);

StringBuilder data = new StringBuilder();


while (cursor.moveToNext()) {
int nameIndex = cursor.getColumnIndex(DBHelper.COLUMN_NAME);
int ageIndex = cursor.getColumnIndex(DBHelper.COLUMN_AGE);

if (nameIndex != -1 && ageIndex != -1) {


String name = cursor.getString(nameIndex);
int age = cursor.getInt(ageIndex);
data.append("Name: ").append(name).append(", Age: ").append(age).append("\n");
} else {
// Handle the case where the column index is not found
data.append("Invalid data in cursor").append("\n");
}
}

cursor.close();

if (data.length() == 0) {
Toast.makeText(this, "No data found", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, data.toString(), Toast.LENGTH_SHORT).show();
}
10117702021 ROHIT GHOSH BCA 6 – B
}

public void deleteData(View view) {


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

SQLiteDatabase db = dbHelper.getWritableDatabase();
int deletedRows = db.delete(DBHelper.TABLE_NAME, DBHelper.COLUMN_NAME + " = ?", new String[]{name});

if (deletedRows > 0) {
Toast.makeText(this, "Data deleted successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No matching data found to delete", Toast.LENGTH_SHORT).show();
}
}

public void updateData(View view) {


String name = editTextName.getText().toString().trim();
String ageString = editTextAge.getText().toString().trim();

if (name.isEmpty() || ageString.isEmpty()) {
Toast.makeText(this, "Please enter name and age", Toast.LENGTH_SHORT).show();
return;
}

int age = Integer.parseInt(ageString);

SQLiteDatabase db = dbHelper.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(DBHelper.COLUMN_AGE, age);

int updatedRows = db.update(DBHelper.TABLE_NAME, values, DBHelper.COLUMN_NAME + " = ?", new String[]


{name});

if (updatedRows > 0) {
Toast.makeText(this, "Data updated successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No matching data found to update", Toast.LENGTH_SHORT).show();
}
}
}

10117702021 ROHIT GHOSH BCA 6 – B


OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 13

Create an application to pick up any image from the native application gallery and display it on the
screen.

CODE

Activity_main.xml

<!-- activity_main.xml -->


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

<Button
android:id="@+id/button_pick_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Image"
android:layout_centerInParent="true" />

<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/button_pick_image"
android:layout_margin="16dp"
android:visibility="gone"
android:scaleType="centerInside" />
</RelativeLayout>

MainActivity.java

package com.example.imagedisplayerr;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static final int REQUEST_IMAGE_PICK = 1;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

10117702021 ROHIT GHOSH BCA 6 – B


setContentView(R.layout.activity_main);

Button pickImageButton = findViewById(R.id.button_pick_image);


imageView = findViewById(R.id.image_view);

pickImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickImageFromGallery();
}});
}
private void pickImageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_IMAGE_PICK);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
// Get the URI of the selected image
imageView.setVisibility(View.VISIBLE);
imageView.setImageURI(data.getData());
}}}

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 14

Read phonebook contacts using content providers and display in

list. CODE

MainActivity.java

package com.example.phonecontact;
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.content.Context;

public class MainActivity extends AppCompatActivity {

private static final int REQUEST_CONTACTS_PERMISSION = 1;


private ListView listViewContacts;
private ContactAdapter contactAdapter;

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

listViewContacts = findViewById(R.id.list_view_contacts);

// Check if the READ_CONTACTS permission has been granted


if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Permission not yet granted, request it
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS},
REQUEST_CONTACTS_PERMISSION);
} else {
// Permission already granted, fetch contacts
fetchContacts();
10117702021 ROHIT GHOSH BCA 6 – B
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CONTACTS_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, fetch
contacts fetchContacts();
} else {
// Permission denied, handle accordingly (e.g., show a message or disable functionality)
}
}
}

private void fetchContacts() {


Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);

contactAdapter = new ContactAdapter(this, cursor);


listViewContacts.setAdapter(contactAdapter);
}

private static class ContactAdapter extends CursorAdapter {

public ContactAdapter(Context context, Cursor cursor) {


super(context, cursor, 0);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textView = view.findViewById(android.R.id.text1);

int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);


if (displayNameIndex != -1) {
String contactName = cursor.getString(displayNameIndex);
textView.setText(contactName);
} else {
textView.setText("Unknown"); // Or handle the case appropriately
}
}

10117702021 ROHIT GHOSH BCA 6 – B


}
}

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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/text_view_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toTopOf="@+id/list_view_contacts"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ListView
android:id="@+id/list_view_contacts"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@+id/text_view_hello"
app:layout_constraintBottom_toBottomOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

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.READ_CONTACTS" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"

10117702021 ROHIT GHOSH BCA 6 – B


android:supportsRtl="true"
android:theme="@style/Theme.Phonecontact"
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>
</application>

</manifest>

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B


Practical – 15

Create an application to take picture using native application.

CODE

MainActivity.java

package com.example.photocapture;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE = 1;

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

public void captureImage(android.view.View view) {


Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
Toast.makeText(this, "No camera app available", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image captured successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to capture image", 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"

10117702021 ROHIT GHOSH BCA 6 – B


android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toTopOf="@+id/button_capture"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture Image"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_view_hello"
android:onClick="captureImage" />
</androidx.constraintlayout.widget.ConstraintLayout>

OUTPUT

10117702021 ROHIT GHOSH BCA 6 – B

You might also like