0% found this document useful (0 votes)
14 views62 pages

Lab PRograms1

The document outlines a series of tasks for developing Android applications, including displaying messages, using various layouts, implementing UI components, handling events, and integrating features like SMS and Google Maps. It provides code snippets for creating simple applications that demonstrate these functionalities. The tasks culminate in a mini project that applies the concepts learned throughout the exercises.

Uploaded by

sikandhar8277
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)
14 views62 pages

Lab PRograms1

The document outlines a series of tasks for developing Android applications, including displaying messages, using various layouts, implementing UI components, handling events, and integrating features like SMS and Google Maps. It provides code snippets for creating simple applications that demonstrate these functionalities. The tasks culminate in a mini project that applies the concepts learned throughout the exercises.

Uploaded by

sikandhar8277
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

1. Create a simple Android application to display a "Hello M S Ramaiah" message.

2. Design an Android application to demonstrate the use of LinearLayout, RelativeLayout,


and ConstraintLayout.
3. Develop an app to implement UI components like Buttons, TextViews, Checkboxes, and
Radio Buttons.
4. Implement event handling for various UI components such as clicks and toggle switches.
5. Create an application to demonstrate Explicit and Implicit Intents with data transfer
between Activities.
6. Create a sample application with login module (check user name and password) on
successful login change Textview “Login Successful”. On login fail alert using Toast “login
fail”
7. Build an application to send an SMS or make a phone call using Native Actions with Intents.
8. Develop an application to showcase the use of Fragments and Fragment Lifecycle.
9. Create a multi-screen application with communication between Fragments and Activities.
10. Design an application to integrate Google Maps and display the user's current location.
11. Create an Android application to play and record audio or video using Android Media APIs.
12. Create an app to persist data using SQLite by creating a table, inserting, updating, and
deleting records.
13. Build an application to save and retrieve data from internal and external storage.
14. Implement Mini project based on the concept learnt in Theory

1. Create a simple Android application to display a "Hello


M S Ramaiah" message.
Solution:

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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello M S Ramaiah"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output:
2. Design an Android application to demonstrate the use of LinearLayout,
RelativeLayout, and ConstraintLayout.
Solution:Project Structure:

We’ll create three activities:

1.MainActivity.java – LinearLayout

2. RelativeActivity.java – RelativeLayout

3. ConstraintActivity.java – ConstraintLayout

Each activity will show a basic layout example and a button to move to the next layout.

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

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

<Button
android:id="@+id/btnFirst"
android:layout_width="0dp"
android:layout_height="94dp"
android:layout_weight="1"
android:onClick="loadFirstFragment"
android:text="First Fragment"

/>

<Button
android:id="@+id/btnSecond"
android:layout_width="0dp"
android:layout_height="88dp"
android:layout_weight="1"
android:onClick="loadSecondFragment"
android:text="Second Fragment" />

</LinearLayout>

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

MainActivity.java
package com.example.prog2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


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

Button btnLinear = findViewById(R.id.button_linear);


btnLinear.setOnClickListener(new View.OnClickListener() {
private View v;

@Override
public void onClick(View v) {
this.v = v;
Intent intent = new Intent(MainActivity.this, RelativeActivity.class);
startActivity(intent);
}
});
}
}

2. RelativeActivity.java – RelativeLayout

✅ activity_relative.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:padding="16dp">

<TextView
android:id="@+id/relative_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is RelativeLayout"
android:textSize="20sp" />

<Button
android:id="@+id/button_relative"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/relative_text"
android:layout_marginTop="20dp"
android:text="Go to ConstraintLayout" />
</RelativeLayout>
✅ RelativeActivity.java
package com.example.prog2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class RelativeActivity extends AppCompatActivity {


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

Button btnRelative = findViewById(R.id.button_relative);


btnRelative.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RelativeActivity.this, ConstraintActivity.class);
startActivity(intent);
}
});
}
}

3. ConstraintActivity.java – ConstraintLayout

✅ activity_constraint.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<TextView
android:id="@+id/constraint_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is ConstraintLayout"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="100dp"/>

<Button
android:id="@+id/button_constraint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back to LinearLayout"
app:layout_constraintTop_toBottomOf="@id/constraint_text"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

✅ RelativeActivity.java

