Java Android App Development Course, Firebase Cloud Messaging

In this tutorial, we will explain in detail how to implement push notifications within an Android application using Firebase Cloud Messaging (FCM). FCM is a cloud service provided by Google that enables mobile applications to send messages to users.

1. Introduction to Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging (FCM) is a free service that allows developers to send messages between servers and client apps.
With FCM, tasks such as sending push notifications, transferring messages between devices, or sending data messages can be carried out easily.

1.1 Key Features of FCM

  • Supports push notifications for free.
  • Supports various platforms including Android, iOS, and web.
  • Allows detailed configuration for message sending.
  • Supports notification handling in the background.

2. Setting Up Firebase Project

To use FCM, you need to create a Firebase project.
Follow the steps below to set up your Firebase project.

2.1 Accessing Firebase Console

1. Go to the Firebase Console.
2. Log in with your Google account.
3. Click the “Add Project” button to create a new project.

2.2 Activating Firebase Cloud Messaging

1. In the Firebase project dashboard, select “Cloud Messaging.”
2. Verify the server key and sender ID, which will be needed for integration with the Android app later.

3. Setting Up Android Studio Project

▶ Next, we will learn how to integrate Firebase into the Android project.

3.1 Installing Android Studio

Install Android Studio and create a new project.
Set the minimum SDK version and project language to Java before starting development.

3.2 Integrating Firebase

1. In Android Studio, select the “Tools” menu and click on “Firebase.”
2. When the Firebase Assistant opens, find “Cloud Messaging” and click on “Set up Firebase Cloud Messaging.”
3. The Firebase SDK will be automatically added to your project.

3.3 Gradle Configuration

You need to add the necessary dependencies in the build.gradle (Module: app) file.


dependencies {
    implementation 'com.google.firebase:firebase-messaging:23.0.0' // Change version to the latest
}

3.4 AndroidManifest.xml Configuration

Add configurations to the Android manifest file to enable the use of FCM.


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

    <application
        ...
        >

        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>

4. Implementing FCM Message Reception

To receive FCM messages, you need to implement a class that inherits from FirebaseMessagingService.

4.1 Implementing FirebaseMessagingService

Create a class for receiving messages and override the onMessageReceived method.
This method is called when a push notification is received.


import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Code for receiving messages
        if (remoteMessage.getNotification() != null) {
            // Show notification
            showNotification(remoteMessage.getNotification().getTitle(), 
                             remoteMessage.getNotification().getBody());
        }
    }

    private void showNotification(String title, String message) {
        // Use NotificationManager to display the notification
    }
}

5. Sending Messages

Now let’s learn how to send messages from the server using FCM.
We will implement a Node.js server to send messages and learn how to handle errors in the client app.

5.1 Setting Up Node.js Server

Set up a simple server using Node.js to send messages via FCM.
First, install the necessary packages.


npm install firebase-admin

5.2 Server Code


const admin = require('firebase-admin');

// Initialize Firebase Admin SDK
admin.initializeApp({
    credential: admin.credential.applicationDefault(),
});

const fcmToken = 'YOUR_DEVICE_TOKEN'; // FCM token of the device to send the message

const message = {
    notification: {
        title: 'Hello!',
        body: 'This is a test notification.',
    },
    token: fcmToken,
};

// Sending the message
admin.messaging().send(message)
    .then((response) => {
        console.log('Successfully sent message:', response);
    })
    .catch((error) => {
        console.log('Error sending message:', error);
    });

6. Implementing Notification Display

To show the received messages to the user, display a notification.
You can create notifications using NotificationCompat.


import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

private void showNotification(String title, String message) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    String channelId = "Channel_ID";
    String channelName = "Channel_Name";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    notificationManager.notify(1, builder.build());
}

7. Testing Push Notifications

Run the server to check if the message is sent to the device with the designated FCM token.
After sending, run the Android app to verify if the notification appears.

8. Conclusion

In this tutorial, we explored how to implement push notifications in an Android app using FCM in Java.
Leveraging the powerful features of FCM can enhance communication with users.
Utilize various notification features and real-time data transmission to develop more convenient apps!

