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

Mobile Application Development

The document provides a comprehensive guide on using Android Fragments and Firebase in mobile application development. It covers the purpose and types of fragments, their lifecycle, and how to implement tabbed navigation using TabLayout and ViewPager2. Additionally, it explains Firebase's features, including authentication and real-time database integration, along with practical examples and setup instructions for Android Studio.

Uploaded by

Huzaifa
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)
16 views55 pages

Mobile Application Development

The document provides a comprehensive guide on using Android Fragments and Firebase in mobile application development. It covers the purpose and types of fragments, their lifecycle, and how to implement tabbed navigation using TabLayout and ViewPager2. Additionally, it explains Firebase's features, including authentication and real-time database integration, along with practical examples and setup instructions for Android Studio.

Uploaded by

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

Tabbed layout Code:

TabLayout tabLayout = findViewById(R.id.tabLayout);


ViewPager2 viewPager = findViewById(R.id.viewPager);

TabAdapter adapter = new TabAdapter(this);


viewPager.setAdapter(adapter);

new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {


tab.setText("Tab " + (position + 1));
}).attach();

Fragmentation Slide
Lecture Objectives

The document focuses on:

1. Understanding Fragments:

Their purpose and usage in Android applications.

2. Differentiating Fragments:

Between static and dynamic types.

3. Fragment Lifecycle:

Exploring their lifecycle and how fragments communicate with activities.

4. Tabbed Activities:

Learning to create tabbed navigation using fragments.

1.1 Introduction to Fragments


Definition

 What are Fragments?

Fragments are modular


components within an activity. Think of them as "sub-
activities" or reusable UI blocks.

 Why use Fragments?


o To make apps modular and responsive.
o Fragments can be reused in multiple activities, enhancing code efficiency.

Types of Fragments
1. Static Fragments:
o Defined in XML layout files.
o They are fixed and always a part of the activity.
o Their lifecycle is tied directly to the activity hosting them.
2. Dynamic Fragments:
o Defined in XML but added or replaced programmatically using the

FragmentManager class.
o More flexible, as they can be changed at runtime.

Uses Cases of Fragments


 Tabbed Navigation:

Examples include apps with swipe able tabs.

 Master-Detail Flow:

Useful in apps that display a list and detailed content side by side (e.g.,
email apps).
1.2 Fragment Lifecycle and Communication

Lifecycle of Fragments
Fragments share similarities with activities but have their own lifecycle methods:

1. onAttach():

Called when the fragment is associated with an activity.

2. onCreate():

Used for initialization, like loading data.


3. onCreateView():

Inflates( ‫ )پھوالنا‬Create the fragment layout.


4. onActivityCreated():
Runs after the activity's onCreate() method.

5. onDestroyView():

Cleans up resources when the fragment’s view is destroyed.

6. onDetach():
Invoked when the fragment is detached from the activity.

Fragment Communication
Fragments interact with their parent activity and other fragments via:

1. Interfaces:
Custom interfaces can be implemented for communication.

2. ViewModel:

A shared ViewModel enables sharing data between fragments.

3. FragmentManager:

getParentFragmentManager()is used for managing fragment transactions.

1.3 Overview of Tabbed Activities


Tabbed Navigation

Purpose:
Enhances user experience by organizing content into tabs.
 Tools:
1. ViewPager2:

Enables swipe-based navigation between fragments.

2. TabLayout:
Displays the tabs for easy access.
Real-World Examples
 Messaging Apps:

Chats, Contacts, and Settings in tabs.


 Settings Screens:
Organizing app preferences across different sections.

Android Fragments Overview


 A fragment represents multiple screens within a single activity.
 The FragmentManager class manages interactions and transactions involving
fragments.

Fragment Lifecycle
Fragment vs. Activity Lifecycle
Fragments depend on their parent activity for lifecycle management but have unique
events:

1. onAttach():

Fragment connects to the activity.


2. onCreateView():

Layout inflation for the fragment.


3. onActivityCreated():
Ensures the activity's onCreate() is complete.

4. onDestroyView():
Cleans up the fragment's view-related resources.

5. onDetach():
Disconnects the fragment from the activity.
Comparison Table

Stage Activity Fragment


Initialization onCreate() onAttach(), onCreate()
UI Creation setContentView() onCreateView()
Ready for Interaction onResume() onResume()
Termination onDestroy() onDestroyView(), onDetach()

Differences in Use Cases


 Activities:
Best for global UI or standalone screens.

 Fragments:
Ideal for reusable, modular UI (e.g., tabs, master-detail).

Key Recap Points


1. Static vs. Dynamic Fragments:
o Static fragments are fixed; dynamic fragments offer flexibility.
2. Fragment Lifecycle:
o Includes methods unique to fragments (onAttach(), onCreateView()).
3. Tabbed Activities:
o Use ViewPager2 and TabLayout for user-friendly navigation.

Android Tabbed layout


What is Android TabLayout?

TabLayout is a tool used in Android to create horizontal tabs, which allow users to
switch between different sections or views of your app.

 It replaced the old ActionBar. TabListener feature, which is no longer used in modern
Android development.
 TabLayout was introduced as part of the design support library, which
contains components to build apps with modern designs.

Key Methods of TabLayout


1. newTab():

This method is used to create new tabs in your app.

2. setText(int):

This is used to set the text or title of a tab.


3. setIcon(int):

This is used to set an icon for a tab. Icons help users understand what the tab
represents.

Tabs are displayed on the screen by attaching them to a TabLayout.

Two Types of TabLayouts


1. Sliding Tabs (TabLayout with ViewPager):

This type allows the user to swipe between tabs horizontally.

It is commonly used when there are multiple tabs, and you want to make navigation
smooth.

2. Non-Sliding Tabs (TabLayout with FrameLayout):


o In this setup, tabs do not allow swiping.
o Each tab directly opens its content when clicked.
o TabItem:
This is a component from the Android design support library.

It is used to define the items (tabs) within the TabLayout.


Summary

TabLayout is a flexible way to implement tabs in your Android app.

It provides features like:

 Customizing tabs
with text and icons.
 Switching between different content or views using tabs.
 Supporting both sliding
and non-sliding behavior depending on how you
implement it (with ViewPager for sliding and FrameLayout for static
tabs).

Accessing the Data using the Content Provider


Overview of Content Providers

 Purpose:

Content Providers in Android act as a structured way to access and manage data
stored in various apps.

They allow apps to share their data securely with other apps.
 Examples:

Common types of data managed include Contacts,

Media files (like photos and videos), and Call logs.

 Interaction:
The Content Resolver class is used by apps to communicate with Content
Providers.