package com.example.prog2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class RelativeActivity extends AppCompatActivity {


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

Button btnRelative = findViewById(R.id.button_relative);


btnRelative.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RelativeActivity.this, ConstraintActivity.class);
startActivity(intent);
}
});
}
}

AndroidManifest.xml: Make sure you register all three activities:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<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"
android:supportsRtl="true"
android:theme="@style/Theme.Prog2"
tools:targetApi="31">
<activity android:name=".ConstraintActivity"/>
<activity android:name=".RelativeActivity"/>
<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:
3. Develop an app to implement UI components like Buttons,
TextViews, Checkboxes, and Radio Buttons.

Solution:

MainActivity.Java

package com.example.prog4;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText etName;
Button btnShow;
TextView tvOutput;
Switch switchLight;
CheckBox cbMusic, cbReading;
RadioGroup rgGender;
RadioButton rbMale, rbFemale;

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

// Initialize UI components
etName = findViewById(R.id.etName);
btnShow = findViewById(R.id.btnShow);
tvOutput = findViewById(R.id.tvOutput);
switchLight = findViewById(R.id.switchLight);
cbMusic = findViewById(R.id.cbMusic);
cbReading = findViewById(R.id.cbReading);
rgGender = findViewById(R.id.rgGender);
rbMale = findViewById(R.id.rbMale);
rbFemale = findViewById(R.id.rbFemale);

// Handle Button click


btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = etName.getText().toString();
tvOutput.setText("Hello " + name);
}
});
// Handle Switch toggle
switchLight.setOnCheckedChangeListener((compoundButton, isChecked) -> {
if (isChecked) {
Toast.makeText(this, "Light is ON", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Light is OFF", Toast.LENGTH_SHORT).show();
}
});

// Handle CheckBox events


cbMusic.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
Toast.makeText(this, "You like Music",
Toast.LENGTH_SHORT).show();
}
});

cbReading.setOnCheckedChangeListener((buttonView, isChecked) -> {


if (isChecked) {
Toast.makeText(this, "You like Reading",
Toast.LENGTH_SHORT).show();
}
});

// Handle RadioGroup (Gender) selection


rgGender.setOnCheckedChangeListener((group, checkedId) -> {
RadioButton selected = findViewById(checkedId);
Toast.makeText(this, "Gender: " + selected.getText(),
Toast.LENGTH_SHORT).show();
});
}
}

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

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

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

<TextView
android:id="@+id/tvOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Output will appear here"
android:textSize="16sp"
android:paddingTop="8dp" />

<Switch
android:id="@+id/switchLight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light Switch" />
<CheckBox
android:id="@+id/cbMusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Music" />

<CheckBox
android:id="@+id/cbReading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reading" />

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

<RadioButton
android:id="@+id/rbMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />

<RadioButton
android:id="@+id/rbFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>

</LinearLayout>
Output:
4.Implement event handling for various UI components such as clicks and
toggle switches.
Solution:

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

<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"
android:supportsRtl="true"
android:theme="@style/Theme.Pro3"
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>
mainActivity.java
package com.example.pro3;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.*;

public class MainActivity extends AppCompatActivity {

TextView tvResult;
RadioGroup rgGender;
RadioButton rbMale, rbFemale;
CheckBox cbJava, cbPython, cbAndroid;
Button btnSubmit;

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

tvResult = findViewById(R.id.tvResult);
rgGender = findViewById(R.id.rgGender);
rbMale = findViewById(R.id.rbMale);
rbFemale = findViewById(R.id.rbFemale);

cbJava = findViewById(R.id.cbJava);
cbPython = findViewById(R.id.cbPython);
cbAndroid = findViewById(R.id.cbAndroid);

btnSubmit = findViewById(R.id.btnSubmit);

btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

StringBuilder result = new StringBuilder("You selected:\n");

// Gender
int selectedId = rgGender.getCheckedRadioButtonId();
if (selectedId != -1) {
RadioButton selectedRadio = findViewById(selectedId);
result.append("Gender:
").append(selectedRadio.getText()).append("\n");
}

// Skills
result.append("Skills: ");
if (cbJava.isChecked()) result.append("Java ");
if (cbPython.isChecked()) result.append("Python ");
if (cbAndroid.isChecked()) result.append("Android ");
tvResult.setText(result.toString());
}
});
}
}

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

<!-- TextView -->


