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

Android App Development Guide

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)
25 views62 pages

Android App Development Guide

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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" />

</[Link]>

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

We’ll create three activities:

[Link] – LinearLayout

2. [Link] – RelativeLayout

3. [Link] – ConstraintLayout

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

1. [Link] – LinearLayout
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
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>

[Link]
package [Link].prog2;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

Button btnLinear = findViewById([Link].button_linear);


[Link](new [Link]() {
private View v;

@Override
public void onClick(View v) {
this.v = v;
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
}
});
}
}

2. [Link] – RelativeLayout

✅ activity_relative.xml

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


<RelativeLayout xmlns:android="[Link]
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>
✅ [Link]
package [Link].prog2;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class RelativeActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_relative);

Button btnRelative = findViewById([Link].button_relative);


[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
}
});
}
}

3. [Link] – ConstraintLayout

✅ activity_constraint.xml

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


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
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"/>
</[Link]>

✅ [Link]

package [Link].prog2;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class RelativeActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_relative);

Button btnRelative = findViewById([Link].button_relative);


[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
}
});
}
}

[Link]: Make sure you register all three activities:

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<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="[Link]" />

<category android:name="[Link]" />


</intent-filter>
</activity>
</application>

</manifest>

Output:
3. Develop an app to implement UI components like Buttons,
TextViews, Checkboxes, and Radio Buttons.

Solution:

[Link]

package [Link].prog4;
import [Link];
import [Link];
import [Link].*;
import [Link];

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) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Initialize UI components
etName = findViewById([Link]);
btnShow = findViewById([Link]);
tvOutput = findViewById([Link]);
switchLight = findViewById([Link]);
cbMusic = findViewById([Link]);
cbReading = findViewById([Link]);
rgGender = findViewById([Link]);
rbMale = findViewById([Link]);
rbFemale = findViewById([Link]);

// Handle Button click


[Link](new [Link]() {
@Override
public void onClick(View view) {
String name = [Link]().toString();
[Link]("Hello " + name);
}
});
// Handle Switch toggle
[Link]((compoundButton, isChecked) -> {
if (isChecked) {
[Link](this, "Light is ON", Toast.LENGTH_SHORT).show();
} else {
[Link](this, "Light is OFF", Toast.LENGTH_SHORT).show();
}
});

// Handle CheckBox events


[Link]((buttonView, isChecked) -> {
if (isChecked) {
[Link](this, "You like Music",
Toast.LENGTH_SHORT).show();
}
});

[Link]((buttonView, isChecked) -> {


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

// Handle RadioGroup (Gender) selection


[Link]((group, checkedId) -> {
RadioButton selected = findViewById(checkedId);
[Link](this, "Gender: " + [Link](),
Toast.LENGTH_SHORT).show();
});
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
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:
[Link] event handling for various UI components such as clicks and
toggle switches.
Solution:

[Link]

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<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="[Link]" />

<category
android:name="[Link]" />
</intent-filter>
</activity>
</application>

</manifest>
[Link]
package [Link].pro3;
import [Link];
import [Link];
import [Link];
import [Link].*;

public class MainActivity extends AppCompatActivity {

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

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

tvResult = findViewById([Link]);
rgGender = findViewById([Link]);
rbMale = findViewById([Link]);
rbFemale = findViewById([Link]);

cbJava = findViewById([Link]);
cbPython = findViewById([Link]);
cbAndroid = findViewById([Link]);

btnSubmit = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {

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

// Gender
int selectedId = [Link]();
if (selectedId != -1) {
RadioButton selectedRadio = findViewById(selectedId);
[Link]("Gender:
").append([Link]()).append("\n");
}

// Skills
[Link]("Skills: ");
if ([Link]()) [Link]("Java ");
if ([Link]()) [Link]("Python ");
if ([Link]()) [Link]("Android ");
[Link]([Link]());
}
});
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
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>
[Link] 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
[Link]

[Link]
package [Link].program4;

import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
[Link](this);
setContentView([Link].activity_main);
}
public void onImplicitButtonClicked(View view)
{
Uri url=[Link]("[Link]
Intent i=new Intent(Intent.ACTION_VIEW, url);
startActivity(i);
}
public void onExplicitButtonClicked(View view )
{
Intent i=new Intent([Link], [Link]);
startActivity(i);
}
}
[Link]
package [Link].program4;

import [Link];
import [Link];

import [Link];
public class SecondActivity extends AppCompatActivity {
Button btnImplicitContent;
@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);
setContentView([Link].activity_second);

}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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" />
</[Link]>
Manifest file

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


