Java Android App Development Course, Understanding Intents

In Android development, Intent is an essential element that enables interaction between applications. Understanding and utilizing intents is crucial for developing Android apps. In this article, we will take a detailed look at the concept of intents, their types, how to use them, example code, and more.

1. What is an Intent?

An intent is a message that requests the Android system to perform an action among components. Intents are used to start other Activities, Services, or Broadcast Receivers. They allow for data transfer and interaction within the app.

1.1. Components of an Intent

Intent intent = new Intent(context, TargetActivity.class);
  • Context: The environment information of the layer where the intent is initiated.
  • TargetActivity: The class of the Activity that will be started when the intent completes.

Intents can include optional information. You can add information using methods like:

intent.putExtra("key", "value");

2. Types of Intents

Intents in Android can be broadly classified into two types.

2.1. Explicit Intent

An explicit intent is used to start a specific component directly. It is primarily used to start another Activity within the same app.

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

2.2. Implicit Intent

An implicit intent relies on the action and data to find and execute an appropriate component. For example, a request to open a web page can be initiated as follows:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
startActivity(intent);

3. Passing Data with Intents

Data can be passed between two Activities using intents. This process consists of the following steps.

3.1. Passing Data

Data can be passed using intents in the following way:

Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("message", "Hello, SecondActivity!");
startActivity(intent);

3.2. Receiving Data

To receive the passed data, the receiving Activity can use the following code:

Intent intent = getIntent();
String message = intent.getStringExtra("message");
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

4. Flags of Intents

When using intents, flags can be set to modify the behavior of the intent. Commonly used flags include the following.

4.1. FLAG_ACTIVITY_NEW_TASK

This flag allows you to start an Activity in a new task.

Intent intent = new Intent(this, NewTaskActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

4.2. FLAG_ACTIVITY_CLEAR_TOP

Using this flag will clear all Activities above the existing Activity if it already exists and will start that Activity.

Intent intent = new Intent(this, TargetActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

5. Starting Services with Intents

Intents can also be used to start services. A service is a component that helps perform tasks in the background.

5.1. Defining and Starting a Service

Here’s how to define and start a service.

Intent intent = new Intent(this, MyService.class);
startService(intent);

5.2. Lifecycle of a Service

A service has the following lifecycle.

  • onCreate(): Called when the service is created.
  • onStartCommand(): Called when the service is started.
  • onDestroy(): Called when the service is destroyed.

6. Broadcast Receiver and Intents

A Broadcast Receiver is a component that receives events occurring from the system or applications.

6.1. Sending a Broadcast

To send a broadcast using an intent, you can do the following:

Intent intent = new Intent("com.example.CUSTOM_EVENT");
sendBroadcast(intent);

6.2. Receiving a Broadcast

A Broadcast Receiver can be defined as follows:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Broadcast received!", Toast.LENGTH_SHORT).show();
    }
}

7. Creating a Sample App using Intents

Now, let’s create a simple sample app using what you’ve learned about intents.

7.1. Package Structure

Our app will have the following package structure.

  • com.example.intentapp
  • com.example.intentapp.activities
  • com.example.intentapp.receivers

7.2. MainActivity.java

The main Activity of the Android app uses the user interface (UI) and intents to call SecondActivity.

package com.example.intentapp.activities;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("message", "Hello, SecondActivity!");
                startActivity(intent);
            }
        });
    }
}

7.3. SecondActivity.java

SecondActivity receives and displays the data sent from MainActivity.

package com.example.intentapp.activities;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        Intent intent = getIntent();
        String message = intent.getStringExtra("message");

        TextView textView = findViewById(R.id.textView);
        textView.setText(message);
    }
}

7.4. Configuring AndroidManifest.xml

Register the new Activity in AndroidManifest.xml.

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

8. Best Practices for Intents

Following some best practices while using intents can help create a more efficient app.

  • Use explicit intents whenever possible. Implicit intents can impact performance.
  • When passing data with intents, use appropriate data types. Parcelable objects are recommended over strings.
  • Minimize the size of the data passed through intents.