<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:text="Your Selection:"
android:textAlignment="center"
android:textSize="18sp" />

<!-- RadioGroup for Gender -->


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

<RadioButton
android:id="@+id/rbMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"/>

<RadioButton
android:id="@+id/rbFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>
</RadioGroup>

<!-- CheckBoxes for Skills -->


<CheckBox
android:id="@+id/cbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"/>

<CheckBox
android:id="@+id/cbPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Python"/>

<CheckBox
android:id="@+id/cbAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android"/>

<!-- Button -->


<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_marginTop="16dp"/>
</LinearLayout>
5.Create an application to demonstrate Explicit and Implicit Intents with data
transfer between Activities.

/* Explicit Intent: This involves navigating from one activity to another within the same
application. Implicit Intent: This involves triggering an action that can be handled by another
application. */
NOTE:.Goto device manager->select the emulator and wipe out data) and set DNS server IP as
8.8.8.8

Mainactivity.java
package com.example.program4;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
}
public void onImplicitButtonClicked(View view)
{
Uri url=Uri.parse("https://www.google.com");
Intent i=new Intent(Intent.ACTION_VIEW, url);
startActivity(i);
}
public void onExplicitButtonClicked(View view )
{
Intent i=new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
}
}
SecondActivity.java
package com.example.program4;

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

import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
Button btnImplicitContent;
@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:gravity="center"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/implicit_intent"
android:onClick="onImplicitButtonClicked"
style="?android:attr/buttonBarButtonStyle" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/explicit_intent"
android:onClick="onExplicitButtonClicked"
style="?android:attr/buttonBarButtonStyle" />
</LinearLayout>
Activity_second.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=".SecondActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome_to_explicit_intent"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Manifest file

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<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"
android:supportsRtl="true"
android:theme="@style/Theme.PRogram4"
tools:targetApi="31">
<activity
android:name=".SecondActivity"
android:exported="false">
</activity>

<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:
On click of implicit intent button appears below screen
On click of Explicit intent button appears below screen

6. Create a sample application with login module (check user name and
password) on successful login change Textview “Login Successful”. On login
fail alert using Toast “login fail”

1. XML Layout (activity_main.xml)


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

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

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

<Button
android:id="@+id/btnLogin"
android:text="Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />

<TextView
android:id="@+id/tvStatus"
android:text=""
android:textSize="18sp"
android:textColor="#008000"
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

3. Java Code (MainActivity.java)

public class MainActivity extends AppCompatActivity {

EditText etUsername, etPassword;


Button btnLogin;
TextView tvStatus;

final String validUsername = "admin";


final String validPassword = "1234";

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

etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
tvStatus = findViewById(R.id.tvStatus);

btnLogin.setOnClickListener(v -> {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();

if (username.equals(validUsername) && password.equals(validPassword)) {


tvStatus.setText("Login Successful");
Toast.makeText(this, "Welcome " + username, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Login Failed", Toast.LENGTH_SHORT).show();
tvStatus.setText("");
}
});
}
}

Output:
7.Build an application to send an SMS or make a phone call using Native
Actions with Intents.

Solution:
Mainactivity.java
package com.example.sms;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;

public class MainActivity extends AppCompatActivity {

private static final int SMS_PERMISSION_CODE = 101;


private EditText editTextPhoneNumber;
private EditText editTextMessage;
private TextView textViewReceivedMessages;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
editTextMessage = findViewById(R.id.editTextMessage);
textViewReceivedMessages =
findViewById(R.id.textViewReceivedMessages);
// Request SMS permissions if not granted

if (!checkSMSPermission()) {
requestSMSPermission();
}
// Register SMS receiver
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}
// Button click listener for sending SMS
public void sendMessage(View view) {
String phoneNumber =
editTextPhoneNumber.getText().toString().trim();
String message = editTextMessage.getText().toString();

if (phoneNumber.isEmpty()) {
Toast.makeText(this, "Please enter a valid phone number",
Toast.LENGTH_SHORT).show();
return;
}
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(this, "Message sent", Toast.LENGTH_SHORT).show();
} catch (IllegalArgumentException e) {
Toast.makeText(this, "Invalid phone number format",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to send message",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
// Check if SMS permission is granted

private boolean checkSMSPermission() {


return ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) ==
PackageManager.PERMISSION_GRANTED;
}
// Request SMS permission
private void requestSMSPermission() {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.SEND_SMS},
SMS_PERMISSION_CODE);
}
// SMS receiver
private final BroadcastReceiver smsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])
pdu);
String senderPhoneNumber =
smsMessage.getDisplayOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
textViewReceivedMessages.append("From: " +
senderPhoneNumber + "\n");
textViewReceivedMessages.append("Message: " +
messageBody + "\n\n");
}
}
}
}
};
}

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="@color/white"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:autofillHints="Enter phone number"
android:hint="Enter phone number"
android:inputType="phone" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPhoneNumber"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:autofillHints="Enter Message"
android:hint="Enter Message" />