<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<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="[Link]" />
<category android:name="[Link]" />
</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="[Link]
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 ([Link])

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) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

etUsername = findViewById([Link]);
etPassword = findViewById([Link]);
btnLogin = findViewById([Link]);
tvStatus = findViewById([Link]);

[Link](v -> {
String username = [Link]().toString();
String password = [Link]().toString();

if ([Link](validUsername) && [Link](validPassword)) {


[Link]("Login Successful");
[Link](this, "Welcome " + username, Toast.LENGTH_SHORT).show();
} else {
[Link](this, "Login Failed", Toast.LENGTH_SHORT).show();
[Link]("");
}
});
}
}

Output:
[Link] an application to send an SMS or make a phone call using Native
Actions with Intents.

Solution:
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

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) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
editTextPhoneNumber = findViewById([Link]);
editTextMessage = findViewById([Link]);
textViewReceivedMessages =
findViewById([Link]);
// Request SMS permissions if not granted

if (!checkSMSPermission()) {
requestSMSPermission();
}
// Register SMS receiver
IntentFilter intentFilter = new IntentFilter();
[Link]("[Link].SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
}
@Override
protected void onDestroy() {
[Link]();
unregisterReceiver(smsReceiver);
}
// Button click listener for sending SMS
public void sendMessage(View view) {
String phoneNumber =
[Link]().toString().trim();
String message = [Link]().toString();

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

private boolean checkSMSPermission() {


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

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
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>

[Link] File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
xmlns:tools="[Link]

<uses-feature
android:name="[Link]"
android:required="false" />
<uses-permission android:name="[Link].SEND_SMS"/>
<uses-permission android:name="[Link].RECEIVE_SMS"/>
<uses-permission android:name="[Link].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/[Link]"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]" />

<category android:name="[Link]" />


</intent-filter>
</activity>
</application>

</manifest>

Output:
[Link] Emulator Contact -> Store some contacts
2. Send sms to those contacts
3. Goto message in emulator and check sms
Program 14

[Link] 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
 [Link]
 [Link] (Fragment A)
 [Link] (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

[Link]
package [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity implements


[Link] {

ReceiverFragment receiverFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Add SenderFragment
getSupportFragmentManager().beginTransaction()
.replace([Link], new SenderFragment())
.commit();
// Add ReceiverFragment
receiverFragment = new ReceiverFragment();
getSupportFragmentManager().beginTransaction()
.replace([Link], receiverFragment)
.commit();
}

// Interface method called from SenderFragment


@Override
public void onDataPass(String data) {
[Link](data);
}
}

[Link]

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];

public class ReceiverFragment extends Fragment {

TextView textView;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = [Link]([Link].fragment_receiver, container, false);
textView = [Link]([Link]);
return view;
}

public void updateText(String data) {


if (textView != null) {
[Link](data);
}
}
}

[Link]

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];

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) {
[Link](context);
dataPasser = (OnDataPass) context;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {

View view = [Link]([Link].fragment_sender, container, false);

editText = [Link]([Link]);
button = [Link]([Link]);

[Link](v -> {
String text = [Link]().toString();
[Link](text);
});

return view;
}
}

activity_main.xml

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


<LinearLayout xmlns:android="[Link]
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="[Link]
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="[Link]
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>

[Link] 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.

[Link] (Step 1: Permissions )

<manifest xmlns:android="[Link]
package="[Link]">

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

<application
android:allowBackup="true"
android:label="Audio Recorder"
android:supportsRtl="true"
android:theme="@style/[Link]">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<LinearLayout
xmlns:android="[Link]
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>

[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

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) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Request permissions
[Link](this,
new String[]{[Link].RECORD_AUDIO,
[Link].WRITE_EXTERNAL_STORAGE,
[Link].READ_EXTERNAL_STORAGE},
1);

btnRecord = findViewById([Link]);
btnStop = findViewById([Link]);
btnPlay = findViewById([Link]);

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