Java Android App Development Course, Understanding Firebase

Android is currently one of the most widely used mobile platforms. Developing Android apps using Java is familiar to many developers and provides intuitive and powerful features. In this course, we will take an in-depth look at Firebase, which provides essential backend services for Android app development.

1. What is Firebase?

Firebase is a mobile and web application development platform provided by Google. Developers can easily implement various features such as database, user authentication, hosting, and cloud messaging through Firebase. The main features of Firebase are as follows:

  • Real-time Database: Data is updated in real-time whenever changes occur.
  • User Authentication: Supports social media integration with Google, Facebook, Twitter, etc., as well as email/password-based authentication.
  • Hosting: Provides hosting services for static websites and SPA (Single Page Application) deployment.
  • Cloud Features: Supports various cloud features, allowing you to run apps without the need to manage server resources.

2. Getting Started with Firebase

Let’s learn how to integrate Firebase into an Android project. We will set up a Firebase project and proceed with the integration into the Android app through the steps below.

2.1 Creating a Firebase Project

  1. Access the Firebase Console (https://console.firebase.google.com/).
  2. Create a new project.
  3. Enter the project name and choose whether to enable Google Analytics.
  4. Once the project is created, select that project.

2.2 Registering the Android App

  1. Click “Add app” on the dashboard and select the “Android” icon.
  2. Enter the app’s package name. (e.g., com.example.myapp)
  3. If necessary, set the app’s app store ID and SHA-1 key.
  4. After clicking “Register app,” download the google-services.json file and add it to the app directory of your Android project.

2.3 Gradle Configuration

Add the following dependency to the project’s build.gradle file:

apply plugin: 'com.google.gms.google-services'

Add the following to the module (build.gradle) file:

dependencies {
    // Firebase SDK
    implementation 'com.google.firebase:firebase-analytics:21.0.0'
    implementation 'com.google.firebase:firebase-auth:22.0.0'
    implementation 'com.google.firebase:firebase-database:20.0.0'
}

3. Implementing Firebase Authentication

In this section, we will implement user authentication using email and password.

3.1 User Registration

import com.google.firebase.auth.FirebaseAuth;

FirebaseAuth mAuth = FirebaseAuth.getInstance();

public void registerUser(String email, String password) {
    mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, task -> {
            if (task.isSuccessful()) {
                // Registration successful
                FirebaseUser user = mAuth.getCurrentUser();
                // Navigate to main screen
            } else {
                // Registration failed
                Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
            }
        });
}

3.2 User Login

public void loginUser(String email, String password) {
    mAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, task -> {
            if (task.isSuccessful()) {
                // Login successful
                FirebaseUser user = mAuth.getCurrentUser();
                // Navigate to main screen
            } else {
                // Login failed
                Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
            }
        });
}

4. Using Firebase Realtime Database

Let’s learn how to store and retrieve data using Firebase’s real-time database.

4.1 Writing Data to the Database

DatabaseReference database = FirebaseDatabase.getInstance().getReference();

public void saveData(String userId, String name, String email) {
    User user = new User(name, email);
    database.child("users").child(userId).setValue(user)
        .addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                // Data saved successfully
            } else {
                // Failed to save data
            }
        });
}

4.2 Reading Data

public void readData(String userId) {
    database.child("users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);
            // Use the user object
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            // Failed to read data
        }
    });
}

5. Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging (FCM) is used to send push notifications. Below is how to set up FCM.

5.1 Setting Up FCM

  1. Select “Cloud Messaging” in the Firebase Console.
  2. Check the server key, which will be used later to send notifications from the server.

5.2 Adding FCM to the Android App

Add the FCM dependency to the build.gradle file:

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

5.3 Implementing FCM Receiver

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Handle the received message
        String title = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();
        sendNotification(title, message);
    }

    private void sendNotification(String title, String message) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID")
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.drawable.ic_notification);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, builder.build());
    }
}

6. Conclusion

In this course, we learned how to integrate Firebase into Android app development. Firebase offers powerful features and greatly contributes to improving developer productivity. Utilize various functions such as user authentication, data storage, and push notifications to develop outstanding apps.

We will continue to cover additional implementation examples and usage instructions, so please stay tuned for further interest.

Java Android App Development Course, Integrating with Firebase

Author: [Author Name]

Date: [Date]

1. Introduction

Firebase, which makes data storage, management, and user authentication easy and quick while developing Android apps, is loved by many developers. In this tutorial, we will learn in detail how to integrate Firebase with Android apps using Java.

2. What is Firebase?

Firebase is a mobile and web application development platform developed by Google, offering various features such as:

  • Realtime Database
  • User Authentication
  • Hosting
  • Cloud Storage
  • Push Notifications
  • Analytics

3. Setting Up a Firebase Project

To connect your Android app to Firebase, you must first create a project in the Firebase console.

  1. Log in to the Firebase console and create a new project.
  2. Enter the project name and other settings, then click “Continue”.
  3. Select whether to set up Google Analytics or not and click “Create Project”.

4. Adding an Android App

After creating your project, you need to add your Android app to the Firebase project:

  1. In the Firebase console, click the “Add App” button and select the Android icon.
  2. Enter the package name of your app (e.g., com.example.myapp).
  3. Enter your email and app nickname, then click “Register App”.
  4. Download the google-services.json file and add it to the app folder of your project.

5. Configuring Gradle

Next, open your Gradle files and add Firebase-related libraries:

build.gradle (Project level)
buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10' // Google Services plugin
    }
}

build.gradle (App level)
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // Add this line at the bottom

dependencies {
    implementation 'com.google.firebase:firebase-database:20.3.0'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
}

            

Now you have added the necessary Firebase libraries. You need to sync Gradle to reflect the changes.

6. Integrating Firebase Realtime Database

Now let’s integrate the Firebase Realtime Database.

  1. Go back to the Firebase console and click the “Database” tab.
  2. Click the “Get Started” button to create a database and set it to “Test Mode”.
  3. We will write code to read and write data within the app.

7. Writing and Reading Data Example

Here is a simple example of writing and reading data in the database:

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class MainActivity extends AppCompatActivity {

    private DatabaseReference mDatabase;

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

        // Initialize Firebase instance
        mDatabase = FirebaseDatabase.getInstance().getReference();

        // Write data to the database
        writeNewUser("user1", "James", "james@example.com");
    }

    private void writeNewUser(String userId, String name, String email) {
        User user = new User(name, email);
        mDatabase.child("users").child(userId).setValue(user);
    }
}

class User {
    public String name;
    public String email;

    public User() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }
}
            

8. Integrating Firebase User Authentication

You can also add user authentication using Firebase. Here’s an example of authentication using email/password:

import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Initialize FirebaseAuth
        mAuth = FirebaseAuth.getInstance();
    }

    private void signIn(String email, String password) {
        mAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()) {
                        // Sign-in successful
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // Sign-in failed
                        Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    }
}
            

9. Integrating Firebase Cloud Storage

Now let’s learn how to upload and download images using Firebase’s cloud storage.

import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

public class MainActivity extends AppCompatActivity {

    private StorageReference mStorageRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Initialize FirebaseStorage
        mStorageRef = FirebaseStorage.getInstance().getReference();

        // Upload image
        uploadImage();
    }

    private void uploadImage() {
        Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
        StorageReference riversRef = mStorageRef.child("images/rivers.jpg");
        riversRef.putFile(file)
            .addOnSuccessListener(new OnSuccessListener() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Upload successful
                    Log.d("Firebase", "Image uploaded successfully.");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Upload failed
                    Log.e("Firebase", "Image upload failed.");
                }
            });
    }
}
            

10. Conclusion

In this tutorial, we learned how to integrate Firebase into Android apps using Java. With Firebase, you can easily use various features such as real-time databases, user authentication, and cloud storage. Utilize Firebase in your future projects to develop more efficient and functional apps!

This article was written in accordance with [Copyright Information].

Java Android App Development Course, Firebase Storage

Data storage is a very important part of Android development. There are various ways to store app data, including local databases, file systems, and cloud databases. In this tutorial, we will discuss storage using Firebase, a cloud service provided by Google. Firebase Storage offers a convenient way to store and manage images, videos, audio files, and more. In this tutorial, we will learn how to set up Firebase Storage and how to use it in an Android app.

