Table of Contents
Introduction to Activities and Navigation
Understanding Activities and Their Lifecycle
2.1 What is an Activity?
2.2 Activity Lifecycle Explained
2.3 Real-Life Example: E-Commerce App
2.4 Best Practices and Exception Handling
Intents: Passing Data Between Activities
3.1 What are Intents?
3.2 Explicit and Implicit Intents
3.3 Real-Life Example: Food Delivery App
3.4 Code Example: Passing Data
3.5 Pros, Cons, and Alternatives
Navigation Components: NavHost and NavController
4.1 Introduction to Navigation Components
4.2 Setting Up Navigation in Android Studio
4.3 Real-Life Example: Social Media App
4.4 Code Example: Navigation Graph
4.5 Best Practices and Exception Handling
Fragments: Basics and Implementation
5.1 What are Fragments?
5.2 Fragment Lifecycle
5.3 Real-Life Example: Fitness Tracker App
5.4 Code Example: Fragment Implementation
5.5 Pros, Cons, and Alternatives
Backstack Management and Navigation Patterns
6.1 Understanding the Backstack
6.2 Navigation Patterns: Single Activity vs. Multiple Activities
6.3 Real-Life Example: Travel Booking App
6.4 Code Example: Backstack Management
6.5 Best Practices and Exception Handling
Practical Exercise: Building a Multi-Screen App
7.1 Project Overview: Recipe App
7.2 Step-by-Step Implementation
7.3 Complete Code Example
7.4 Testing and Debugging
Conclusion and Next Steps
1. Introduction to Activities and Navigation
Activities and navigation form the backbone of Android app development. Activities represent individual screens, while navigation ensures seamless transitions between them. This module explores Activities, Intents, Navigation Components, Fragments, and backstack management, using real-life examples like e-commerce, food delivery, and social media apps. Whether you're a beginner or advancing your skills, this guide provides user-friendly, step-by-step instructions with detailed code examples, best practices, and exception handling to help you build robust multi-screen apps.
2. Understanding Activities and Their Lifecycle
2.1 What is an Activity?
An Activity is a single screen in an Android app with a user interface. It’s a core component that handles user interactions, such as button clicks or text input. For example, in a messaging app, the chat screen is an Activity.
2.2 Activity Lifecycle Explained
The Activity lifecycle defines the stages an Activity goes through, from creation to destruction. Understanding this is crucial for managing resources and ensuring smooth user experiences.
onCreate(): Initializes the Activity, sets up the UI, and restores saved state.
onStart(): Activity becomes visible but not interactive.
onResume(): Activity is in the foreground and interactive.
onPause(): Activity is partially obscured (e.g., dialog appears).
onStop(): Activity is no longer visible.
onDestroy(): Activity is destroyed, freeing resources.
onRestart(): Activity resumes after being stopped.
2.3 Real-Life Example: E-Commerce App
In an e-commerce app like Amazon, the product listing screen is an Activity. When a user clicks a product, a new Activity (product details) is launched. The lifecycle ensures the app saves the user’s cart state during onPause() and restores it in onResume().
2.4 Best Practices and Exception Handling
Save Instance State: Use onSaveInstanceState() to save data like user input before configuration changes (e.g., screen rotation).
Avoid Heavy Operations in onCreate(): Prevent lag by offloading tasks to background threads.
Exception Handling: Handle null pointer exceptions when accessing UI elements.
Example Code:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Lifecycle", "onCreate called");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("key", "value");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String value = savedInstanceState.getString("key");
Log.d("Lifecycle", "Restored: " + value);
}
}
Pros: Structured lifecycle management ensures predictable behavior.
Cons: Overcomplicating lifecycle methods can lead to bugs.
Alternatives: Use ViewModel to manage UI-related data across configuration changes.
3. Intents: Passing Data Between Activities
3.1 What are Intents?
Intents are messaging objects used to request actions, such as starting a new Activity or sharing data with another app.
3.2 Explicit and Implicit Intents
Explicit Intents: Specify the target Activity (e.g., navigate from HomeActivity to DetailActivity).
Implicit Intents: Request an action without specifying the component (e.g., open a URL in a browser).
3.3 Real-Life Example: Food Delivery App
In a food delivery app like Uber Eats, selecting a restaurant launches a new Activity displaying the menu. An Intent carries the restaurant ID to the menu Activity.
3.4 Code Example: Passing Data
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.navigateButton);
button.setOnClickListener(v -> {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("restaurantName", "Pizza Hut");
intent.putExtra("restaurantId", 123);
startActivity(intent);
});
}
}
DetailActivity.java:
public class DetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
TextView textView = findViewById(R.id.detailText);
Intent intent = getIntent();
String name = intent.getStringExtra("restaurantName");
int id = intent.getIntExtra("restaurantId", -1);
textView.setText("Restaurant: " + name + ", ID: " + id);
}
}
3.5 Pros, Cons, and Alternatives
Pros: Intents are versatile for inter-Activity communication and external app interactions.
Cons: Improper data handling can cause crashes (e.g., missing extras).
Alternatives: Use Navigation Components for modern navigation or EventBus for event-driven communication.
4. Navigation Components: NavHost and NavController
4.1 Introduction to Navigation Components
The Navigation Component simplifies navigation using a navigation graph, NavHost, and NavController. It centralizes navigation logic, making it easier to manage complex flows.
4.2 Setting Up Navigation in Android Studio
Add dependencies in build.gradle:
implementation "androidx.navigation:navigation-fragment:2.7.7"
implementation "androidx.navigation:navigation-ui:2.7.7"
Create a navigation graph (res/navigation/nav_graph.xml).
Add a NavHostFragment to your Activity layout.
4.3 Real-Life Example: Social Media App
In a social media app like Instagram, the Navigation Component manages transitions between the feed, profile, and messages screens within a single Activity.
4.4 Code Example: Navigation Graph
nav_graph.xml:
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_graph"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name=".HomeFragment"
android:label="Home">
<action
android:id="@+id/action_home_to_detail"
app:destination="@id/detailFragment" />
</fragment>
<fragment
android:id="@+id/detailFragment"
android:name=".DetailFragment"
android:label="Detail" />
</navigation>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
}
}
4.5 Best Practices and Exception Handling
Use Safe Args for type-safe navigation.
Handle backstack to prevent duplicate fragments.
Catch IllegalArgumentException for invalid navigation actions.
5. Fragments: Basics and Implementation
5.1 What are Fragments?
Fragments are modular UI components within an Activity, enabling reusable and dynamic layouts. They’re ideal for tablets or apps with multiple UI sections.
5.2 Fragment Lifecycle
Similar to Activities, Fragments have a lifecycle: onCreate(), onCreateView(), onStart(), etc.
5.3 Real-Life Example: Fitness Tracker App
In a fitness tracker app, one Activity hosts Fragments for steps, calories, and heart rate, allowing users to swipe between metrics.
5.4 Code Example: Fragment Implementation
HomeFragment.java:
public class HomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
activity_main.xml:
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new HomeFragment())
.commit();
}
}
}
5.5 Pros, Cons, and Alternatives
Pros: Fragments enable modular UI and support responsive designs.
Cons: Complex Fragment transactions can lead to bugs.
Alternatives: Use Jetpack Compose for modern UI development.
6. Backstack Management and Navigation Patterns
6.1 Understanding the Backstack
The backstack tracks the order of Activities or Fragments, allowing users to navigate backward using the back button.
6.2 Navigation Patterns: Single Activity vs. Multiple Activities
Single Activity: Use one Activity with multiple Fragments (modern approach).
Multiple Activities: Use separate Activities for each screen (traditional).
6.3 Real-Life Example: Travel Booking App
In a travel booking app, users navigate from search to results to booking. The Navigation Component manages the backstack to ensure smooth back navigation.
6.4 Code Example: Backstack Management
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
navController.navigate(R.id.detailFragment);
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
Log.d("Navigation", "Current destination: " + destination.getLabel());
});
6.5 Best Practices and Exception Handling
Use popBackStack() to control back navigation.
Handle IllegalStateException for Fragment transactions.
7. Practical Exercise: Building a Multi-Screen App
7.1 Project Overview: Recipe App
Create a Recipe app with a home screen listing recipes and a detail screen showing recipe details, using Intents for navigation.
7.2 Step-by-Step Implementation
Create a new project in Android Studio.
Design the home screen layout with a RecyclerView.
Implement an Intent to navigate to the detail screen.
Handle data passing and display in the detail screen.
7.3 Complete Code Example
activity_main.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<String> recipes = Arrays.asList("Pizza", "Pasta", "Salad");
recyclerView.setAdapter(new RecipeAdapter(recipes, recipe -> {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("recipeName", recipe);
startActivity(intent);
}));
}
}
RecipeAdapter.java:
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder> {
private List<String> recipes;
private Consumer<String> onItemClick;
public RecipeAdapter(List<String> recipes, Consumer<String> onItemClick) {
this.recipes = recipes;
this.onItemClick = onItemClick;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String recipe = recipes.get(position);
holder.textView.setText(recipe);
holder.itemView.setOnClickListener(v -> onItemClick.accept(recipe));
}
@Override
public int getItemCount() {
return recipes.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(android.R.id.text1);
}
}
}
activity_detail.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/recipeDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="18sp" />
</LinearLayout>
DetailActivity.java:
public class DetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
TextView recipeDetail = findViewById(R.id.recipeDetail);
String recipeName = getIntent().getStringExtra("recipeName");
recipeDetail.setText("Recipe: " + recipeName);
}
}
7.4 Testing and Debugging
Test navigation by clicking a recipe and verifying the detail screen.
Debug using Logcat to trace Intent data and lifecycle events.
Handle edge cases like null extras or configuration changes.
8. Conclusion and Next Steps
This module covered Activities, Intents, Navigation Components, Fragments, and backstack management with practical examples. Practice by extending the Recipe app with Fragments or Navigation Components. In the next module, explore data persistence and networking for dynamic apps.
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam