0% found this document useful (0 votes)
3 views

Android App Development (2)

The document serves as a comprehensive guide to Android development, covering topics such as Android architecture, project structure, UI design, and data storage techniques. It includes detailed sections on setting up the development environment, creating applications, and deploying them, along with practical lab exercises. Additionally, it discusses career opportunities in Android development and provides insights into the features and evolution of the Android operating system.

Uploaded by

vsurender reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Android App Development (2)

The document serves as a comprehensive guide to Android development, covering topics such as Android architecture, project structure, UI design, and data storage techniques. It includes detailed sections on setting up the development environment, creating applications, and deploying them, along with practical lab exercises. Additionally, it discusses career opportunities in Android development and provides insights into the features and evolution of the Android operating system.

Uploaded by

vsurender reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

TABLE OF CONTENTS

1. Introduction to Android and Android Studio

1.1 Android Overview

1.2 Features of Android

1.3 Introduction to Android Studio

2. Setting Up the Development Environment

2.1 Installation Process

2.2 First Application

3. Android Architecture and Project Structure

3.1 Android Architecture Layers

3.2 Components of Android Application

3.3 Project File Structure

4. UI Design and Layout Management

4.1 Layout Types

4.2 Common UI Widgets

4.3 Advanced Views

4.4 Designing User-Friendly Interfaces

5. Activities, Intents, and Fragments

5.1 Activities

5.2 Intents

5.3 Fragments

6. Data Storage Techniques in Android

6.1 SharedPreferences

6.2 Internal and External Storage

6.3 SQLite Database

7. Web Services and API Integration

7.1 Working with Web APIs

7.2 JSON Parsing

7.3 Retrofit Integration


8. Background Tasks and Notifications

8.1 Background Processing

8.2 Broadcast Receivers

8.3 Notifications

9. Location-Based Services and Google Maps

9.1 Accessing Device Location

9.2 Integrating Google Maps

10. Application Deployment and Project Work

10.1 Preparing App for Release

10.2 Publishing to Google Play

10.3 Final Project Guidelines

Suggested Lab Exercises


1. Introduction to Android and Android Studio

1.1 Android Overview

Definition and Purpose


Android is an open-source mobile operating system developed by Google, primarily used in
touchscreen mobile devices such as smartphones and tablets. It offers a rich application framework
and user interface tailored to handle complex interactions through touch gestures.

History and Evolution


Android Inc. was founded in 2003 and acquired by Google in 2005. The first commercial Android
device was released in 2008. Each version of Android, until version 10, was named after desserts,
such as Cupcake, Donut, Eclair, and so on. Android versions are known for improvements in user
interface, security, speed, and hardware compatibility.

Version Name Release Year

1.5 Cupcake 2009

2.2 Froyo 2010

4.0 Ice Cream Sandwich 2011

5.0 Lollipop 2014

6.0 Marshmallow 2015

7.0 Nougat 2016

8.0 Oreo 2017

9.0 Pie 2018

10+ Numeric only 2019 onwards

Key Features

• Multi-tasking: Run multiple applications simultaneously.

• Connectivity: Support for Wi-Fi, Bluetooth, NFC, and more.

• App Store Integration: Access to Google Play Store with millions of apps.

• Customizability: OEMs and developers can heavily customize Android.

• Developer-Friendly: Strong community support and documentation.

Use Cases

• Smartphones and tablets


• Smart TVs

• Wearable devices (Wear OS)

• Automotive infotainment systems (Android Auto)

• IoT Devices

1.2 Features of Android

• Open Source: Available under Apache License; developers can modify the source code.

• Rich Development Environment: Integrated with debugging tools, memory and performance
profiling, and device emulation.

• Optimized for Mobile: Designed specifically for constrained environments.

• Multimedia Support: Supports a wide range of audio, video, and image formats.

• Cloud Integration: Tight integration with Google Cloud and Firebase.

1.3 Introduction to Android Studio

What is Android Studio?


Android Studio is the official Integrated Development Environment (IDE) for Android app
development, based on IntelliJ IDEA. It offers tools for designing, developing, testing, and publishing
Android applications.

Key Features

• Intelligent Code Editor: Code completion, refactoring, and suggestions.

• Flexible Build System: Uses Gradle to build apps efficiently.

• Emulator Support: Run and test apps without a physical device.

• UI Design Tools: Drag-and-drop features for XML layout editing.

• Real-Time Profiler: Monitor CPU, memory, and network usage.

• Firebase Integration: For real-time databases, analytics, and cloud messaging.

Comparison with Other IDEs

Feature Android Studio Eclipse with ADT IntelliJ IDEA

Official Support Yes No (deprecated) Yes (via plugin)

UI Designer Excellent Limited Moderate

Performance Tools Advanced Basic Moderate

1.4 Programming Languages for Android


• Java: Originally the primary language for Android development; stable and mature.

• Kotlin: Now preferred by Google; concise and safer than Java.

• C++: For high-performance apps using the Android NDK.

• Others: Python (via third-party tools), Flutter (Dart), and React Native (JavaScript)

1.5 Real-World Applications of Android

• Banking apps like Google Pay and PhonePe

• E-commerce apps like Amazon and Flipkart

• Social Media apps like WhatsApp, Instagram

• Health & Fitness trackers

• Education (E-learning platforms, coding apps)

• Entertainment (OTT platforms, Games)

1.6 Career Opportunities in Android Development

• Job Roles:

o Android Developer

o Mobile App Tester

o UI/UX Designer

o Firebase Engineer

o Full-Stack Mobile Developer

• Average Salary (India): ₹3.5 – ₹10 LPA

• Growth Trends: Increasing demand in startups, fintech, edtech, and IoT sectors.

2. Setting Up the Development Environment

2.1 Installation Process

A. Prerequisites

Before starting with Android development, ensure the following prerequisites are met:

• A computer running Windows, macOS, or Linux


• Minimum 8 GB RAM (16 GB recommended)

• At least 4 GB of disk space

• Stable internet connection

• Knowledge of Java or Kotlin (basics)

B. Installing Java Development Kit (JDK)

Android applications (especially those using Java) require the Java Development Kit (JDK).

Steps to Install JDK:

1. Visit the official Oracle JDK download page

2. Download the JDK appropriate for your OS.

3. Install the JDK and set the environment variable:

o Windows: Add the JAVA_HOME path in system environment variables.

o Linux/Mac: Export JAVA_HOME in the terminal or .bashrc/.zshrc.

Check Installation:

java -version

C. Downloading and Installing Android Studio

Steps:

1. Visit https://developer.android.com/studio

2. Download the latest Android Studio.

3. Run the installer:

o Choose SDK and Emulator setup during the wizard.

o Allow the installer to download required components.

4. Launch Android Studio after installation.

D. SDK Manager and SDK Tools

SDK Manager is where you manage Android versions and tools required to compile and run your
app.

• Tools in SDK Manager:

o Android SDK Tools

o Android SDK Platform-Tools


o Android SDK Build-Tools

o NDK (Native Development Kit)

Ensure the following are installed:

• SDK Platform (e.g., Android 11, API Level 30 or higher)

• Emulator images (for ARM or x86 devices)

• Google USB Driver (for real device debugging)

E. Emulator Setup and Configuration

Android Emulator allows you to test apps without a physical device.

Steps to Create an Emulator:

1. Open Android Studio → Tools → AVD Manager

2. Click “Create Virtual Device”

3. Choose a hardware profile (Pixel 4, Nexus 5X, etc.)

4. Select a system image (e.g., Android 12 x86)

5. Configure RAM, resolution, and device orientation

6. Launch emulator to test your apps

Note: Emulator requires Virtualization (VT-x/AMD-V) enabled in BIOS.

2.2 First Application

A. Creating a New Project

1. Open Android Studio → Click New Project

2. Choose a template (e.g., Empty Activity)

3. Set:

o Name: HelloWorld

o Language: Java or Kotlin

o Minimum SDK: Choose API 21 (Lollipop) or above

4. Finish → Wait for Gradle to build the project

B. Exploring the Project Structure

The generated project will contain:


HelloWorld/

├── manifests/ (AndroidManifest.xml)

├── java/ (Source code)

│ └── com.example.helloworld.MainActivity.java

├── res/ (Resources)

│ ├── layout/ (XML layout files)

│ ├── drawable/ (Images and vector icons)

│ └── values/ (strings.xml, styles.xml)

├── build.gradle (App level and project level)

Important files:

• MainActivity.java: Main logic

• activity_main.xml: UI layout

• AndroidManifest.xml: App metadata

• Gradle Files: Build configuration and dependencies

C. Running “Hello World” App

1. Open MainActivity.java and ensure the code is:

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

2. Open activity_main.xml and define the UI:

<TextView

android:id="@+id/helloText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World!"

android:layout_gravity="center"
android:textSize="24sp"/>

3. Click the Run button (green triangle) in the toolbar.

4. Choose an emulator or connected device.

5. Output: “Hello World!” appears on the screen.

D. Using Logcat for Debugging

Logcat is Android’s logging system that shows real-time logs while your app is running.

To use Logcat:

1. Go to View → Tool Windows → Logcat

2. Add logs in Java:

Log.d("MainActivity", "App has started");

3. Filters can help focus on only your app logs:

o Select the app package name

o Choose log levels: Debug, Info, Error, etc.

Assignments and Lab Activities:

1. Install JDK and Android Studio on your personal computer.

2. Create a new project and explore the project file structure.

3. Build and run your first app on an emulator and your Android phone.

4. Practice writing log statements and viewing them using Logcat.

3. Android Architecture and Project Structure

3.1 Android Architecture Layers

Android architecture is designed in a layered fashion. Each layer provides services to the layer above
it and utilizes the services of the layer below it.

A. Linux Kernel (Bottom Layer)

• Acts as the foundation of the Android platform.

• Provides:

o Hardware abstraction
o Memory management

o Process and thread management

o Networking

o Security settings

• Devices drivers: Wi-Fi, Bluetooth, Display, Camera, Audio, etc.

B. Native Libraries

• Built using C/C++.

• Important native libraries include:

o WebKit – browser engine

o OpenGL|ES – graphics rendering

o SQLite – relational database engine

o Media Framework – audio/video codecs

o Surface Manager – UI rendering

C. Android Runtime (ART)

• Replaced Dalvik VM (from Android 5.0 onwards).

• Converts .dex files into native instructions using ahead-of-time (AOT) compilation.

• Improves performance, memory management, and battery life.

• Includes core libraries (e.g., Collections, IO, threading).

D. Application Framework

• High-level APIs used by developers to build Android apps.

• Provides access to:

o Activity Manager

o Content Providers

o Resource Manager

o Notification Manager

o View System

E. Applications (Top Layer)

• The user-facing applications.

• Examples: Phone, Contacts, Email, Games, Custom Apps.

• Developers write apps that run on this layer using the APIs from lower levels.
3.2 Components of Android Application

Android apps are built from four main components, each playing a unique role:

A. Activities

• Represents a single screen with UI.

• Every app starts from MainActivity.

• Manages lifecycle via methods like onCreate(), onStart(), onPause(), etc.

• Can be linked to other activities using Intents.

B. Services

• Runs in the background without UI.

• Used for long-running operations like:

o Playing music

o Downloading files

o Syncing data

• Types: Started Service and Bound Service

C. Broadcast Receivers

• Listens for system-wide broadcast events.

• Examples:

o Battery low

o Connectivity changes

o SMS received

• Can register statically (via manifest) or dynamically (in code)

D. Content Providers

• Allows an app to share data with other apps.

• Uses URI format to access data.

• Provides CRUD access to structured data like contacts, images, etc.

3.3 Project File Structure

When you create a new project in Android Studio, several directories and files are auto-generated:

A. Manifest Folder

• Contains AndroidManifest.xml

• Declares:
o Package name

o Permissions (e.g., internet access)

o Activities, services, receivers

o App launcher icon and name

Example:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.myapp">

<application

android:label="MyApp"

android:icon="@mipmap/ic_launcher">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN"/>

<category android:name="android.intent.category.LAUNCHER"/>

</intent-filter>

</activity>

</application>

</manifest>

B. Java/Kotlin Folder

• Contains your source code and logic

• Structured by packages

• Includes:

o MainActivity.java or .kt (entry point)

o Other activities, adapters, utility classes

C. res (Resources) Folder

Houses all the non-code UI elements, including:

• layout/: XML files that define UI design


• drawable/: PNG, JPEG, SVG images or shape files

• mipmap/: App launcher icons (supports various screen sizes)

• values/:

o strings.xml: Reusable text values

o colors.xml: Centralized color codes

o styles.xml: App themes and styles

D. Gradle Scripts

There are two build.gradle files:

1. Project-level build.gradle

o Applies global configuration (e.g., repositories, classpath).

2. App-level build.gradle

o Contains:

▪ Application ID

▪ Compile SDK and target SDK versions

▪ Dependencies (libraries)

▪ Versioning info

Example:

android {

compileSdkVersion 33

defaultConfig {

applicationId "com.example.myapp"

minSdkVersion 21

targetSdkVersion 33

versionCode 1

versionName "1.0"

dependencies {

implementation 'com.google.android.material:material:1.9.0'
}

Lab Activities and Assignments

• Draw the Android architecture in your notebook and label each layer.

• Create a dummy project and identify the use of each folder in the structure.

• Modify the manifest file to change app name and add an additional activity.

UI Design and Layout Management

4.1 Introduction to Android UI

The User Interface (UI) in Android is built using XML layout files and connected with Java/Kotlin
code. Android offers a range of UI elements (widgets) like buttons, text fields, images, etc., that help
create visually engaging applications.

Key Concepts:

• View: A UI element (e.g., TextView, Button)

• ViewGroup: A layout that contains Views (e.g., LinearLayout, RelativeLayout)

4.2 Layout Types

Android provides various types of layouts for positioning and aligning views.

A. LinearLayout

• Arranges elements in a single row or column

• Attributes: orientation="vertical" or horizontal

<LinearLayout

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView android:text="Welcome"/>

<Button android:text="Click Me"/>

</LinearLayout>

B. RelativeLayout (Deprecated in latest APIs)


• Places elements relative to each other or to parent

• Allows complex positioning but now often replaced by ConstraintLayout

C. ConstraintLayout

• A flexible layout that replaces RelativeLayout

• Allows positioning based on constraints to other views

<androidx.constraintlayout.widget.ConstraintLayout>

<Button

android:id="@+id/myBtn"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

D. FrameLayout

• Stacks all children on top of each other (like layers)

• Useful for loading screens, overlapping views

E. GridLayout & TableLayout

• GridLayout: Arranges views in rows and columns

• TableLayout: Like HTML tables; used for forms or tables

4.3 Views and ViewGroups

• Views: UI elements that users interact with

o TextView, Button, EditText, ImageView, CheckBox, Switch, ProgressBar

• ViewGroups: Containers for Views

o LinearLayout, ConstraintLayout, FrameLayout

4.4 TextView and EditText

TextView

Used to display text to the user.


<TextView

android:id="@+id/txtHello"

android:text="Hello, World!"

android:textSize="18sp"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

EditText

Used to receive input from the user.

<EditText

android:id="@+id/editName"

android:hint="Enter your name"

android:layout_width="match_parent"

android:layout_height="wrap_content"/>

4.5 Buttons and Event Handling

Button

A clickable UI element to perform actions.

<Button

android:id="@+id/btnSubmit"

android:text="Submit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

Handling Clicks in Java/Kotlin

Java:

Button btn = findViewById(R.id.btnSubmit);

btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

Toast.makeText(getApplicationContext(), "Button clicked!", Toast.LENGTH_SHORT).show();

});