Content Providers are similar to a central storage system.

They store
app data (like images, audio, and videos) in databases (like
SQLite), files, or over a network.
Other apps can access this data securely if the Content Provider grants the necessary
permissions.

CRUD Operations in Content Providers


CRUD stands for the four main operations possible with a Content Provider:

1. Create:
Add new data to the Content Provider.

2. Read:
Retrieve data from the Content Provider.

3. Update:

Modify existing data in the Content Provider.

4. Delete:

Remove data from the Content Provider.

How Content Providers Work


 Request Process:
o User interfaces (UI components) like Activities or Fragments use an object called
a Cursor Loader to send queries.
o These queries are sent through the Content Resolver, which acts as a
client.
o The Content Provider processes these requests (like creating, reading,
updating, or deleting data) and sends the results back to the app.

This setup ensures efficient communication between the UI and the data storage.

Steps to Create a Content Provider

1. Create a New Class:


o This class should extend the ContentProvider base class.
o It will handle all the data-related tasks for the app.
2. Define a URI:
o AURI (Uniform Resource Identifier) helps access the data in the
Content Provider.
3. Set Up a Database:
o Create a database
to store app data, like user information or files.
4. Override Abstract Methods:
o The ContentProvider class has six abstract methods.

You need to provide implementations for them.

5. Register the Content Provider:


o Add an entry in the AndroidManifest.xml file using the <provider> tag.
The Six Abstract Methods in ContentProvider
1. query():
o Used to fetch data. Returns the result as a cursor object (a structure to
iterate through database results).
2. insert():
o Adds a new record to the database and returns the URI of the inserted row.
3. update():
o Modifies data in the database and returns the number of rows
updated.
4. delete():
o Removes data from the database and returns the number of rows deleted.
5. onUpgrade():
o Called when the database version changes, used to handle schema
updates.
6. onCreate():
o Called when the database is created for the first time.
Defines the database structure (tables and their fields).

Practical Example:

Developing a "Contact Manager" App

Objective:

Create an app where users can manage contacts (add, view, update, and delete).
Steps:

1. Create a Database:
o Define a table with fields like:
 Name
 Phone Number
 Email
2. Design the Layout:
o Use EditText widgets for user input.
o Add Button widgets for actions like save, update, and delete.
o Use ListView or RecyclerView to display the contacts.
3. Implement CRUD Operations:
o Write code to perform the four main operations (Create, Read, Update, Delete) using
SQLite.
4. Test the App:
o Ensure each function (add, view, update, delete) works as expected.
o Verify the data is displayed correctly in the app’s UI.

Week 13 and the 14 Firebase

Lecture Title: Firebase in Mobile Application Development

1.1 What is Firebase?

Firebase is a service provided by Google that acts as a "Backend-as-a-Service"


(BaaS).

It provides tools that allow you to build apps quickly without worrying about
setting up servers.

 Examples of where Firebase is used:


o Food Delivery Apps:
Handles user logins,

Real-time order updates,

and data synchronization.

o Social Media Apps:

Keeps posts and comments synchronized in real-time.

1.2 Key Firebase Services


Firebase provides various tools:

 Authentication:
For managing user login and registration.

 Realtime Database:
Stores and syncs data in real time across users.

 Cloud Firestore:

A more advanced database for large-scale apps.

 Cloud Messaging:

Sends push notifications to users.

 Storage:

For saving user-uploaded files like images and videos.

1.3 Benefits of Firebase


 Real-Time Updates:
Data changes reflect instantly on all devices.

 Easy to Use:

Reduces complex coding for server setups.

 Free Tier:
Suitable for small projects or learning.

Part 2: Setting Up Firebase in Android Studio

2.1 Prerequisites
Before starting, ensure:

 You have Android Studio installed.


 You have a Google account.

2.2 Step-by-Step Firebase Setup

1. Go to the Firebase Console online.


2. Create a new project and name it “MyApp.”
3. Register your Android app with:
o Package Name: com.example.myapp
o App Nickname: MyApp
4. Download the google-services.json file and place it in the app/ folder of
your project.
5. Add these lines to your build.gradle file to include Firebase dependencies:
6. implementation 'com.google.firebase:firebase-auth:21.3.0'
7. implementation 'com.google.firebase:firebase-database:20.2.3'
8. Sync your project.

2.3 Verifying Setup:

Test Firebase by adding this code:

FirebaseDatabase.getInstance().getReference("test").setValue("Hello
Firebase!");

Part 3: Firebase Authentication


Firebase Authentication helps you manage user sign-ups and logins using:

 Email/Password.
 Social logins (e.g., Google, Facebook).
 Example in Real Life:
o E-Commerce Apps:
New users register, and existing users log in to view orders.

Implementing Email/Password Authentication

Registering a User:

 FirebaseAuth auth = FirebaseAuth.getInstance();


 auth.createUserWithEmailAndPassword("[email protected]", "password123")
 .addOnCompleteListener(task -> {
 if (task.isSuccessful()) {
 Log.d("Auth", "Registration successful!");
 } else {
 Log.e("Auth", "Failed: " + task.getException().getMessage());
 }
 });

Logging In a User:

auth.signInWithEmailAndPassword("[email protected]", "password123")
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d("Auth", "Login successful!");
} else {
Log.e("Auth", "Login failed: " + task.getException().getMessage());
}
});
 Live Demo Tasks:
o Build simple login and registration screens.
o Test user login functionality.

3.3 Real-World Challenges:


 Security Issues:
Always use strong passwords and set Firebase security rules.

 Scalability:

Prepare for large numbers of users.

Part 4: Firebase Realtime Database


The Realtime Database allows apps to synchronize data instantly between users and
devices.

 Examples of Real-Life Usage:


o Chat Applications:

Messages appear instantly for everyone.

o Ride-Hailing Apps:
Real-time updates of driver and rider locations.

4.2 Implementing Basic CRUD Operations


Write Data to the Database:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
 Map<String, Object> user = new HashMap<>();
 user.put("name", "John Doe");
 user.put("email", "[email protected]");

 database.child("users").child("user1").setValue(user)
 .addOnCompleteListener(task -> {
 if (task.isSuccessful()) {
 Log.d("Database", "Data written successfully!");
 } else {
 Log.e("Database", "Failed: " + task.getException().getMessage());
 }
 });
 Read Data from the Database:
database.child("users").child("user1").get()
.addOnCompleteListener(task -> {
 if (task.isSuccessful()) {
 Log.d("Database", "Data: " + task.getResult().getValue());
 } else {
 Log.e("Database", "Failed: " + task.getException().getMessage());
 }
 });