9. Conclusion

Intents are a key concept in Android apps, enabling interaction and data transfer between applications. In this article, we explored the fundamental concepts of intents, their types, methods of data transfer, and their relationship with services and broadcast receivers. Based on this foundational knowledge, you can develop various Android apps.

Utilize intents in your future Android app development to add more features and create apps that provide an enhanced user experience. I hope you continue to improve your skills through various practices using intents!

Java Android App Development Course, Image Processing – Glide Library

Image processing is an essential part of Android app development. In particular, the Glide library plays a significant role in efficiently loading and displaying images of various resolutions. In this tutorial, we will learn how to load and cache images using the Glide library.

1. Overview of the Glide Library

Glide is an image loading and caching library developed by Google, capable of fetching images from complex URLs or loading images from the local file system. Glide provides powerful capabilities to handle edge cases and various image formats, making it very useful in image processing applications.

2. Setting Up Glide

To use Glide, you first need to add the library to your Gradle file. Open the build.gradle file of your project in Android Studio and add the following dependencies.

dependencies {
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
}

After adding the above content, synchronize the Gradle file to include the Glide library in your project.

3. Basic Usage of Glide

The usage of Glide is very simple. By default, you can load an image into an ImageView like this.

import com.bumptech.glide.Glide;

ImageView imageView = findViewById(R.id.imageView);
Glide.with(this)
     .load("https://example.com/image.jpg")
     .into(imageView);

In the above code, Glide.with(this) retrieves the context of the current activity, and the .load() method is used to fetch the image. Finally, the .into() method is used to set the image into the ImageView.

4. Image Loading Options in Glide

Glide offers various image loading options. Here are some common options used frequently.

4.1. Resizing Images

You can resize the image to your desired dimensions while loading. The example below shows how to load an image resized to 100×100 pixels.

Glide.with(this)
     .load("https://example.com/image.jpg")
     .override(100, 100)
     .into(imageView);

4.2. Setting Placeholder and Error Images

You can set a placeholder image to display while the image is loading or an error image to show in case of a loading failure.

Glide.with(this)
     .load("https://example.com/image.jpg")
     .placeholder(R.drawable.placeholder)
     .error(R.drawable.error)
     .into(imageView);

4.3. Creating Circular Images

If you want to create a circular image using Glide, refer to the following example.

import com.bumptech.glide.load.resource.bitmap.CircleCrop;

Glide.with(this)
     .load("https://example.com/profile.jpg")
     .transform(new CircleCrop())
     .into(imageView);

5. Caching Mechanism of Glide

Glide automatically performs caching when loading images. It uses both memory and disk caching to optimize performance.

5.1. Memory Cache

Memory cache helps the application quickly access images within the range of memory. This reduces the response time while loading images.

5.2. Disk Cache

Disk cache allows images to be saved on the device’s storage media, enabling faster loading for subsequent identical requests. This helps reduce data usage and improve performance.

6. Advanced Features of Glide

In addition to basic image loading, Glide provides various advanced features. Here are a few of them.

6.1. GIF Support

Glide allows you to easily load GIF images. The code below demonstrates how to set a GIF image in an ImageView.

Glide.with(this)
     .asGif()
     .load("https://example.com/animation.gif")
     .into(imageView);

6.2. Implementing a Progress Bar

You can display a progress bar while the image is loading using Glide. The RequestListener of Glide can be used to handle loading states.

Glide.with(this)
     .load("https://example.com/image.jpg")
     .listener(new RequestListener() {
         @Override
         public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
             // Handle load failure
             return false;
         }

         @Override
         public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
             // Handle successful image load
             return false;
         }
     })
     .into(imageView);

6.3. Parameter Tuning

Glide provides capabilities to manage images more precisely using additional parameters. For example, you can preprocess each image before loading them.

Glide.with(this)
     .load("https://example.com/image.jpg")
     .apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 3)))
     .into(imageView);

Conclusion