Kotlin:

val btn = findViewById<Button>(R.id.btnSubmit)

btn.setOnClickListener {

Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show()

4.6 ImageView and Media Integration

ImageView

Used to display images.

<ImageView

android:id="@+id/imageLogo"

android:layout_width="100dp"

android:layout_height="100dp"

android:src="@drawable/logo"/>

Adding Media Files

• Add image or video files into res/drawable or res/raw folders.

• Use MediaPlayer class to play sound or video files.

Example:

MediaPlayer mp = MediaPlayer.create(this, R.raw.soundfile);

mp.start();

4.7 Toasts, Snackbars, and Dialogs

Toast

Used for displaying short messages to the user.


Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show();

Snackbar

Like a toast but with an action button, ideal for user interaction.

Snackbar.make(findViewById(android.R.id.content), "Deleted", Snackbar.LENGTH_LONG)

.setAction("UNDO", v -> { /* undo code */ }).show();

Dialogs

Used for alerts, confirmations, and prompts.

new AlertDialog.Builder(this)

.setTitle("Exit")

.setMessage("Are you sure?")

.setPositiveButton("Yes", (dialog, which) -> finish())

.setNegativeButton("No", null)

.show();

Lab Tasks and Assignments:

1. Design a screen with:

o A welcome TextView

o An EditText to input name

o A Button that shows a toast saying “Hello, [name]”

2. Use ConstraintLayout to center align all elements.

3. Add an ImageView and a play button to play a sound using MediaPlayer.

4. Practice using Dialogs and Snackbars for basic alerts.

5. Activities, Intents, and Navigation

5.1 Understanding Activities

An Activity represents a single screen with a user interface in Android apps. It acts as the entry point
for user interaction.

Key Methods in Activity Lifecycle:

1. onCreate() – Called when activity is first created.


2. onStart() – Called when the activity becomes visible.

3. onResume() – Called when the user can interact with the activity.

4. onPause() – Called when activity is partially visible.

5. onStop() – Called when the activity is no longer visible.

6. onDestroy() – Called when the activity is finishing.

Activity Lifecycle Flow:

onCreate → onStart → onResume

↓ ↑

onPause ← onStop ← onRestart

onDestroy

5.2 Creating Multiple Activities

Apps often need more than one screen, such as a login screen, dashboard, profile, etc. For each new
screen, we define a new Activity.

Steps to Add a New Activity:

1. Right-click on the java/ folder → New → Activity → Empty Activity

2. Name it (e.g., SecondActivity)

3. Android Studio will generate:

o SecondActivity.java / .kt

o activity_second.xml

4. Declare the new activity in AndroidManifest.xml:

<activity android:name=".SecondActivity"></activity>

5.3 Intents and Intent Filters

Intents

An Intent is a messaging object used to request an action from another app component.

Types:

• Explicit Intent – Starts a specific component within your app.

• Implicit Intent – Requests action from another app (e.g., open browser, call).

Explicit Intent Example:


Intent intent = new Intent(MainActivity.this, SecondActivity.class);

startActivity(intent);

Passing Data with Intent:

intent.putExtra("username", "John");

Receiving Data in SecondActivity:

String name = getIntent().getStringExtra("username");

Implicit Intent Example:

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setData(Uri.parse("https://www.google.com"));

startActivity(intent);

5.4 Navigating Between Screens

Use startActivity() to move between activities. Optionally, use finish() to remove the current activity
from the stack.

Intent intent = new Intent(this, DashboardActivity.class);

startActivity(intent);

finish(); // Optional

5.5 Back Stack and Navigation

The Android system manages a back stack of activities for navigation. Pressing the back button pops
the top activity off the stack.

• You can override onBackPressed() to customize behavior.

• Use finish() to end the current activity.

5.6 Activity Result APIs (Modern Alternative to startActivityForResult)


To get a result back from another activity (e.g., user picks a file), use the modern
ActivityResultLauncher.

Java Example (New API):

ActivityResultLauncher<Intent> launcher = registerForActivityResult(

new ActivityResultContracts.StartActivityForResult(),

result -> {

if (result.getResultCode() == RESULT_OK) {

Intent data = result.getData();

// handle returned data

});

Intent intent = new Intent(this, SecondActivity.class);

launcher.launch(intent);

5.7 Using Navigation Component (Optional Advanced)

Android Jetpack's Navigation Component simplifies fragment-based navigation.

• Define navigation in navigation_graph.xml

• Use NavController to manage navigation

• Helps implement navigation drawer, bottom nav, etc.

Assignments and Activities:

1. Create two activities: LoginActivity and DashboardActivity.

2. Pass username from LoginActivity to DashboardActivity using Intent.

3. Add a Back button in DashboardActivity that returns to LoginActivity.

4. Use an Implicit Intent to open a website or dial a number.

5. Create a form and use Toast/Snackbar to confirm data submission.

6. Data Storage and Persistence

In Android, data storage is crucial for saving user preferences, files, and databases. This section
covers various methods used to store data locally on an Android device.
6.1 SharedPreferences

SharedPreferences is used for storing small amounts of key-value data, such as login sessions,
settings, or user preferences.

Storing Data:

SharedPreferences sharedPref = getSharedPreferences("MyPrefs", MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPref.edit();

editor.putString("username", "JohnDoe");

editor.putBoolean("isLoggedIn", true);

editor.apply();

Retrieving Data:

SharedPreferences sharedPref = getSharedPreferences("MyPrefs", MODE_PRIVATE);

String username = sharedPref.getString("username", "Guest");

boolean isLoggedIn = sharedPref.getBoolean("isLoggedIn", false);

Deleting Data:

editor.remove("username"); // removes only one

editor.clear(); // clears all

editor.apply();

6.2 Internal Storage

Used for storing private data within the app's internal directory.

Saving a File:

String data = "Hello, Android!";

FileOutputStream fos = openFileOutput("example.txt", MODE_PRIVATE);

fos.write(data.getBytes());

fos.close();

Reading a File:

FileInputStream fis = openFileInput("example.txt");

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));


String line;

while ((line = reader.readLine()) != null) {

Log.d("FileRead", line);

fis.close();

Note: Internal storage files are not accessible by other apps.

6.3 External Storage (Deprecated in many modern APIs)

Used for storing files on SD card or external shared directories (e.g., Downloads, Pictures).

Permissions Needed:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Checking Availability:

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

// Safe to write

Note: Scoped Storage in Android 10+ limits external access.

6.4 SQLite Database

SQLite is a lightweight relational database built into Android. It stores structured data locally.

Creating a DB Helper Class:

public class DBHelper extends SQLiteOpenHelper {

public DBHelper(Context context) {

super(context, "StudentDB", null, 1);

public void onCreate(SQLiteDatabase db) {


db.execSQL("CREATE TABLE Students(id INTEGER PRIMARY KEY, name TEXT)");

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS Students");

onCreate(db);

Inserting Data:

SQLiteDatabase db = helper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put("name", "Alice");

db.insert("Students", null, values);

Reading Data:

Cursor cursor = db.rawQuery("SELECT * FROM Students", null);

while (cursor.moveToNext()) {

Log.d("Student", cursor.getString(1)); // name

6.5 Room Database (Modern SQLite Alternative)

Room is part of Android Jetpack and provides an abstraction over SQLite with annotations and
compile-time checks.

Define an Entity:

@Entity

public class User {

@PrimaryKey(autoGenerate = true)

public int uid;


@ColumnInfo(name = "username")

public String name;

Create DAO Interface:

@Dao

public interface UserDao {

@Insert

void insertUser(User user);

@Query("SELECT * FROM User")

List<User> getAllUsers();

Database Class:

@Database(entities = {User.class}, version = 1)

public abstract class AppDatabase extends RoomDatabase {

public abstract UserDao userDao();

Using Room in Activity:

AppDatabase db = Room.databaseBuilder(getApplicationContext(),

AppDatabase.class, "my-database").build();

new Thread(() -> {

db.userDao().insertUser(new User("TestUser"));

}).start();

Practical Activities:

1. Use SharedPreferences to implement a "Remember Me" login checkbox.

2. Save and read a short user note using Internal Storage.


3. Create an SQLite database to store and display student records.

4. Implement Room Database to handle a list of products with Room + RecyclerView.

7. Working with Multimedia and Sensors

This module explores how to incorporate audio, video, images, and device sensors like accelerometer
and gyroscope into your Android applications to create more interactive and responsive experiences.

7.1 Playing Audio and Video

Android provides classes like MediaPlayer and VideoView to handle multimedia playback.

Playing Audio with MediaPlayer

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.musicfile);

mediaPlayer.start(); // Play audio

• Add your .mp3 file in the res/raw/ directory.

Controlling Playback:

mediaPlayer.pause(); // Pause

mediaPlayer.seekTo(0); // Rewind

mediaPlayer.stop(); // Stop

Release Resources:

mediaPlayer.release();

Playing Video with VideoView

<VideoView

android:id="@+id/videoView"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

VideoView videoView = findViewById(R.id.videoView);

videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.sample_video);

videoView.start();
Use MediaController for playback controls:

MediaController mediaController = new MediaController(this);

videoView.setMediaController(mediaController);

7.2 Capturing Images and Videos Using Camera

Using Camera Intent to Capture Image

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

Get the image in onActivityResult:

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

Bundle extras = data.getExtras();

Bitmap imageBitmap = (Bitmap) extras.get("data");

imageView.setImageBitmap(imageBitmap);

7.3 Sensors and SensorManager

Android devices come with various sensors:

• Accelerometer (motion)

• Gyroscope (rotation)

• Proximity sensor

• Light sensor

Using the Accelerometer

SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

SensorEventListener sensorListener = new SensorEventListener() {

@Override

public void onSensorChanged(SensorEvent event) {


float x = event.values[0];

float y = event.values[1];

float z = event.values[2];

Log.d("Sensor", "X: " + x + " Y: " + y + " Z: " + z);

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy) {}

};

sensorManager.registerListener(sensorListener, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);

Don't forget to unregister the listener:

@Override

protected void onPause() {

super.onPause();

sensorManager.unregisterListener(sensorListener);

7.4 Using the Microphone

Recording Audio

Use MediaRecorder to record from the microphone.

MediaRecorder recorder = new MediaRecorder();

recorder.setAudioSource(MediaRecorder.AudioSource.MIC);

recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

recorder.setOutputFile("/sdcard/record.3gp");

recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

try {

recorder.prepare();

recorder.start();
} catch (IOException e) {

e.printStackTrace();

Stop Recording:

recorder.stop();

recorder.release();

Permission Needed:

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

7.5 Accessing the Gallery

To pick an image from the gallery:

Intent intent = new Intent(Intent.ACTION_PICK,


MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(intent, PICK_IMAGE_REQUEST);

Handling Result:

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {

Uri selectedImage = data.getData();

imageView.setImageURI(selectedImage);

Practical Activities:

1. Play an audio file and allow the user to pause/resume playback.

2. Capture a picture using the device’s camera and display it in an ImageView.

3. Record audio using the microphone and save the file to external storage.

4. Use the accelerometer to detect phone shake.

5. Display a video using VideoView with playback controls.


8. Working with Web Services and APIs

This section will guide you through integrating Android applications with web services, including
calling RESTful APIs, parsing JSON data, and displaying results in your app using modern libraries.

8.1 Introduction to Web Services and REST APIs

Web Services allow apps to communicate over the internet, typically through HTTP.

REST (Representational State Transfer) is a popular architecture for designing networked


applications. It uses HTTP methods like:

• GET – Retrieve data

• POST – Create data

• PUT – Update data

• DELETE – Remove data

A REST API provides access to server-side resources such as user profiles, product lists, etc., in
formats like JSON or XML.

8.2 Using HTTP with AsyncTask (Legacy Approach)

While now deprecated for production, it's important to understand how AsyncTask was used to
perform background API calls.

private class GetDataTask extends AsyncTask<Void, Void, String> {

protected String doInBackground(Void... voids) {

try {

URL url = new URL("https://api.example.com/data");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

InputStream in = new BufferedInputStream(conn.getInputStream());

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

StringBuilder result = new StringBuilder();

String line;

while ((line = reader.readLine()) != null) {

result.append(line);

}
return result.toString();

} catch (Exception e) {

return null;

protected void onPostExecute(String result) {

// Parse and display result

8.3 Parsing JSON Data

Assume we get this JSON response from an API:

"name": "John Doe",

"email": "[email protected]"

We can parse it as:

try {

JSONObject jsonObject = new JSONObject(response);

String name = jsonObject.getString("name");

String email = jsonObject.getString("email");

} catch (JSONException e) {

e.printStackTrace();

For a JSON array:

{"name": "Alice"},

{"name": "Bob"}

JSONArray jsonArray = new JSONArray(response);


for (int i = 0; i < jsonArray.length(); i++) {

JSONObject obj = jsonArray.getJSONObject(i);

String name = obj.getString("name");

8.4 Using Retrofit (Recommended Library)

Retrofit is a powerful HTTP client for Android and Java, developed by Square.

Add Dependencies:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

Create API Interface:

public interface ApiService {

@GET("users")

Call<List<User>> getUsers();

Model Class:

public class User {

String name;

String email;

Retrofit Setup:

Retrofit retrofit = new Retrofit.Builder()

.baseUrl("https://api.example.com/")

.addConverterFactory(GsonConverterFactory.create())

.build();

ApiService apiService = retrofit.create(ApiService.class);

Call<List<User>> call = apiService.getUsers();

call.enqueue(new Callback<List<User>>() {

@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {

List<User> users = response.body();

// Use the data

@Override

public void onFailure(Call<List<User>> call, Throwable t) {

// Handle error

});

8.5 Displaying API Data in RecyclerView

To display the fetched data:

1. Parse the JSON using Retrofit and Gson.

2. Pass the data to a RecyclerView.Adapter.

3. Display it in a list format.

recyclerView.setAdapter(new UserAdapter(userList));

8.6 Making POST Requests (Sending Data to Server)

@FormUrlEncoded

@POST("register")

Call<ResponseBody> registerUser(

@Field("name") String name,

@Field("email") String email

);

Call<ResponseBody> call = apiService.registerUser("Alice", "[email protected]");

call.enqueue(new Callback<ResponseBody>() {

public void onResponse(...) {

// success

}
public void onFailure(...) {

// error

});

8.7 Retrofit with LiveData and ViewModel (Advanced MVVM)

• Combine Retrofit with LiveData to update UI reactively.

• Use ViewModel to manage the data across configuration changes.

Practical Activities:

1. Call a GET API and show the response in a TextView.

2. Parse a JSON array and display items in a RecyclerView.

3. Use Retrofit to register a user with name and email (POST).

4. Create a weather app using a free weather API and show current temperature.

5. Implement a progress bar while data loads.

9. Building Real-Time Apps with Firebase

Firebase is a powerful platform for building real-time applications, with features such as
authentication, real-time database, and cloud storage. This section will walk you through integrating
Firebase services into your Android app.

9.1 Introduction to Firebase

Firebase is a platform provided by Google that includes a suite of services like:

• Firebase Authentication

• Firebase Realtime Database

• Firebase Firestore

• Firebase Cloud Messaging (FCM)

• Firebase Storage

9.2 Setting Up Firebase in Android

Steps to Integrate Firebase:


1. Go to the Firebase Console.

2. Create a new project.

3. In the Firebase console, add your Android app:

o Register your app with the package name.

o Download google-services.json and place it in the app/ folder.

4. Add Firebase SDK to your project by modifying your build.gradle files:

Project-level build.gradle:

classpath 'com.google.gms:google-services:4.3.10' // Add this line

App-level build.gradle:

apply plugin: 'com.google.gms.google-services' // Add this line at the bottom

Add the necessary Firebase dependencies in your app's build.gradle:

implementation 'com.google.firebase:firebase-auth:21.0.1'

implementation 'com.google.firebase:firebase-database:20.0.2'

Sync your project.

9.3 Firebase Authentication

Firebase Authentication allows you to easily authenticate users using different methods like
email/password, phone number, Google Sign-In, Facebook, etc.

Email and Password Authentication:

FirebaseAuth mAuth = FirebaseAuth.getInstance();

// Register a user

mAuth.createUserWithEmailAndPassword("[email protected]", "password")

.addOnCompleteListener(this, task -> {

if (task.isSuccessful()) {

// Registration success

FirebaseUser user = mAuth.getCurrentUser();

} else {

// Registration failure

Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show();

}
});

// Log in a user

mAuth.signInWithEmailAndPassword("[email protected]", "password")

.addOnCompleteListener(this, task -> {

if (task.isSuccessful()) {

// Login success

FirebaseUser user = mAuth.getCurrentUser();

} else {

// Login failure

Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show();

});

Sign-Out:

mAuth.signOut();

9.4 Firebase Realtime Database

Firebase Realtime Database is a cloud-hosted NoSQL database that supports real-time data syncing
between the client and server.

Storing Data:

FirebaseDatabase database = FirebaseDatabase.getInstance();

DatabaseReference myRef = database.getReference("users");

myRef.setValue("John Doe");

Reading Data:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");

ref.addValueEventListener(new ValueEventListener() {

@Override

public void onDataChange(DataSnapshot dataSnapshot) {

String value = dataSnapshot.getValue(String.class);

Log.d("Firebase", "Value is: " + value);


}

@Override

public void onCancelled(DatabaseError error) {

Log.w("Firebase", "Failed to read value.", error.toException());

});

Storing Complex Data:

To store custom objects:

class User {

String name;

String email;

public User(String name, String email) {

this.name = name;

this.email = email;

User user = new User("John Doe", "[email protected]");

myRef.setValue(user);

9.5 Firebase Firestore (NoSQL Database)

Firestore is Firebase’s newer, more scalable NoSQL database. Unlike Realtime Database, Firestore
allows storing data in documents and collections.

Storing Data in Firestore:

FirebaseFirestore db = FirebaseFirestore.getInstance();

Map<String, Object> user = new HashMap<>();

user.put("first", "John");

user.put("last", "Doe");

user.put("born", 1990);
db.collection("users")

.add(user)

.addOnSuccessListener(documentReference -> {

Log.d("Firestore", "DocumentSnapshot added with ID: " + documentReference.getId());

})

.addOnFailureListener(e -> Log.w("Firestore", "Error adding document", e));

Retrieving Data from Firestore:

db.collection("users")

.get()

.addOnCompleteListener(task -> {

if (task.isSuccessful()) {

QuerySnapshot documentSnapshots = task.getResult();

for (DocumentSnapshot document : documentSnapshots) {

Log.d("Firestore", document.getId() + " => " + document.getData());

} else {

Log.w("Firestore", "Error getting documents.", task.getException());

});

9.6 Firebase Cloud Messaging (FCM)

FCM enables you to send notifications to users or devices. You can send notifications directly from
the Firebase console or via backend systems.

Setting Up Firebase Cloud Messaging:

1. Enable Firebase Cloud Messaging in the Firebase Console.

2. Add the dependency in your app-level build.gradle file:

implementation 'com.google.firebase:firebase-messaging:23.0.0'

3. Create a custom service to handle incoming messages:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

if (remoteMessage.getData().size() > 0) {

Log.d("FCM", "Message data payload: " + remoteMessage.getData());

if (remoteMessage.getNotification() != null) {

Log.d("FCM", "Message Notification Body: " + remoteMessage.getNotification().getBody());

4. Don’t forget to declare the service in the AndroidManifest.xml:

<service

android:name=".MyFirebaseMessagingService"

android:exported="true">

<intent-filter>

<action android:name="com.google.firebase.MESSAGING_EVENT" />

</intent-filter>

</service>

Practical Activities:

1. Implement Firebase Authentication (login and register).

2. Store and retrieve user data using Firebase Realtime Database.

3. Create a chat app using Firebase Realtime Database for real-time messaging.

4. Store and retrieve data with Firestore in a shopping app.

5. Set up Firebase Cloud Messaging to send and receive notifications.

10. Testing and Debugging Android Apps

Testing and debugging are critical steps in the development process to ensure that Android
applications function as expected and are free from bugs or crashes. This module will cover the best
practices for testing Android applications and debugging common issues.

10.1 Introduction to Testing in Android


Testing ensures that the application behaves as expected across various scenarios. It helps identify
bugs and regressions before the app reaches users. Android supports different types of testing:

• Unit Testing: Tests individual units or components of the application (e.g., methods, classes).

• UI Testing: Tests the UI interactions and ensures that the app responds correctly to user
input.

• Integration Testing: Ensures that components of the app work together as expected.

10.2 Types of Testing

Unit Testing

Unit testing is the process of testing individual methods or functions. The most common framework
used for unit testing in Android is JUnit.

JUnit Example:

public class CalculatorTest {

private Calculator calculator;

@Before

public void setup() {

calculator = new Calculator();

@Test

public void testAddition() {

assertEquals(4, calculator.add(2, 2));

@Test

public void testSubtraction() {

assertEquals(0, calculator.subtract(2, 2));

In this example, we test the add and subtract methods of a Calculator class.
UI Testing with Espresso

Espresso is an Android UI testing framework that allows you to simulate user interactions and verify
UI behaviors.

Basic UI Test with Espresso:

@Test

public void testButtonClick() {

onView(withId(R.id.button))

.perform(click());

onView(withId(R.id.textView))

.check(matches(withText("Button clicked")));

This test simulates a button click and verifies that a TextView is updated correctly.

Integration Testing

Integration testing ensures that multiple components of the app work together correctly.

Example: Testing a network call followed by a UI update:

@Test

public void testNetworkRequestAndUIUpdate() {

mockNetworkCall();

onView(withId(R.id.button)).perform(click());

onView(withId(R.id.textView)).check(matches(withText("Data loaded")));

Here, we test whether the UI updates after a network request is completed.

10.3 Debugging Tools in Android Studio

Android Studio provides several tools to help developers identify and fix issues in their applications.

Logcat

Logcat is a system tool that provides detailed logs from Android devices. It is useful for tracking
errors, warnings, and debug messages.

• Access Logcat: In Android Studio, go to View > Tool Windows > Logcat.

• Log messages:
Log.d("TAG", "Debug message");

Log.e("TAG", "Error message", exception);

Log Levels:

• d - Debug

• e - Error

• i - Info

• w - Warning

• v - Verbose

Breakpoints and Debugger

Set breakpoints to pause execution at specific lines and inspect the variables, memory, and call stack.

• Set a Breakpoint: Click on the left margin next to the line number.

• Start Debugging: Click the Debug button in Android Studio (the bug icon) to run your app
with the debugger.

Debugging Commands:

• Step Over: Continue to the next line of code.

• Step Into: Dive into a method or function.

• Step Out: Exit the current method and go back to the caller.

10.4 Using Android Profiler

Android Profiler helps you monitor the performance of your app in real-time.

• CPU Profiler: Monitor CPU usage and identify performance bottlenecks.

• Memory Profiler: Track memory usage and identify potential memory leaks.

• Network Profiler: Monitor network traffic and check if the app is consuming too much
bandwidth.

You can access these tools via View > Tool Windows > Profiler.

10.5 Testing on Multiple Devices and Screen Sizes

It's crucial to test your application on different devices and screen sizes to ensure a consistent
experience for all users.

Using Android Virtual Device (AVD)

You can create different virtual devices (AVDs) with different screen sizes, Android versions, and
device types (e.g., phone, tablet, wearable). This is essential for testing how your app behaves on
various devices.
• Create an AVD: Go to Tools > AVD Manager and create a new device profile.

• Run on Multiple Devices: You can run your app simultaneously on physical devices and
virtual devices to ensure compatibility.

10.6 Firebase Test Lab

Firebase Test Lab allows you to test your app on a range of real devices hosted in Google's data
centers. It can simulate real-world conditions and help you test on devices you don't own.

• Integrate Test Lab with Android Studio by linking your project to Firebase.

• Run tests on Firebase Test Lab: After configuring Firebase Test Lab in your project, run your
tests on physical devices hosted on Google’s servers.

10.7 Continuous Integration (CI) and Continuous Delivery (CD)

CI/CD is a set of practices to automatically test and deploy applications.

Using Firebase App Distribution:

Firebase App Distribution allows you to distribute your app to testers automatically after every build.

1. Integrate Firebase App Distribution into your CI/CD pipeline.

2. Upload your APK or AAB automatically using the Firebase CLI or Firebase Console.

Using Jenkins or GitHub Actions:

You can automate the build, test, and deployment processes using Jenkins, GitHub Actions, or other
CI/CD tools.

Practical Activities:

1. Write unit tests for a basic calculator app (addition, subtraction).

2. Create a UI test for a login screen using Espresso.

3. Use Logcat to track down an error in a login function.

4. Set up breakpoints and debug an app that crashes on launch.

5. Analyze your app's memory usage and identify memory leaks using Android Profiler.

6. Test your app on multiple devices and different screen sizes using AVDs.

7. Distribute your app to testers using Firebase App Distribution.

This concludes the comprehensive course content for "Android Studio and Applications." You’ve now
covered the essential aspects of building Android apps from setup, coding, UI design, and
multimedia, to testing and debugging.

You might also like