4.3 Challenges in Real-Time Apps

 Efficiently handling large amounts of data.


 Structuring NoSQL databases to scale effectively.

Homework Assignment

1. Create an Android app with:


o Firebase Authentication for login and registration.
o Firebase Realtime Database to save and retrieve user data.
2. Build a chat feature using the Realtime Database.

MDAFIRBASE
The content of the document explains how to integrate Firebase Realtime Database into an Android
application, step by step, along with creating a to-do list app that uses Firebase
as its backend.
Here's a simplified and beginner-friendly explanation of each topic:

What is Firebase?
Firebase is a service that provides tools to help developers build high-quality apps.

One of its main features is the Realtime Database, which:

 Stores data in the cloud as JSON.


 Syncs data across all users in real time.
 Works even when the app is offline.
Other Firebase features include:
 Authentication:
User login.
 Storage: Saving files.

Setting Up Firebase in Android Studio


To use Firebase:

1. Enable Google Repository in Android Studio:


o Go to Tools > SDK Manager > SDK Tools tab.
o Check Google Repository and click OK.
2. Use Firebase Assistant in Android Studio:
o Go to Tools > Firebase.
o Select a feature like "Realtime Database."
o Follow the steps to connect your project to Firebase and add its code.
Adding Firebase to Your App
Steps to integrate Firebase:
1. Open Android Studio and go to Tools > Firebase.
2. From the menu on the right, pick a Firebase service (like "Realtime Database").
3. Click Connect to Firebase.
4. Add required dependencies by selecting "Add [SERVICE NAME] to app."

Example of dependencies for Firebase Realtime Database:


implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-core:16.0.3'

Setting Up a Firebase Project


1. Go to Firebase Console:
o Open Firebase Console.
o Click "Create New Project."
2. Steps to Create a Project:
o Step 1: Name your project and accept terms.
o Step 2: Enable or disable Google Analytics.
o Step 3 (if Analytics is enabled): Choose your country and agree to terms.
Linking Your App to Firebase
1. Add an App to Firebase:
o In the Firebase Console, click the Android icon.
o Enter your app’s package name and click "Register App."
2. Download Configuration File:
o Download the google-services.json file and add it to your project.
3. Add Firebase SDK:
o Add Firebase dependencies to your build.gradle file.
o Sync the project.

Building a To-Do List App


The app will:
 Use RecyclerView to display tasks.
 Store tasks in Firebase Realtime Database.
 Allow adding and deleting tasks.
Firebase Database Setup
1. Go to Firebase Console > Realtime Database > Rules.
2. Set rules for testing:
{
"rules": {
".read": true,
".write": true
}
}

App Design and Code


1. UI Design:
o activity_main.xml:
 RecyclerView to list tasks.
 EditText for entering a new task.
 Button to add a task.
o to_do_list.xml:
 TextView for task title.
 ImageView for a delete button.
2. Code Overview:
o Task.java: A class to represent a task.
o RecyclerViewAdapter: Manages how tasks are displayed.
o MainActivity.java:
 Handles Firebase connections.
 Adds tasks to Firebase using push() and setValue().
 Deletes tasks by removing them from Firebase.

Running the App


1. Use Android Studio to build and run the app.
2. The app will:
o Display tasks from Firebase.
o Add new tasks to Firebase when the "Add Task" button is clicked.
o Delete tasks when the delete icon is tapped.

LAB 4 Code
package com.example.lab_manuals;

 What it does: This defines the package name for your app. A package is like a folder where your app's
code files are organized. com.example.lab_manuals is the name of this app's package.

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

 What it does: These are the tools or libraries your code needs to work.
o Bitmap: For creating a blank image to draw on.
o Canvas: A surface (like a sheet of paper) for drawing shapes and text.
o Color: To set colors for drawing.
o Paint: The "brush" to draw shapes and text.
o BitmapDrawable: Turns a Bitmap into something the app can display.
o Bundle: Holds data when the app starts.
o ImageView: A UI element to show the image.
o AppCompatActivity: A base class (template) for activities using AndroidX (modern Android
libraries).

public class MainActivity extends AppCompatActivity {

 What it does: This defines the MainActivity class, which is the main screen of your app. It extends
AppCompatActivity, meaning it uses all the features of an Android activity.

@Override
protected void onCreate(Bundle savedInstanceState) {

 What it does: This is the onCreate method, which is called when the app starts. It sets up the activity
(screen) when you open the app.

super.onCreate(savedInstanceState);

 What it does: This calls the onCreate method of the parent class (AppCompatActivity) to make sure
everything is set up correctly for the activity.

setContentView(R.layout.activity_main);

 What it does: This connects the Java code to the XML layout file (activity_main.xml), which defines
what the screen looks like (e.g., buttons, images, etc.).

Bitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

 What it does: Creates a blank image (Bitmap) with a width of 720 pixels and a height of 1280 pixels.
The ARGB_8888 setting means the image supports transparency and high-quality colors.

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

 What it does: Finds the ImageView with the ID imageView from the XML layout file. This is where the
blank bitmap will be displayed.

i.setImageDrawable(new BitmapDrawable(getResources(), bg));

 What it does: Converts the blank Bitmap into a drawable (something that can be displayed) and sets it
as the background for the ImageView.
Canvas canvas = new Canvas(bg);

 What it does: Creates a Canvas object to draw on the blank Bitmap. The canvas is like a drawing
surface attached to the bitmap.

Paint paint = new Paint();

 What it does: Creates a Paint object, which is like a brush used for drawing on the canvas.

paint.setColor(Color.BLUE);

 What it does: Sets the brush color to blue.

paint.setTextSize(50);

 What it does: Sets the size of the text that will be drawn using the brush.

Drawing Shapes and Text:


canvas.drawText("Rectangle", 420, 150, paint);

 What it does: Draws the word "Rectangle" on the canvas at the position (420, 150).

canvas.drawRect(400, 200, 650, 700, paint);

 What it does: Draws a rectangle on the canvas. The rectangle's top-left corner is at (400, 200), and the
bottom-right corner is at (650, 700).

canvas.drawText("Circle", 120, 150, paint);

 What it does: Draws the word "Circle" at the position (120, 150).

canvas.drawCircle(200, 350, 150, paint);

 What it does: Draws a circle with a center at (200, 350) and a radius of 150.

canvas.drawText("Square", 120, 800, paint);

 What it does: Draws the word "Square" at the position (120, 800).

canvas.drawRect(50, 850, 350, 1150, paint);

 What it does: Draws a square. The top-left corner is (50, 850), and the bottom-right corner is (350,
1150).

canvas.drawText("Line", 480, 800, paint);


 What it does: Draws the word "Line" at the position (480, 800).

canvas.drawLine(520, 850, 520, 1150, paint);

 What it does: Draws a vertical line from the point (520, 850) to (520, 1150).

Closing Braces:
}