<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_below="@id/editTextMessage"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:onClick="sendMessage"
tools:ignore="HardcodedText,UsingOnClickInXml" />

<TextView
android:id="@+id/textViewReceivedMessages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/buttonSend"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:textColor="@color/black" />

</RelativeLayout>

AndroidManifest.xml File
<?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-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>

<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"
android:supportsRtl="true"
android:theme="@style/Theme.SMS"
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:
1.Goto Emulator Contact -> Store some contacts
2. Send sms to those contacts
3. Goto message in emulator and check sms
Program 14

9.Create a multi-screen application with communication between


Fragments and Activities.
Solution:

The app has:


 Fragment A with an EditText and Button.
 When the Button is clicked, the entered text is sent to MainActivity.
 MainActivity receives the data and passes it to Fragment B to display it.

Project Structure
 MainActivity.java
 SenderFragment.java (Fragment A)
 ReceiverFragment.java (Fragment B)
 XML Layouts for each

Key Concepts Demonstrated:

Concept Use
Fragments Modular screens inside activity
Interface Callback To communicate Fragment → Activity
Activity Logic Transfers data between fragments

MainActivity.Java
package com.example.fra;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements


SenderFragment.OnDataPass {

ReceiverFragment receiverFragment;

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

// Add SenderFragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainerA, new SenderFragment())
.commit();
// Add ReceiverFragment
receiverFragment = new ReceiverFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainerB, receiverFragment)
.commit();
}

// Interface method called from SenderFragment


@Override
public void onDataPass(String data) {
receiverFragment.updateText(data);
}
}

ReceiverFragment.java

package com.example.fra;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ReceiverFragment extends Fragment {

TextView textView;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_receiver, container, false);
textView = view.findViewById(R.id.tvResult);
return view;
}

public void updateText(String data) {


if (textView != null) {
textView.setText(data);
}
}
}

SenderFragment.Java

package com.example.fra;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class SenderFragment extends Fragment {

EditText editText;
Button button;
OnDataPass dataPasser;

public interface OnDataPass {


void onDataPass(String data);
}

@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
dataPasser = (OnDataPass) context;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_sender, container, false);

editText = view.findViewById(R.id.etInput);
button = view.findViewById(R.id.btnSend);

button.setOnClickListener(v -> {
String text = editText.getText().toString();
dataPasser.onDataPass(text);
});

return view;
}
}

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

<FrameLayout
android:id="@+id/fragmentContainerA"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"/>

<FrameLayout
android:id="@+id/fragmentContainerB"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"/>
</LinearLayout>

fragment_receiver.xml

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


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

<TextView
android:id="@+id/tvResult"
android:text="Waiting for data..."
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"/>
</FrameLayout>

fragment_sender.xml

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


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

<EditText
android:id="@+id/etInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter something" />

<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send to Fragment B" />
</LinearLayout>

10.Create an Android application to play and record audio or video using


Android Media APIs. a activity with one record, stop and play button
Here is a simple Android app that allows you to record, stop, and play audio using Android’s Media APIs.
This example is written in Java and includes:

 Record button to start recording audio.


 Stop button to stop recording or playing.
 Play button to play the recorded audio.

AndroidManifest.xml (Step 1: Permissions )

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.audiorecorder">

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
android:allowBackup="true"
android:label="Audio Recorder"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="20dp">

<Button
android:id="@+id/btnRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"/>

<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"/>

<Button
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"/>
</LinearLayout>

MainActivity.java
package com.example.audiorecorder;
import android.Manifest;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private Button btnRecord, btnStop, btnPlay;


private MediaRecorder mediaRecorder;
private MediaPlayer mediaPlayer;
private String audioFilePath;

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