[Link](v -> {
startRecording();
});

[Link](v -> {
stopRecordingOrPlayback();
});

[Link](v -> {
startPlaying();
});
}

private void startRecording() {


mediaRecorder = new MediaRecorder();
[Link]([Link].M
IC);
[Link]([Link].
THREE_GPP);
[Link](audioFilePath);
[Link]([Link]
.AMR_NB);

try {
[Link]();
[Link]();
[Link](this, "Recording started...",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
[Link]();
}
}

private void stopRecordingOrPlayback() {


if (mediaRecorder != null) {
[Link]();
[Link]();
mediaRecorder = null;
[Link](this, "Recording stopped",
Toast.LENGTH_SHORT).show();
}

if (mediaPlayer != null && [Link]()) {


[Link]();
[Link]();
mediaPlayer = null;
[Link](this, "Playback stopped",
Toast.LENGTH_SHORT).show();
}
}

private void startPlaying() {


mediaPlayer = new MediaPlayer();
try {
[Link](audioFilePath);
[Link]();
[Link]();
[Link](this, "Playing audio...",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
[Link]();
}
}
}
[Link] an application to showcase the use of Fragments and
Fragment Lifecycle.

Solution:

🧱 Project Structure
app/
├── java/
│ └── [Link]/
│ ├── [Link]
│ ├── [Link]
│ └── [Link]
├── res/
│ └── layout/
│ ├── activity_main.xml
│ ├── fragment_first.xml
│ └── fragment_second.xml

1. [Link]
package [Link];
import [Link];

import [Link];

import [Link];
import [Link];
import [Link];

import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].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 = [Link]();
[Link]([Link].fragment_container, fragment);
[Link]();
}
}

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class FirstFragment extends Fragment {

public FirstFragment() {}

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

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

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

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

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

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

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

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

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SecondFragment extends Fragment {

public SecondFragment() {}

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

activity_main.xml
<LinearLayout
xmlns:android="[Link]
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="[Link]
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="[Link]
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:
[Link]

activity_main.xml

[Link]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]">

<uses-permission
android:name="[Link].READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission
android:name="[Link].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/[Link]">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]"/>
<category android:name="[Link]"/>
</intent-filter>
</activity>
</application>
</manifest>

Define [Link] in [Link]

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

res/values/[Link]:

<resources xmlns:tools="[Link]
<style name="[Link]" parent="[Link]">
<!-- 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"?>


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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" />
</[Link]>

[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link].*;

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) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

editTextData = findViewById([Link]);
textViewOutput = findViewById([Link]);

findViewById([Link]).setOnClickListener(view ->
saveToInternal());
findViewById([Link]).setOnClickListener(view ->
loadFromInternal());
findViewById([Link]).setOnClickListener(view ->
saveToExternal());
findViewById([Link]).setOnClickListener(view ->
loadFromExternal());
}

private void saveToInternal() {


String data = [Link]().toString();
try {
FileOutputStream fos = openFileOutput(internalFile, MODE_PRIVATE);
[Link]([Link]());
[Link]();
showToast("Saved to internal storage");
} catch (Exception e) {
[Link]();
}
}

private void loadFromInternal() {


try {
FileInputStream fis = openFileInput(internalFile);
BufferedReader reader = new BufferedReader(new
InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line;
while((line = [Link]()) != null){
[Link](line).append("\n");
}
[Link]([Link]());
[Link]();
} catch (Exception e) {
[Link]();
}
}

private void saveToExternal() {


if (isExternalStorageWritable()) {
File file = new File(getExternalFilesDir(null), externalFile);
try {
FileOutputStream fos = new FileOutputStream(file);
[Link]([Link]().toString().getBytes());
[Link]();
showToast("Saved to external storage");
} catch (Exception e) {
[Link]();
}
}
}

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 = [Link]()) != null){
[Link](line).append("\n");
}
[Link]([Link]());
[Link]();
} catch (Exception e) {
[Link]();
}
}

private boolean isExternalStorageWritable() {


return
[Link]().equals(Environment.MEDIA_MOUNTED)
;
}

private void showToast(String message) {


[Link](this, message, Toast.LENGTH_SHORT).show();
}
}

You might also like