 These close the onCreate method and the MainActivity class.

Summary:

 You created a blank image, drew shapes and text on it using a canvas, and displayed it in an ImageView.
Each line sets up or customizes how the drawing looks on the screen.

Code
com.example.lab_manuals;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle; import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity; // Use AndroidX

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating a Bitmap

Bitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

// Setting the Bitmap as background for the ImageView

ImageView i = findViewById(R.id.imageView);
i.setImageDrawable(new BitmapDrawable(getResources(), bg));

// Creating the Canvas Object

Canvas canvas = new Canvas(bg);

// Creating the Paint Object and set its color & TextSize
Paint paint = new Paint(); paint.setColor(Color.BLUE);
paint.setTextSize(50);
// To draw a Rectangle

canvas.drawText("Rectangle", 420, 150, paint);

canvas.drawRect(400, 200, 650, 700, paint);

// To draw a Circle

canvas.drawText("Circle", 120, 150, paint);


canvas.drawCircle(200, 350, 150, paint);
// To draw a Square

canvas.drawText("Square", 120, 800, paint);


canvas.drawRect(50, 850, 350, 1150, paint);

// To draw a Line

canvas.drawText("Line", 480, 800, paint);


canvas.drawLine(520, 850, 520, 1150, paint);
}

• So now the Coding part is also completed.

• Now run the application to see the output.

OutPut:
LAB 5
Code for MainActivity.java:

package com.example.lab_manuals;

import android.app.Activity;

import android.app.AlertDialog.Builder; import

android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDataase;

import android.os.Bundle;

import android.view.View;
import android.view.View.OnClickListener; import

android.widget.Button;

import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener

EditText Rollno,Name,Marks;
Button Insert,Delete,Update,View,ViewAll;

SQLiteDatabase db;

/** Called when the activity is first created.


*/

@Override

savedInstanceState)

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

Rollno=(EditText)findViewById(R.id.Rollno);

Name=(EditText)findViewById(R.id.Name);

Marks=(EditText)findViewById(R.id.Marks);

Insert=(Button)findViewById(R.id.Insert);

Delete=(Button)findViewById(R.id.Delete);

Update=(Button)findViewById(R.id.Update);

View=(Button)findViewById(R.id.View);

ViewAll=(Button)findViewById(R.id.ViewAll);
Insert.setOnClickListener(this);

Delete.setOnClickListener(this);

Update.setOnClickListener(this);

View.setOnClickListener(this);

ViewAll.setOnClickListener(this);

// Creating database and table db=openOrCreateDatabase("StudentDB",


Context.MODE_PRIVATE, null);

db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);");

public void onClick(View view)

// Inserting a record to the Student table

if(view==Insert)

// Checking for empty fields

if(Rollno.getText().toString().trim().length()==0

|| Name.getText().toString().trim().length()==0

||

Marks.getText().toString().trim().length()==0)

showMessage("Error", "Please enter all values");

return;