Glide is an excellent tool that makes image processing simple and efficient in Android applications. By utilizing memory and disk cache options, you can improve the overall performance of your app, while supporting various image formats and transformation features. We hope you learned how to use Glide through this tutorial and can apply it to your apps.

Additionally, you can find the documentation for Glide here.

Java Android App Development Course, Using Authentication Features

In Android application development, the authentication feature is very important for protecting user information and data security. In this course, we will cover how to implement the authentication feature. We will explain step by step from basic concepts to actual code.

1. Understanding Authentication Feature

The authentication feature is the process of verifying who the user is. It is generally implemented through a username and password. However, nowadays various methods such as social login, biometrics, and two-factor authentication are being used. In Java Android apps, it can be implemented more easily through external libraries such as Firebase Authentication.

2. Setting Up the Project

Open Android Studio and create a new project. Follow the steps below:

  1. Open Android Studio and click “New Project”.
  2. Select Empty Activity and click Next.
  3. Enter the project name and package name. For example: com.example.authenticationdemo.
  4. Select Java as the language and click Finish.

3. Setting Up Firebase

Firebase is Google’s cloud service that makes it easy to implement authentication features. To set up a Firebase project, follow these steps:

  1. Log in to the Firebase console (https://console.firebase.google.com/).
  2. Add a new project.
  3. In the project settings, click the Android icon to register the Android app.
  4. Enter the package name and click “Add App”.
  5. Download the google-services.json file and add it to the app folder.
  6. Add the Google services plugin to your project’s build.gradle file.
  7. buildscript {
        dependencies {
            classpath 'com.google.gms:google-services:4.3.10' // Make sure to update to the latest version
        }
    }
    
    allprojects {
        repositories {
            google()
            mavenCentral()
        }
    }
            
  8. Add the Firebase Authentication library to the app’s build.gradle file.
  9. apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'
    
    dependencies {
        implementation 'com.google.firebase:firebase-auth:21.0.6' // Make sure to update to the latest version
    }
            

4. Designing the Layout

To implement the authentication feature, you need to design the user interface (UI). Modify the res/layout/activity_main.xml file to create a UI like the following:

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

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Email"/>

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Password"
        android:inputType="textPassword"/>

    <Button
        android:id="@+id/buttonSignIn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Log In"/>

    <Button
        android:id="@+id/buttonSignUp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Sign Up"/>
    
</LinearLayout>
    

5. Implementing the Authentication Logic

Now, let’s implement the actual authentication logic. Open the MainActivity.java file and add the following code.

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

    private EditText editTextEmail;
    private EditText editTextPassword;
    private Button buttonSignIn;
    private Button buttonSignUp;

    private FirebaseAuth mAuth;

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

        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword = findViewById(R.id.editTextPassword);
        buttonSignIn = findViewById(R.id.buttonSignIn);
        buttonSignUp = findViewById(R.id.buttonSignUp);

        mAuth = FirebaseAuth.getInstance();

        buttonSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn(editTextEmail.getText().toString(), editTextPassword.getText().toString());
            }
        });

        buttonSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createAccount(editTextEmail.getText().toString(), editTextPassword.getText().toString());
            }
        });
    }

    private void signIn(String email, String password) {
        mAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    FirebaseUser user = mAuth.getCurrentUser();
                    Toast.makeText(MainActivity.this, "Login successful: " + user.getEmail(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Login failed.", Toast.LENGTH_SHORT).show();
                }
            });
    }

    private void createAccount(String email, String password) {
        mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    FirebaseUser user = mAuth.getCurrentUser();
                    Toast.makeText(MainActivity.this, "Registration successful: " + user.getEmail(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Registration failed.", Toast.LENGTH_SHORT).show();
                }
            });
    }
}
    

6. Running and Testing the App

After adding all the code, run the app to test if the functionality works well. Check if both login and sign-up functions work properly. It is also important to provide appropriate feedback to users and handle errors when they occur.

7. Implementing Additional Features