// Request permissions
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE},
1);

btnRecord = findViewById(R.id.btnRecord);
btnStop = findViewById(R.id.btnStop);
btnPlay = findViewById(R.id.btnPlay);

audioFilePath =
getExternalFilesDir(Environment.DIRECTORY_MUSIC).getA
bsolutePath() + "/recording.3gp";

btnRecord.setOnClickListener(v -> {
startRecording();
});

btnStop.setOnClickListener(v -> {
stopRecordingOrPlayback();
});

btnPlay.setOnClickListener(v -> {
startPlaying();
});
}

private void startRecording() {


mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.M
IC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.
THREE_GPP);
mediaRecorder.setOutputFile(audioFilePath);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder
.AMR_NB);

try {
mediaRecorder.prepare();
mediaRecorder.start();
Toast.makeText(this, "Recording started...",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}

private void stopRecordingOrPlayback() {


if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
Toast.makeText(this, "Recording stopped",
Toast.LENGTH_SHORT).show();
}

if (mediaPlayer != null && mediaPlayer.isPlaying()) {


mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
Toast.makeText(this, "Playback stopped",
Toast.LENGTH_SHORT).show();
}
}

private void startPlaying() {


mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(audioFilePath);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(this, "Playing audio...",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
8.Develop an application to showcase the use of Fragments and
Fragment Lifecycle.

Solution:

🧱 Project Structure
app/
├── java/
│ └── com.example.fragmentdemo/
│ ├── MainActivity.java
│ ├── FirstFragment.java
│ └── SecondFragment.java
├── res/
│ └── layout/
│ ├── activity_main.xml
│ ├── fragment_first.xml
│ └── fragment_second.xml

1. MainActivity.java
package com.example.fragmentdemo;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

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

public class MainActivity extends AppCompatActivity {


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

// Load the default fragment


loadFragment(new FirstFragment());
}

// Called by android:onClick="loadFirstFragment"
public void loadFirstFragment(View view) {
loadFragment(new FirstFragment());
}

// Called by android:onClick="loadSecondFragment"
public void loadSecondFragment(View view) {
loadFragment(new SecondFragment());
}

private void loadFragment(Fragment fragment) {


FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_container, fragment);
ft.commit();
}
}

FirstFragment.java

package com.example.fragmentdemo;

import android.os.Bundle;
import android.util.Log;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FirstFragment extends Fragment {

public FirstFragment() {}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FragmentLifecycle", "FirstFragment - onCreate");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FragmentLifecycle", "FirstFragment - onCreateView");
return inflater.inflate(R.layout.fragment_first, container, false);
}

@Override
public void onStart() {
super.onStart();
Log.d("FragmentLifecycle", "FirstFragment - onStart");
}

@Override
public void onResume() {
super.onResume();
Log.d("FragmentLifecycle", "FirstFragment - onResume");
}

@Override
public void onPause() {
super.onPause();
Log.d("FragmentLifecycle", "FirstFragment - onPause");
}

@Override
public void onStop() {
super.onStop();
Log.d("FragmentLifecycle", "FirstFragment - onStop");
}

@Override
public void onDestroyView() {
super.onDestroyView();
Log.d("FragmentLifecycle", "FirstFragment - onDestroyView");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d("FragmentLifecycle", "FirstFragment - onDestroy");
}
}

SecondFragment.java

package com.example.fragmentdemo;

import android.os.Bundle;
import android.util.Log;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SecondFragment extends Fragment {

public SecondFragment() {}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FragmentLifecycle", "SecondFragment - onCreateView");
return inflater.inflate(R.layout.fragment_second, container, false);
}
}

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

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

<Button
android:id="@+id/btnFirst"
android:layout_width="0dp"
android:layout_height="94dp"
android:layout_weight="1"
android:onClick="loadFirstFragment"
android:text="First Fragment"

/>

<Button
android:id="@+id/btnSecond"
android:layout_width="0dp"
android:layout_height="88dp"
android:layout_weight="1"
android:onClick="loadSecondFragment"
android:text="Second Fragment" />

</LinearLayout>

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</LinearLayout>

fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#C8E6C9"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:text="This is First Fragment"
android:textSize="20sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>

fragment_second.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#FFCDD2"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="This is Second Fragment"
android:textSize="20sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>