db.execSQL("INSERT INTO student


VALUES('"+Rollno.getText()+"','"+Name.getText()+
"','"+Marks.getText()+"');"); showMessage("Success", "Record
added");

clearText();
}

// Deleting a record from the Student table

if(view==Delete)

// Checking for empty roll number

if(Rollno.getText().toString().trim().length()==0)

showMessage("Error", "Please enter Rollno"); return;

Cursor c=db.rawQuery("SELECT * FROM student WHERE


rollno='"+Rollno.getText()+"'", null); if(c.moveToFirst())

db.execSQL("DELETE FROM student WHERE rollno='"+Rollno.getText()+"'");

showMessage("Success", "Record Deleted");

else

showMessage("Error", "Invalid Rollno");

clearText();

// Updating a record in the Student table if(view==Update)

// Checking for empty roll number

if(Rollno.getText().toString().trim().length()==0)

{
showMessage("Error", "Please enter Rollno"); return;

Cursor c=db.rawQuery("SELECT * FROM student WHERE


rollno='"+Rollno.getText()+"'", null); if(c.moveToFirst()) {

db.execSQL("UPDATE student SET name='" + Name.getText() + "',marks='" + Marks.getText() +

"' WHERE rollno='"+Rollno.getText()+"'");

showMessage("Success", "Record Modified");

else { showMessage("Error", "Invalid

Rollno");

clearText();

// Display a record from the Student table if(view==View)

// Checking for empty roll number

if(Rollno.getText().toString().trim().length()==0)

showMessage("Error", "Please enter Rollno"); return;

Cursor c=db.rawQuery("SELECT * FROM student WHERE


rollno='"+Rollno.getText()+"'", null); if(c.moveToFirst())

Name.setText(c.getString(1));

Marks.setText(c.getString(2));

}
else

showMessage("Error", "Invalid Rollno"); clearText();

// Displaying all the records if(view==ViewAll)

Cursor c=db.rawQuery("SELECT * FROM student", null);

if(c.getCount()==0)

showMessage("Error", "No records found"); return;

StringBuffer buffer=new StringBuffer();


while(c.moveToNext())

buffer.append("Rollno: "+c.getString(0)+"\n");

buffer.append("Name: "+c.getString(1)+"\n");

buffer.append("Marks: "+c.getString(2)+"\n\n");

showMessage("Student Details", buffer.toString());

public void showMessage(String title,String message)

Builder builder=new Builder(this);

builder.setCancelable(true);
builder.setTitle(title);

builder.setMessage(message); builder.show();

public void clearText()

Rollno.setText("");

Name.setText("");

Marks.setText("");

Rollno.requestFocus();

Expanation
Sure! Let me break down the code for you and explain every single line as simply as possible. Here's the
explanation:

Code Breakdown
package com.example.lab_manuals;

 This declares the package of the app. A package is like a folder that organizes your code files.

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 These are import statements that include required classes for the app to work:
o Activity: Represents a screen in the app.
o Builder: Used to create and display alert messages.
o Context: Provides access to application resources.
o Cursor: Helps in reading data from the database.
o SQLiteDatabase: Manages the database operations.
o Bundle, View, and OnClickListener: Handle UI and user interactions.
o Button and EditText: UI elements for user input and actions.

public class MainActivity extends Activity implements OnClickListener

 Defines the MainActivity class, which represents the main screen of the app.
 extends Activity: This class is a type of Activity.
 implements OnClickListener: This means the class will handle button clicks.

Variable Declarations

EditText Rollno, Name, Marks;


Button Insert, Delete, Update, View, ViewAll;
SQLiteDatabase db;

 Declares variables for:


o Rollno, Name, Marks: Text input fields for entering roll number, name, and marks.
o Insert, Delete, Update, View, ViewAll: Buttons for different actions.
o db: A variable to interact with the SQLite database.

@Override
protected void onCreate(Bundle savedInstanceState)

 This is the method that runs when the screen is first created.
 onCreate: Sets up the activity (screen).
 Bundle savedInstanceState: Used to restore saved data when the app is reopened.

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

 super.onCreate(savedInstanceState): Calls the parent class method to initialize the activity.


 setContentView(R.layout.activit_main): Sets the layout of the screen. It connects this class to the
activit_main.xml file (though there seems to be a typo—it should be activity_main).

Linking UI Elements

Rollno = (EditText)findViewById(R.id.Rollno);
Name = (EditText)findViewById(R.id.Name);
Marks = (EditText)findViewById(R.id.Marks);
Insert = (Button)findViewById(R.id.Insert);
Delete = (Button)findViewById(R.id.Delete);
Update = (Button)findViewById(R.id.Update);
View = (Button)findViewById(R.id.View);
ViewAll = (Button)findViewById(R.id.ViewAll);

 Finds each UI element in the layout using its id and links it to the variable.

Setting Button Click Listeners

Insert.setOnClickListener(this);
Delete.setOnClickListener(this);
Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);
 Attaches click listeners to each button. When clicked, the onClick method will handle the action.

Database Initialization
db = openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR, name VARCHAR,
marks VARCHAR);");

 openOrCreateDatabase: Opens an existing database or creates a new one named StudentDB.


 execSQL: Executes an SQL command to create a table named student with three columns: rollno,
name, and marks.

Handling Button Clicks

public void onClick(View view)

 This method is called whenever a button is clicked.


 View view: Identifies which button was clicked.

Insert Button

if(view == Insert) {
if(Rollno.getText().toString().trim().length() == 0 ||
Name.getText().toString().trim().length() == 0 ||
Marks.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student VALUES('" + Rollno.getText() + "','" +
Name.getText() + "','" + Marks.getText() + "');");
showMessage("Success", "Record added");
clearText();
}

 Checks if all fields (Rollno, Name, Marks) are filled.


 If not, displays an error message using showMessage.
 Otherwise, inserts the values into the student table and shows a success message.
 Clears the input fields using clearText.

Delete Button

if(view == Delete) {
if(Rollno.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c = db.rawQuery("SELECT * FROM student WHERE rollno='" +
Rollno.getText() + "'", null);
if(c.moveToFirst()) {
db.execSQL("DELETE FROM student WHERE rollno='" + Rollno.getText() +
"'");
showMessage("Success", "Record Deleted");
} else {
showMessage("Error", "Invalid Rollno");
}
clearText();
}

 Checks if Rollno is entered. If not, shows an error.


 Searches for the record by roll number.
 Deletes the record if found, or shows an error if not.

Update Button

if(view == Update) {
if(Rollno.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c = db.rawQuery("SELECT * FROM student WHERE rollno='" +
Rollno.getText() + "'", null);
if(c.moveToFirst()) {
db.execSQL("UPDATE student SET name='" + Name.getText() + "',
marks='" + Marks.getText() + "' WHERE rollno='" + Rollno.getText() + "'");
showMessage("Success", "Record Modified");
} else {
showMessage("Error", "Invalid Rollno");
}
clearText();
}

 Checks if Rollno is entered.


 Searches for the record by roll number.
 Updates the record's name and marks if found.

View Button

if(view == View) {
if(Rollno.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c = db.rawQuery("SELECT * FROM student WHERE
rollno='" + Rollno.getText() + "'", null);
if(c.moveToFirst()) {
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
} else {
showMessage("Error", "Invalid Rollno");
clearText();
}
}

 Searches for a record by roll number.


 Displays the name and marks in the respective fields if found.

View All Button

if(view == ViewAll) {
Cursor c = db.rawQuery("SELECT * FROM student", null);
if(c.getCount() == 0) {
showMessage("Error", "No records found");
return;
}
StringBuffer buffer = new StringBuffer();
while(c.moveToNext()) {
buffer.append("Rollno: " + c.getString(0) + "\n");
buffer.append("Name: " + c.getString(1) + "\n");
buffer.append("Marks: " + c.getString(2) + "\n\n");
}
showMessage("Student Details", buffer.toString());
}

 Retrieves all records from the student table.


 Displays the details in a dialog box if records exist.

Helper Methods
showMessage

public void showMessage(String title, String message) {


Builder builder = new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
 Displays an alert dialog with a title and message.

clearText

public void clearText() {


Rollno.setText("");
Name.setText("");
Marks.setText("");
Rollno.requestFocus();
}

 Clears all input fields and sets focus back to the Rollno field.

LAB 6
Sure! I’ll break down every single line of your code and explain it in the simplest way possible. Let’s go step by
step.

Package Declaration
package com.example.lab_manuals;
 This line defines the package where this file (MainActivity.java) belongs. Think of it like a folder for
organizing your code. Your app is organized into the com.example.lab_manuals package.

Imports

These lines import necessary tools and libraries that your app uses.

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

 ListActivity: A special type of activity in Android that displays a list of items.


 Intent: Used to start other activities or perform actions, like opening a webpage.
 Uri: Represents a URL or a file path.
 AsyncTask: Helps run long-running tasks (like downloading data) in the background so the app doesn’t
freeze.
 Bundle: Used to pass data when creating or restoring an activity.
 View: Represents a part of the screen.
 ArrayAdapter: A simple adapter used to bind data to a list.
 ListView: A UI element that displays a scrollable list of items.
 XmlPullParser and related classes: These are used to read (parse) XML data from the internet.
 Other imports: Handle URLs, input streams, and exceptions for internet connections.

Class Declaration

public class MainActivity extends ListActivity

 MainActivity: The main class where your app’s logic is defined.


 extends ListActivity: Means this class inherits from ListActivity to show a list on the screen.
Global Variables

List headlines;
List links;

 headlines: A list to store the titles of articles from the RSS feed.
 links: A list to store the links (URLs) for the articles.

onCreate Method
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new MyAsyncTask().execute();
}
 onCreate: This method is called when the app starts.
 super.onCreate(savedInstanceState): Initializes the activity using the parent class.
 new MyAsyncTask().execute(): Starts a background task (using MyAsyncTask) to download and
process the RSS feed.

MyAsyncTask Class
class MyAsyncTask extends AsyncTask<Object, Void, ArrayAdapter>

 This is a custom class that extends AsyncTask. It allows you to perform work in the background without
freezing the app.

doInBackground Method

@Override
protected ArrayAdapter doInBackground(Object[] params)
{
headlines = new ArrayList();
links = new ArrayList();
 doInBackground: Runs in the background to avoid slowing down the app.
 headlines = new ArrayList();: Creates an empty list to store the article titles.
 links = new ArrayList();: Creates an empty list to store the article URLs.

Downloading and Parsing the RSS Feed

try
{
URL url = new URL("https://codingconnect.net/feed");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");

 URL url: Defines the URL of the RSS feed to fetch data from.
 XmlPullParserFactory: Creates a parser to process the XML data.
 factory.setNamespaceAware(false): No need to handle XML namespaces.
 xpp.setInput(...): Provides the RSS feed data to the parser.

Parsing the XML

boolean insideItem = false;


int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
if (xpp.getName().equalsIgnoreCase("item"))
{
insideItem = true;
}
else if (xpp.getName().equalsIgnoreCase("title"))
{
if (insideItem) headlines.add(xpp.nextText());
}
else if (xpp.getName().equalsIgnoreCase("link"))
{
if (insideItem) links.add(xpp.nextText());
}
}
else if (eventType == XmlPullParser.END_TAG &&
xpp.getName().equalsIgnoreCase("item"))
{
insideItem = false;
}
eventType = xpp.next();
}

 insideItem: Tracks whether the parser is inside an <item> tag.


 eventType: Checks what type of tag is currently being read (e.g., start tag, end tag, text).
 while: Loops through the XML until the end of the document.
 if (xpp.getName().equalsIgnoreCase("item")): Checks for <item> tags, which contain individual
articles.
 headlines.add(...): Adds the title of the article to the headlines list.
 links.add(...): Adds the link (URL) of the article to the links list.

Exception Handling

catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (XmlPullParserException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

 Handles errors like:


o MalformedURLException: If the URL is incorrect.
o XmlPullParserException: If there’s an issue with parsing the XML.
o IOException: If there’s a problem with the internet connection.

onPostExecute Method
protected void onPostExecute(ArrayAdapter adapter)
{
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1,
headlines);
setListAdapter(adapter);
}

 onPostExecute: Runs after the background task finishes.


 new ArrayAdapter(...): Creates an adapter to display the article titles (headlines) in the list.
 setListAdapter(adapter): Binds the adapter to the list so the titles show up on the screen.

onListItemClick Method
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
Uri uri = Uri.parse((links.get(position)).toString());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}

 This method is called when the user clicks on an item in the list.
 Uri.parse(links.get(position)): Gets the link (URL) of the clicked article.
 new Intent(...): Creates an intent to open the link in a web browser.
 startActivity(intent): Opens the web browser to show the article.

getInputStream Method
public InputStream getInputStream(URL url)
{
try
{
return url.openConnection().getInputStream();
}
catch (IOException e)
{
return null;
}
}

 getInputStream: Opens a connection to the given URL and gets the data as a stream.
 return null: If there’s an error, it returns null instead of crashing.

Lab 7
package com.example.lab_manuals;

import android.os.Bundle; import


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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


ImageView img;
Button bt1, bt2;

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

bt1 = findViewById(R.id.button); bt2 =


findViewById(R.id.button2); img =
findViewById(R.id.imageView);

bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { new
Thread(new Runnable() {
@Override public void run() {
img.post(new Runnable() {
@Override
public void run() {
img.setImageResource(R.drawable.india1);
}
});
}
}).start();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { new
Thread(new Runnable() {
@Override public void run() {
img.post(new Runnable() {
@Override
public void run() {
img.setImageResource(R.drawable.india2);
}
});
}
}).start();
}
});
}
}

Explaination
Let's go through your Java code step by step in simple terms:

1. Package Declaration:
package com.example.lab_manuals;

 This line specifies the package where your code belongs. It’s like putting your file in a folder, so the
system knows where to find it.

2. Import Statements:
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 These lines import necessary classes for the application to work:
o Bundle: Allows you to pass data between activities.
o View: The base class for all UI elements (like buttons or images).
o Button: Class to use buttons in the UI.
o ImageView: Class to display images in the UI.

3. MainActivity Class:
public class MainActivity extends AppCompatActivity {

 This defines the main class of your app (where the logic happens). MainActivity is the first screen the
user sees when the app is opened. It extends AppCompatActivity, which means it is a type of Android
activity (screen).

4. Declaring Variables:

ImageView img;
Button bt1, bt2;

 Here, you declare two buttons (bt1 and bt2) and one image view (img). These are the elements that will
be used in your UI.

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

 onCreate is a lifecycle method that gets called when the activity (screen) is first created. It sets up the
UI using the layout defined in activity_main.xml. super.onCreate(savedInstanceState) calls the
parent class method to ensure the activity is set up properly.

6. Initializing UI Elements:

bt1 = findViewById(R.id.button);
bt2 = findViewById(R.id.button2);
img = findViewById(R.id.imageView);

 These lines connect the buttons (bt1, bt2) and the image view (img) in the Java code to the ones defined
in the XML layout file (activity_main.xml). findViewById is used to locate the elements by their
unique ID.

7. Button 1 Click Listener:


bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
img.post(new Runnable() {
@Override
public void run() {
img.setImageResource(R.drawable.india1);
}
});
}
}).start();
}
});

 Setting an OnClickListener: When bt1 is clicked, the setOnClickListener method triggers an


action.
 Inside the onClick method, a new thread is created using new Thread(new Runnable() {...}). A
thread is like a mini task that runs in the background, so the main UI remains responsive.
 img.post(new Runnable() {...}): This makes sure that the image update happens on the main UI
thread (because UI updates can't happen directly in a background thread).
 img.setImageResource(R.drawable.india1): This changes the image displayed in the ImageView to
the image resource india1.

8. Button 2 Click Listener:

bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
img.post(new Runnable() {
@Override
public void run() {
img.setImageResource(R.drawable.india2);
}
});
}
}).start();
}
});

 This is very similar to the code for bt1, but for bt2.
 When bt2 is clicked, a new thread is started, and the ImageView (img) is updated to display the image