What is Firebase?

Firebase is a mobile development platform provided by Google that offers various features, including databases, authentication, hosting, and storage. In particular, Firebase Storage is useful for storing and managing different types of files in the cloud. By using Firebase, you can easily manage data without having to operate a backend server.

Key Features

  • Real-time database
  • Cloud storage
  • User authentication
  • Analytics tools
  • Hosting

Setting Up Firebase Storage

To use Firebase Storage, you first need to create a Firebase project and connect it to your Android app. Below are the steps to set up a Firebase project and integrate it into an Android app.

1. Create a Firebase Project

  1. Access the Firebase console: Firebase Console.
  2. Create a new project. Enter a project name and enable analytics if needed.
  3. Once the project is created, go to “Project Settings.”

2. Add Android App

  1. In the project settings page, click the “Add Application” button and select the Android icon.
  2. Enter the package name for the app (e.g., com.example.myapp).
  3. Enter the SHA-1 value of the app’s signing certificate. (Optional)
  4. After registering the app, download the provided google-services.json file and add it to the app/ directory of your Android project.

3. Configure Gradle

You need to modify the build.gradle file to use the Firebase SDK.

build.gradle (Project level)
buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10' // Update to the latest version
    }
}
build.gradle (App level)
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

dependencies {
    implementation 'com.google.firebase:firebase-storage:20.2.0' // Update to the latest version
}

Using Firebase Storage in Android App

Now that we have set up Firebase Storage, let’s learn how to upload and download files. The following example shows the code for a simple Android app that uploads and downloads images.

1. Implementing Image Upload Functionality

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1;
    private Uri imageUri;

    private ImageView imageView;
    private Button uploadButton;

    private FirebaseStorage firebaseStorage;
    private StorageReference storageReference;

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

        imageView = findViewById(R.id.image_view);
        uploadButton = findViewById(R.id.upload_button);

        firebaseStorage = FirebaseStorage.getInstance();
        storageReference = firebaseStorage.getReference("uploads");

        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadImage();
            }
        });
        
        // Open image picker
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            imageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadImage() {
        if (imageUri != null) {
            StorageReference fileReference = storageReference.child(System.currentTimeMillis() + ".jpg");
            fileReference.putFile(imageUri)
                    .addOnSuccessListener(new OnSuccessListener() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        } else {
            Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).show();
        }
    }
}

2. Implementing Image Download Functionality

Let’s add a feature to download the uploaded images. The downloading process will be done by fetching the image via its URL and displaying it in an ImageView.

private void downloadImage(String imageUrl, ImageView imageView) {
    Glide.with(this)
            .load(imageUrl)
            .into(imageView);
}

// Example call
downloadImage("https://firebasestorage.googleapis.com/v0/b/your-app-id.appspot.com/o/uploads%2Fimage.jpg?alt=media", imageView);

Handling Errors During Image Upload

You can add error handling for various errors that may occur while uploading files to show error messages to the user. In the example, we will learn how to check the rules of Firebase Storage or verify network connectivity.