📲 Output

 App starts with FirstFragment


 User can switch between First and Second Fragments using buttons
 Logcat will show lifecycle callbacks like onCreateView, onStart, onStop etc.

Fragment Lifecycle :

Method Description
onAttach() Fragment is attached to activity
onCreate() Initialize fragment
onCreateView() Create UI for fragment
onStart() Fragment becomes visible
onResume() Fragment is interacting with user
onPause() Fragment is partially hidden
onStop() Fragment no longer visible
onDestroyView() Remove UI elements
onDestroy() Final cleanup
onDetach() Fragment is detached from activity
13. Build an application to save and retrieve data from internal
and external storage.
Solution:

Save and retrieve data using:

Internal Storage: Private to your app.

External Storage: Shared/public (e.g., Downloads folder).

Prerequisites:
Android Studio

Target SDK >= 29

Permissions for external storage (handled for Android 10+ using MediaStore or SAF)

File Structure:
MainActivity.java

activity_main.xml

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.storageapp">

<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/> <!-- Needed only up to Android 9 -->

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

Define Theme.StorageApp in themes.xml

If you want to keep a custom theme, define it in:

res/values/themes.xml:

<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Theme.StorageApp" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryDark">@color/purple_700</item>
<item name="colorAccent">@color/teal_200</item>here -->
</style>
</resources>

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">
<EditText
android:id="@+id/editTextData"
android:layout_width="360dp"
android:layout_height="70dp"
android:layout_marginStart="24dp"
android:layout_marginTop="144dp"
android:layout_marginEnd="24dp"
android:hint="Enter data to save"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/btnSaveInternal"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="64dp"
android:text="Save to Internal"
app:layout_constraintTop_toBottomOf="@+id/editTextData"
tools:layout_editor_absoluteX="0dp" />

<Button
android:id="@+id/btnLoadInternal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="28dp"
android:layout_marginEnd="16dp"
android:text="Load from Internal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnSaveInternal" />

<Button
android:id="@+id/btnSaveExternal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Save to External"
app:layout_constraintTop_toBottomOf="@+id/btnLoadInternal"
tools:layout_editor_absoluteX="0dp" />
<Button
android:id="@+id/btnLoadExternal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="48dp"
android:layout_marginEnd="16dp"
android:text="Load from External"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnSaveExternal" />

<TextView
android:id="@+id/textViewOutput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:paddingTop="16dp"
android:text="Output will be shown here"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnLoadExternal" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.storageapp;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Environment;
import android.widget.*;
import java.io.*;

public class MainActivity extends AppCompatActivity {


EditText editTextData;
TextView textViewOutput;

final String internalFile = "internal_data.txt";


final String externalFile = "external_data.txt";

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

editTextData = findViewById(R.id.editTextData);
textViewOutput = findViewById(R.id.textViewOutput);

findViewById(R.id.btnSaveInternal).setOnClickListener(view ->
saveToInternal());
findViewById(R.id.btnLoadInternal).setOnClickListener(view ->
loadFromInternal());
findViewById(R.id.btnSaveExternal).setOnClickListener(view ->
saveToExternal());
findViewById(R.id.btnLoadExternal).setOnClickListener(view ->
loadFromExternal());
}

private void saveToInternal() {


String data = editTextData.getText().toString();
try {
FileOutputStream fos = openFileOutput(internalFile, MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
showToast("Saved to internal storage");
} catch (Exception e) {
e.printStackTrace();
}
}

private void loadFromInternal() {


try {
FileInputStream fis = openFileInput(internalFile);
BufferedReader reader = new BufferedReader(new
InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line;
while((line = reader.readLine()) != null){
sb.append(line).append("\n");
}
textViewOutput.setText(sb.toString());
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private void saveToExternal() {


if (isExternalStorageWritable()) {
File file = new File(getExternalFilesDir(null), externalFile);
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(editTextData.getText().toString().getBytes());
fos.close();
showToast("Saved to external storage");
} catch (Exception e) {
e.printStackTrace();
}
}
}

private void loadFromExternal() {


File file = new File(getExternalFilesDir(null), externalFile);
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new
InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line;
while((line = reader.readLine()) != null){
sb.append(line).append("\n");
}
textViewOutput.setText(sb.toString());
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private boolean isExternalStorageWritable() {


return
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
;
}

private void showToast(String message) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}

You might also like