india2.

9. Closing the Class and Method:


}

 This closes the onCreate method and the MainActivity class.


Summary of the Program Flow:

1. When the app starts, the MainActivity is created, and the layout is displayed.
2. The user can click either bt1 or bt2.
3. If bt1 is clicked, the image changes to india1.
4. If bt2 is clicked, the image changes to india2.
5. Both buttons use background threads to change the image without affecting the UI performance.

Let me know if you need more details!

3. Organize Your Project Files


Ensure your files are placed in the correct locations:
 XML Layout Files:
o activity_main.xml → res/layout/

o fragment_upper.xml → res/layout/

o fragment_lower.xml → res/layout/

 Java Files:
o UpperFragment.java → java/com/anas/staticfragment/

o LowerFragment.java → java/com/anas/staticfragment/

4. Update the AndroidManifest.xml File


Make sure your app’s AndroidManifest.xml file is updated with the main activity. Example:
<application>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

5. Build the App


 Click on "Build" > "Make Project" or press Ctrl+F9.
 Fix any errors if they appear (you can share details with me if you face issues).

6. Run the App


 Connect your Android phone or start an Android Emulator.
 Click Run > Run 'app' or press Shift+F10.
 Choose your device (physical or emulator) to see the app running.

What to Expect:
 Your app will display a screen with two fragments:
o An Upper Fragment (pink background with "Upper Fragment" text).

o A Lower Fragment (blue background with "Lower Fragment" text).

Let me know if you face any specific problems during these steps!

Explanation of the Fragmentation practical


Let’s go through each file step-by-step, line-by-line, in the simplest and easiest way.

1. MainActivity.java

This is the main entry point of your app where everything starts. It connects your activity_main.xml file with
the app.

package com.example.staticfregmentation;

 This defines the package where this file is located. Think of it as a folder to organize your files.

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

 These are instructions for your app to use specific tools. AppCompatActivity is like a blueprint that
provides features for your app's main screen.

public class MainActivity extends AppCompatActivity {


 This creates the main activity (screen). It's a container for your app's UI.

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

 This method runs when your app starts. super.onCreate() ensures the app's startup logic runs
correctly.

setContentView(R.layout.activity_main);
 This connects the screen (activity_main.xml) to this Java file. It tells the app what the main
screen looks like.

}
}

 These curly braces { } mark the start and end of the activity.

2. activity_main.xml
This file defines the design of your main screen. It includes the fragments (parts of the screen) and their layout.

<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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="2"
android:padding="15dp"
tools:context=".MainActivity">

 LinearLayout:

This organizes items in a vertical stack, one below the other.

 xmlns::

These are special settings to make Android layouts work.

 layout_width and layout_height:


Set the size of the layout to match the screen.
 orientation="vertical":

Arranges items vertically.

 weightSum="2":

Divides space between two fragments equally.

 padding="15dp":

Adds space around the content.

 tools:context=".MainActivity":

Links this layout to the MainActivity.java file.

<fragment
android:id="@+id/fragUpper"

android:name="com.example.staticfregmentation.UpperFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />

 This adds the UpperFragment (the top part of the screen).


o id: Unique name for this fragment.
o name: Links to the UpperFragment class.
o layout_weight: Makes this take half the screen.

<fragment
android:id="@+id/fragLower"
android:name="com.example.staticfregmentation.LowerFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />

 This adds the LowerFragment (the bottom part of the screen). It's similar to the UpperFragment.

</LinearLayout>

 This ends the layout.

3. UpperFragment.java
This file defines what the UpperFragment looks like and how it behaves.
package com.example.staticfregmentation;
 The package name organizes this file.

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

 These provide tools to create and control fragments.

public class UpperFragment extends Fragment {

 This creates the UpperFragment class.

public UpperFragment() {
// Required empty public constructor
}
 This is a basic setup for fragments.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_upper,
container, false);
}
}

 This connects fragment_upper.xml to the UpperFragment class. The inflater loads the XML file
and displays it.

4. fragment_upper.xml

This file defines the design of the UpperFragment.

<LinearLayout
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="#f8bbd0"
android:gravity="center"
tools:context=".UpperFragment">
 Creates a layout for the UpperFragment.
o background="#f8bbd0": Sets a pink background.
o gravity="center": Centers items.

<TextView
android:id="@+id/txtUpperFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upper Fragment"
android:textSize="22sp"
android:textColor="#e91e63"
android:textStyle="italic|bold" />
</LinearLayout>

 TextView: Adds text to the fragment.


o text: The words displayed ("Upper Fragment").
o textColor: Text color is pink.
o textStyle: Makes the text italic and bold.

5. LowerFragment.java

This file defines what the LowerFragment looks like and how it behaves.

package com.example.staticfregmentation;

 Organizes the file.

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

 Provides tools to create and control fragments.

public class LowerFragment extends Fragment {

 This creates the LowerFragment class.

public LowerFragment() {
// Required empty public constructor
}

 This is basic setup for fragments.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment_lower, container, false);
}
}

 This connects fragment_lower.xml to the LowerFragment class.

6. fragment_lower.xml

This file defines the design of the LowerFragment.

<LinearLayout
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="#b2ebf2"
android:gravity="center"
tools:context=".LowerFragment">

 Creates a layout for the LowerFragment.


o background="#b2ebf2": Sets a blue background.
o gravity="center": Centers items.

<TextView
android:id="@+id/txtLowerFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lower Fragment"
android:textSize="22sp"
android:textColor="#00bcd4"
android:textStyle="italic|bold" />
</LinearLayout>

 TextView: Adds text to the fragment.


o text: The words displayed ("Lower Fragment").
o textColor: Text color is blue.
o textStyle: Makes the text italic and bold.

7. AndroidManifest.xml

This file provides information about your app to the Android system.

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

 Declares your app and sets its package name.


<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.StaticFregmentation">

 Sets app-level details:


o icon: App icon.
o label: App name.
o theme: Style for the app.

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

 Declares MainActivity as the main screen:


o action.MAIN: Marks it as the entry point.
o category.LAUNCHER: Makes it appear

Mobile Application Quiz


1. Introduction to Fragments (Static, Dynamic)

Fragments are like smaller parts of an app's screen that can work independently or together.
Think of them as reusable pieces of your app's UI (User Interface).

 Static Fragments:
These are fixed parts of the screen, defined directly in the XML layout file.

They don’t change while the app is running.

 Dynamic Fragments:
These are added, removed, or replaced during runtime, using code.

This allows more flexibility to create dynamic interfaces.


Example:
A weather app might use
one fragment to show today's weather and
another to show the weekly forecast.

2. Lifecycle of Fragments and Communication

Fragments have a lifecycle similar to an Activity (the screen in an app).


Here’s a simplified version:

1. onAttach:
Fragment is attached to the Activity.

2. onCreate: Fragment is being created.