private void handleUploadError(Exception e) {
    if (e instanceof StorageException) {
        StorageException storageException = (StorageException) e;
        if (storageException.getErrorCode() == StorageException.ERROR_NOT_AUTHORIZED) {
            Toast.makeText(this, "Unauthorized access", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Error uploading image", Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(this, "Network error", Toast.LENGTH_SHORT).show();
    }
}

Conclusion

In this tutorial, we learned how to set up Firebase Storage and how to upload and download files in an Android app. Firebase provides a variety of cloud-based services, making it a great help for app development. Additionally, combining Firebase with authentication and database features can lead to the development of even more powerful apps. In the next session, we will explore the database features of Firebase.

References

I hope this tutorial will be of great help in your Android app development!

Java Android App Development Course, Incorrect Object-Oriented Programming

Object-oriented programming (OOP) is a crucial concept in Android app development. This article will delve deeply into the principles of object-oriented programming, common mistakes, and how to solve these issues through Java code. This course provides useful information to help facilitate easy access to Android development. Each section includes example code for easier understanding.

1. What is Object-Oriented Programming (OOP)?

Object-oriented programming is one of the paradigms of software development that structures programs as independent units called objects, thereby modularizing the code and enhancing reusability. Java is an object-oriented language that supports OOP’s fundamental principles: encapsulation, inheritance, and polymorphism.

1.1 Fundamental Principles of OOP

  • Encapsulation: This refers to bundling an object’s properties and methods into a single unit and protecting them from external access. This helps maintain data integrity.
  • Inheritance: This is a method of defining new classes based on already defined classes. It increases code reusability and allows for extending functionality.
  • Polymorphism: This is the ability for methods with the same name to behave in various forms. It increases the flexibility of programs.

2. The Dangers of Misusing Object-Oriented Programming

Failing to adhere to the fundamental principles of OOP can lead to decreased code readability and increased maintenance difficulty. Below are common mistakes that occur in OOP:

2.1 Unnecessary Information Exposure

If variables or methods are set as public and accessible externally, the object’s state may become unstable. To avoid these problems, methods to access variables should be established, preventing direct access.

Example Code:

public class User {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }
}

2.2 Inefficient Use of Inheritance

Abusing inheritance can complicate the code and lead to hard-to-track bugs. It is advisable to inherit classes only when necessary and to prefer ‘composition’ whenever possible.

Example Code:

public class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public void start() {
        engine.start();
    }
}

public class Engine {
    public void start() {
        System.out.println("Engine started");
    }
}

2.3 Misuse of Polymorphism

When using polymorphism, it is important to understand the difference between method overloading and overriding. Moreover, the scope of polymorphism use must be clarified, as improper use can complicate the flow of code.

Example Code:

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}

class Cat extends Animal {
    void sound() {
        System.out.println("Meow");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        Animal myCat = new Cat();

        myDog.sound();
        myCat.sound();
    }
}

3. SOLID Principles of Object-Oriented Design

The SOLID principles summarize five principles aimed at improving object-oriented design. By remembering and applying these principles, better applications can be designed.

3.1 Single Responsibility Principle (SRP)

A class should have only one responsibility, and that responsibility must be completely encapsulated. This increases the reusability of the class and makes changes easier.

3.2 Open-Closed Principle (OCP)

Software elements should be open for extension but closed for modification. This allows for adding new functionalities without changing existing code.

3.3 Liskov Substitution Principle (LSP)

Objects of a parent class should be replaceable with objects of a child class. This helps maintain system stability.

3.4 Interface Segregation Principle (ISP)

Clients should not depend on methods they do not use. This prevents the obligatory implementation of unnecessary functionalities.

3.5 Dependency Inversion Principle (DIP)

High-level modules should not depend on low-level modules; both should depend on abstractions. This reduces the coupling between modules.

4. Applying OOP in Android Applications

Now, let’s examine how to apply OOP principles in Android application development. We will create a simple example using the Android Studio IDE.

4.1 Project Setup

Create a new project in Android Studio and select a basic template. Then, set up the package structure as follows:

  • com.example.myapp
  • model
  • view
  • controller

4.2 Defining the Model

Create a model class that represents the data of the application. For example, you can define a User model.

Example Code:

package model;

public class User {
    private String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

4.3 Defining the View

Create a view class that composes the user interface (UI). Utilize Android’s XML layouts to define the UI.

activity_main.xml Example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" />
</LinearLayout>

4.4 Defining the Controller

Define a controller class that manages interactions between the UI and the model. Implement this functionality in the MainActivity.java file.

Example Code:

package controller;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import model.User;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private Button button;
    private User user;

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

        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);
        user = new User("John Doe");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("Hello, " + user.getName());
            }
        });
    }
}

5. Conclusion

Object-oriented programming is a powerful paradigm essential for developing Android applications. The improper application of OOP principles can degrade code readability and maintainability; however, understanding and correctly applying OOP principles allows for the development of efficient and stable applications. This course addressed the fundamental concepts of OOP and common mistakes, and explored how to apply OOP through practical examples. Now you can develop better Android applications using Java and the principles of object-oriented programming.