After building the basic sign-up and login functions, you can consider additional features like:

  • Email Verification: Set up email verification after registration to enhance security.
  • Password Reset: Add a feature that allows users to reset their password if they forget it.
  • Social Login: Implement authentication using social accounts like Google and Facebook.
  • User Profile Management: Add functionality to modify and view user profiles after authentication.

8. Conclusion

In this course, we learned how to implement authentication features in Android apps using Java. We were able to easily apply email/password-based login and registration functions through the Firebase Authentication library. Consider using various authentication methods to enhance the security of your application.

9. References

Java Android App Development Course, Creating an Image Sharing App

Today, we will learn how to create an image sharing app in an Android environment using Java.
This course is for those who have a basic understanding of Android application development.
We will proceed step by step from project setup using Gradle, UI design, to implementing image selection and sharing features.

1. Setting Up the Development Environment

To start the project, you need to install Android Studio.
Android Studio is the official IDE for Android application development and offers various features.
Here’s how to create a project after installing Android Studio.

  1. Open Android Studio and select “New Project”.
  2. Select “Empty Activity” as the template and click the “Next” button.
  3. Set the project name to “ImageSharingApp” and configure the package name and save location as needed.
  4. Select “Java” for the Language and click “Finish” to create the project.

2. UI Configuration

Now let’s configure the user interface of the app.
We will create a simple UI that allows users to select and share images.

2.1 Modifying the Layout File

First, open the res/layout/activity_main.xml file and modify it as follows.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button_select_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select Image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"/>

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_below="@id/button_select_image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:scaleType="centerCrop"/>

    <Button
        android:id="@+id/button_share"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share"
        android:layout_below="@id/image_view"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"/>

</RelativeLayout>

3. Implementing Image Selection Functionality

Let’s add functionality for users to select images in the app.
To do this, we will use an image selection intent.
Open the MainActivity.java file and add the following code.

public class MainActivity extends AppCompatActivity {
    private static final int PICK_IMAGE_REQUEST = 1;

    private ImageView imageView;
    private Button buttonSelectImage, buttonShare;

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

        imageView = findViewById(R.id.image_view);
        buttonSelectImage = findViewById(R.id.button_select_image);
        buttonShare = findViewById(R.id.button_share);

        buttonSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openFileChooser();
            }
        });
    }

    private void openFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Choose an 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) {
            Uri imageUri = data.getData();
            imageView.setImageURI(imageUri);
        }
    }
}

4. Implementing Image Sharing Functionality

Now it’s time to add a feature that allows users to share the selected image with other apps.
We will add code for the sharing functionality to MainActivity.java.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ... keep the existing code

        buttonShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareImage();
            }
        });
    }

    private void shareImage() {
        imageView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
        imageView.setDrawingCacheEnabled(false);

        String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Title", "Description");
        Uri uri = Uri.parse(path);

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        shareIntent.setType("image/jpeg");
        startActivity(Intent.createChooser(shareIntent, "Share the image"));
    }

5. Adding Required Permissions

To use the sharing functionality, storage permissions are required.
Add the following permission to the AndroidManifest.xml file.

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

6. Completion and Testing

All implementations are completed.
Now we will test the app to ensure that the image selection and sharing functionalities work correctly.
Click the “Run” button in Android Studio to run the app on an emulator or a real device.

If the app is working correctly, the user can click the “Select Image” button to choose an image, and
click the “Share” button to share the selected image with other apps.

7. Conclusion

Through this tutorial, we learned how to implement image selection and sharing functionality in an Android app using Java.
This feature provides a useful experience for users and is an important element in creating practical apps.
In the future, adding additional features or improving the UI of this app will also be good learning opportunities.

Thank you! In the next tutorial, we will create an app that can be used in real situations by adding even more diverse features.

Java Android App Development Course, Using the App Bar

1. What is AppBar?

AppBar is an essential component that makes up the basic user interface in Android apps. It is typically positioned at the top of the screen, displaying the title of the current screen and providing users with tools to access the app’s main features.
The AppBar in Android is implemented through the Toolbar class. It can include various buttons, logos, menu icons, and more, playing a significant role in enhancing user experience.

2. Basic Components of AppBar

AppBar consists of several components:

  • Title: Displays the title of the current screen.
  • Navigation Icon: An icon that helps users return to the previous screen.
  • Menu Items: Icons that provide additional features.
  • Action Buttons: Buttons that provide frequently used functionalities.

3. Implementing AppBar

This section explains how to actually implement an AppBar. First, create a new project in Android Studio and set up a basic layout for the AppBar.

3.1 Create a New Android Project

1. Open Android Studio and select “New Project”.
2. Select “Empty Activity” and enter the project name.
3. Choose Java as the language and click “Finish”.

3.2 Modify build.gradle File

There is no need to add `Toolbar` in the `build.gradle` file to use AppBar. The AndroidX library is included by default, so just ensure that the required SDK version is checked.

3.3 Modify activity_main.xml

Next, add the AppBar in the `activity_main.xml` file. Refer to the code below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!"
        android:layout_below="@id/toolbar"
        android:layout_centerInParent="true" />

</RelativeLayout>

3.4 Write Code in MainActivity.java

Next, add the code related to the AppBar in the MainActivity.java file. Refer to the example below:

package com.example.myapplication;

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

public class MainActivity extends AppCompatActivity {

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

        // Setting up the toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("AppBar Example");
    }
}

4. Adding Menu Items

The next step is to add menu items to the AppBar. First, create a menu resource file.

4.1 Create Menu Resource File

1. Right-click the res/menu folder and select “New” > “Menu Resource File”.
2. Name the file `menu_main.xml` and click “OK”.

4.2 Modify menu_main.xml File

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/action_settings"
        android:title="Settings"
        android:orderInCategory="100"
        android:showAsAction="never" />

</menu>

4.3 Add Menu to MainActivity.java

Override the `onCreateOptionsMenu` method to add the newly created menu to the AppBar.

import android.view.Menu;
import android.view.MenuItem;

// Add to MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        // Action when settings item is clicked
        return true;
    }

    return super.onOptionsItemSelected(item);
}

5. Adding Icons to AppBar

Next, we will add icons to the AppBar so that users can access more features. This section explains how to add and configure icons.

5.1 Add Icon to drawable Folder

Add the icon image to the res/drawable folder.
For example, create a file named `ic_settings.xml` and set it up as follows:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,16.5c-1.33,0 -2.48,0.51 -3.41,1.41l-1.59,-1.59c-2.5,2.5 -2.5,6.57 0,9.08s6.57,2.5 9.08,0s2.5,-6.57 0,-9.08l-1.59,1.59C14.48,17.01,13.33,16.5,12,16.5z M12,8.5c1.33,0 2.48,-0.51 3.41,-1.41l1.59,1.59c2.5,-2.5 2.5,-6.57 0,-9.08s-6.57,-2.5 -9.08,0 -2.5,6.57 0,9.08l1.59,-1.59C9.52,8.99,10.67,8.5,12,8.5z"/>
</vector>

5.2 Add Icon to Menu Item

<item
    android:id="@+id/action_settings"
    android:title="Settings"
    android:icon="@drawable/ic_settings"
    android:orderInCategory="100"
    android:showAsAction="ifRoom" />

6. Design and Customizing the AppBar

The AppBar provides default design, but it can be customized as needed.
The following section discusses how to modify the style of the AppBar and additional customization options.

6.1 Modify AppBar Style in styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">#3F51B5</item>
    <item name="colorPrimaryDark">#303F9F</item>
    <item name="colorAccent">#FF4081</item>
    </style>

6.2 Change Colors

To change colors and styles, define colors in res/values/colors.xml and use them in
styles.xml. You can modify the color codes appropriately to change them.

7. Conclusion

Through this tutorial, you learned about the role and implementation of the AppBar in Android app development using Java.
The AppBar is an essential component of the app, providing users with an intuitive interface that enhances their experience.
By customizing the AppBar in various ways, you can improve the overall style and functionality of your app.
Now you have the ability to integrate the AppBar into your app to provide a variety of features.
Continue to practice and add various functionalities to create a more advanced app!