3. onCreateView: Fragment creates its UI (layout).
4. onActivityCreated: Activity and Fragment are ready to work together.
5. onStart: Fragment becomes visible.
6. onResume: Fragment is now fully interactive.
7. onPause: Fragment is not interactive but still visible.
8. onStop: Fragment is not visible anymore.
9. onDestroyView: UI is destroyed.
10. onDestroy: Fragment is removed.
11. onDetach: Fragment is detached from the Activity.

Communication: Fragments talk to the Activity or other fragments using interfaces or ViewModel. For
example, pressing a button in one fragment can send data to another fragment.

3. Tabbed Activity

A Tabbed Activity is an Activity with tabs (like the ones you see in a browser). Each tab can display a different
Fragment.

 Example: A music app might have tabs for "Songs," "Albums," and "Artists."
 Tabs make it easier for users to switch between different sections of the app quickly.

4. Introduction to Content Providers

Content Providers are a way to share data between apps or within the same app. They act as a middleman that
lets you access and manage data.

 Example: A messaging app uses a Content Provider to access your contacts.


 They handle data from sources like databases, files, or the internet.

5. Accessing Data Using Content Providers

To get data from a Content Provider, apps use a special method called ContentResolver.
Steps:

1. Request data using a URI (Uniform Resource Identifier) like content://contacts.


2. Use queries to fetch the specific data you need.
3. The provider gives back the data, usually in a table-like format.

Example:
If you want to show a list of contacts in your app, you query the Contacts Content Provider, and it sends back
names and numbers to display.

Simple Version
Detailed Explanation of Mobile Application Development Topics

Introduction to Fragments (Static, Dynamic)

 Fragments are small, reusable pieces of an app's user interface. They are like mini-activities that can be
used in different combinations.
 Static Fragments: These are added to an activity layout at design time (using XML).
 Dynamic Fragments: These are added or replaced in an activity programmatically during runtime using
FragmentManager.
 Benefits: Fragments improve modularity, reusability, and adaptability for different screen sizes.

Lifecycle of Fragments and Communication

 The Fragment Lifecycle is similar to an Activity lifecycle:


1. onAttach: Fragment is attached to the activity.
2. onCreate: Initialize components.
3. onCreateView: Inflate the fragment layout.
4. onActivityCreated: Activity and fragment are fully initialized.
5. onStart: Fragment becomes visible.
6. onResume: Fragment is interactive.
7. onPause, onStop, onDestroyView: Clean-up phases.
8. onDetach: Fragment detached from the activity.
 Communication: Fragments communicate with activities and other fragments using interfaces,
ViewModels, or shared ViewModel patterns.
Creating a Tabbed Activity

 A Tabbed Activity is an activity that uses tabs to switch between different fragments or views.
 Android Studio has a pre-built template for creating a tabbed activity.
 Tabs can be implemented using TabLayout and ViewPager2 components.

Setting Up Tabs with ViewPager

 ViewPager allows users to swipe between fragments.


 Steps to set up tabs:
1. Add TabLayout and ViewPager2 to your layout file.
2. Use a FragmentStateAdapter to manage fragments for each tab.
3. Link the TabLayout with the ViewPager2 using a TabLayoutMediator.

Calling Built-in Applications Using Intents

 Intent: A message that lets you perform actions or launch other apps.
 Example: To open the phone dialer, use an Intent like this:
 Intent intent = new Intent(Intent.ACTION_DIAL);
 intent.setData(Uri.parse("tel:123456789"));
 startActivity(intent);

Working with Built-in and Implicit Intents

 Built-in Intents: Predefined actions like making calls, sending messages, or opening a browser.
 Implicit Intents: Specify the type of action to perform but not the specific component to handle it.
Example:
 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setData(Uri.parse("http://www.google.com"));
 startActivity(intent);

Introduction to Content Providers

 Content Providers enable apps to share data with other apps securely.
 They provide a standard way to access data stored in databases, files, or other storage.
 Examples: Contacts, calendar, and media files.

Accessing Data Using Content Providers

 Use a ContentResolver to query, insert, update, or delete data from content providers. Example:
 Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
SQLite Basics: Creating and Managing a Database

 SQLite is a lightweight database embedded within Android.


 Steps to create a database:
1. Extend the SQLiteOpenHelper class.
2. Override onCreate to define tables.
3. Use getWritableDatabase() or getReadableDatabase() to interact with the database.

Performing CRUD Operations in SQLite (Create, Read)

 Create: Insert data into the database.


 ContentValues values = new ContentValues();
 values.put("name", "John");
 db.insert("users", null, values);
 Read: Retrieve data using queries.
 Cursor cursor = db.query("users", null, null, null, null, null, null);

Performing CRUD Operations in SQLite (Update, Delete)

 Update: Modify existing data.


 ContentValues values = new ContentValues();
 values.put("name", "Jane");
 db.update("users", values, "id=?", new String[]{"1"});
 Delete: Remove data.
 db.delete("users", "id=?", new String[]{"1"});

Linking SQLite Database with Android UI

 Combine SQLite operations with UI components like EditText, ListView, and RecyclerView to display
and manage data dynamically.

Firebase Setup and Introduction

 Firebase is a platform by Google for building apps with integrated cloud services.
 Setup: Add Firebase SDK to your project by including the necessary dependencies in the Gradle file
and syncing with Firebase.

Firebase Authentication (Login, Registration)

 Firebase provides authentication methods like email/password and social logins.


 Example:
 FirebaseAuth auth = FirebaseAuth.getInstance();
 auth.createUserWithEmailAndPassword(email, password)
 .addOnCompleteListener(task -> {
 if (task.isSuccessful()) {
 // User registered
 }
 });

Working with Firebase Realtime Database (Data Insertion)

 Firebase Realtime Database stores and syncs data in real-time.


 Example of data insertion:
 DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");
 ref.child("user1").setValue(new User("John", 25));

Fetching and Updating Data in Firebase

 Fetching:
 ref.child("user1").addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot snapshot) {
 User user = snapshot.getValue(User.class);
 }
 @Override
 public void onCancelled(DatabaseError error) {
 }
 });
 Updating:
 ref.child("user1").child("age").setValue(30);

Integrating Firebase with Android App (Practical)

 Use Firebase features like authentication, Realtime Database, and cloud functions in your app to
enhance functionality.
 Example: Combine Firebase Authentication with Realtime Database for user profile management.

Data Filtering and Querying in Firebase

 Use queries to filter and sort data from the Firebase Realtime Database. Example:
 Query query = ref.orderByChild("age").equalTo(25);
 query.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot snapshot) {
 // Process data
 }
 @Override
 public void onCancelled(DatabaseError error) {
 }
 });

You might also like