Mobile Application Development
Mobile Application Development
Fragmentation Slide
Lecture Objectives
1. Understanding Fragments:
2. Differentiating Fragments:
3. Fragment Lifecycle:
4. Tabbed Activities:
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.
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():
2. onCreate():
5. onDestroyView():
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:
3. FragmentManager:
Purpose:
Enhances user experience by organizing content into tabs.
Tools:
1. ViewPager2:
2. TabLayout:
Displays the tabs for easy access.
Real-World Examples
Messaging Apps:
Fragment Lifecycle
Fragment vs. Activity Lifecycle
Fragments depend on their parent activity for lifecycle management but have unique
events:
1. onAttach():
4. onDestroyView():
Cleans up the fragment's view-related resources.
5. onDetach():
Disconnects the fragment from the activity.
Comparison Table
Fragments:
Ideal for reusable, modular UI (e.g., tabs, master-detail).
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.
2. setText(int):
This is used to set an icon for a tab. Icons help users understand what the tab
represents.
It is commonly used when there are multiple tabs, and you want to make navigation
smooth.
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).
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:
Interaction:
The Content Resolver class is used by apps to communicate with Content
Providers.
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.
1. Create:
Add new data to the Content Provider.
2. Read:
Retrieve data from the Content Provider.
3. Update:
4. Delete:
This setup ensures efficient communication between the UI and the data storage.
Practical Example:
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.
It provides tools that allow you to build apps quickly without worrying about
setting up servers.
Authentication:
For managing user login and registration.
Realtime Database:
Stores and syncs data in real time across users.
Cloud Firestore:
Cloud Messaging:
Storage:
Easy to Use:
Free Tier:
Suitable for small projects or learning.
2.1 Prerequisites
Before starting, ensure:
FirebaseDatabase.getInstance().getReference("test").setValue("Hello
Firebase!");
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.
Registering a User:
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.
Scalability:
o Ride-Hailing Apps:
Real-time updates of driver and rider locations.
Homework Assignment
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.
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).
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.).
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.
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.
What it does: Creates a Paint object, which is like a brush used for drawing on the canvas.
paint.setColor(Color.BLUE);
paint.setTextSize(50);
What it does: Sets the size of the text that will be drawn using the brush.
What it does: Draws the word "Rectangle" on the canvas at the position (420, 150).
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).
What it does: Draws the word "Circle" at the position (120, 150).
What it does: Draws a circle with a center at (200, 350) and a radius of 150.
What it does: Draws the word "Square" at the position (120, 800).
What it does: Draws a square. The top-left corner is (50, 850), and the bottom-right corner is (350,
1150).
What it does: Draws a vertical line from the point (520, 850) to (520, 1150).
Closing Braces:
}
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;
@Override
ImageView i = findViewById(R.id.imageView);
i.setImageDrawable(new BitmapDrawable(getResources(), 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
// To draw a Circle
// To draw a Line
OutPut:
LAB 5
Code for MainActivity.java:
package com.example.lab_manuals;
import android.app.Activity;
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;
@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);
if(view==Insert)
if(Rollno.getText().toString().trim().length()==0
|| Name.getText().toString().trim().length()==0
||
Marks.getText().toString().trim().length()==0)
return;
clearText();
}
if(view==Delete)
if(Rollno.getText().toString().trim().length()==0)
else
clearText();
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno"); return;
Rollno");
clearText();
if(Rollno.getText().toString().trim().length()==0)
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
else
if(c.getCount()==0)
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message); builder.show();
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.
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
@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);
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.
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);");
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();
}
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();
}
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();
}
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();
}
}
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());
}
Helper Methods
showMessage
clearText
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;
Class Declaration
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.
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.
Exception Handling
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (XmlPullParserException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
onPostExecute Method
protected void onPostExecute(ArrayAdapter adapter)
{
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1,
headlines);
setListAdapter(adapter);
}
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 androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
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.
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.
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.
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/
What to Expect:
Your app will display a screen with two fragments:
o An Upper Fragment (pink background with "Upper Fragment" text).
Let me know if you face any specific problems during these steps!
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.
@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:
xmlns::
weightSum="2":
padding="15dp":
tools:context=".MainActivity":
<fragment
android:id="@+id/fragUpper"
android:name="com.example.staticfregmentation.UpperFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<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>
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;
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
<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>
5. LowerFragment.java
This file defines what the LowerFragment looks like and how it behaves.
package com.example.staticfregmentation;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public LowerFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment_lower, container, false);
}
}
6. fragment_lower.xml
<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">
<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>
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">
<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>
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.
Dynamic Fragments:
These are added, removed, or replaced during runtime, using code.
1. onAttach:
Fragment is attached to 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.
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.
To get data from a Content Provider, apps use a special method called ContentResolver.
Steps:
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
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.
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.
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);
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);
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.
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
Combine SQLite operations with UI components like EditText, ListView, and RecyclerView to display
and manage data dynamically.
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.
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);
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.
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) {
}
});