Android App Development Guide
Android App Development Guide
activity_main.xml
<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:
[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];
@Override
public void onClick(View v) {
this.v = v;
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
}
});
}
}
2. [Link] – RelativeLayout
✅ activity_relative.xml
<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];
3. [Link] – ConstraintLayout
✅ activity_constraint.xml
<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];
<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]" />
</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];
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]);
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]
<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].*;
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) {
// 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">
<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>
<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"/>
/* 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
}
}
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
<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”
<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>
@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();
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];
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
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]" />
</manifest>
Output:
[Link] Emulator Contact -> Store some contacts
2. Send sms to those contacts
3. Goto message in emulator and check sms
Program 14
Project Structure
[Link]
[Link] (Fragment A)
[Link] (Fragment B)
XML Layouts for each
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];
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();
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
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;
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
EditText editText;
Button button;
OnDataPass dataPasser;
@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) {
editText = [Link]([Link]);
button = [Link]([Link]);
[Link](v -> {
String text = [Link]().toString();
[Link](text);
});
return view;
}
}
activity_main.xml
<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
<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
<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>
<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];
@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();
});
}
try {
[Link]();
[Link]();
[Link](this, "Recording started...",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
[Link]();
}
}
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];
// 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());
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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 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
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:
Prerequisites:
Android Studio
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>
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
<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].*;
@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());
}