Java Android App Development Course, Drawer Layout – Screen Composition that Opens from the Side

In Android app development, the Drawer Layout is a UI component that allows users to pull out a hidden menu from the side of the screen. This enables a more intuitive implementation of app navigation. In this tutorial, we will explain the concept of the Drawer Layout and how to implement it in detail.

What is Drawer Layout?

Drawer Layout is one of the layouts in Android that allows users to swipe from the left or right of the screen to open a menu. It is typically used to provide a navigation menu, helping users easily navigate to the main functions or sections of the app.

Advantages of Drawer Layout

  • Space-saving: It allows efficient use of limited screen space.
  • Relatively easy implementation: The Drawer Layout can be easily implemented in the Android SDK.
  • Consistent user experience: Commonly used in Android apps, it provides a familiar interface for users.

Steps to Implement Drawer Layout

1. Create a Project

Create a new project using Android Studio, selecting ‘Empty Activity’ as the project template.

2. Add Gradle Dependencies

Next, check the dependencies needed to use the Drawer Layout. It is usually included by default in the Android SDK, but if you want to add the latest library, you can add the following dependency in the build.gradle file.

implementation 'androidx.drawerlayout:drawerlayout:1.1.1'

3. Create Layout File

Now, open the activity_main.xml file and add the Drawer Layout. Refer to the example code below to create the basic structure.

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Main Content"
            android:layout_gravity="center"/>
    
    </FrameLayout>

    <NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/drawer_menu"/>

</androidx.drawerlayout.widget.DrawerLayout>

4. Create Menu File

To create a menu for the Drawer Layout, create a drawer_menu.xml file in the res/menu directory. This file will define the Drawer menu items.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/nav_home"
        android:title="Home"/>
    <item
        android:id="@+id/nav_profile"
        android:title="Profile"/>
    <item
        android:id="@+id/nav_settings"
        android:title="Settings"/>
</menu>

5. Configure MainActivity

Now, set up the Drawer Layout in the MainActivity.java file. Define the click event for opening the menu and the actions when menu items are selected.

import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;

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

        drawerLayout = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_home:
                        // Handle home click
                        break;
                    case R.id.nav_profile:
                        // Handle profile click
                        break;
                    case R.id.nav_settings:
                        // Handle settings click
                        break;
                }
                drawerLayout.closeDrawers(); // Close drawer
                return true;
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawers();
        } else {
            super.onBackPressed();
        }
    }
}

Customizing Drawer Layout

There are several ways to customize the design or behavior of the Drawer Layout. Let’s look at a few methods below.

1. Adding a Drawer Icon

You can add an icon to open the drawer and set it to open when the user clicks that icon.

import androidx.appcompat.widget.Toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ... existing code omitted ...
    
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawerLayout.addDrawerListener(toggle);
    toggle.syncState();
}

2. Changing Drawer Design

The design of the drawer can be easily changed through XML files and styles. You can modify colors, fonts, and background images to harmonize with the overall theme of the app.

<NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/nav_header"
    app:menu="@menu/drawer_menu"
    app:background="@color/colorAccent"/>

3. Adding Submenus to Drawer Menu Items

You can also add submenus to provide more navigation options. Manage submenus by adding them in the drawer_menu.xml file.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:title="Home"/>
        <item
            android:id="@+id/nav_profile"
            android:title="Profile">
            <menu>
                <item android:id="@+id/nav_profile_info" android:title="Info"/>
                <item android:id="@+id/nav_profile_settings" android:title="Settings"/>
            </menu>
        </item>
    </group>
</menu>

Other Tips and Precautions

There are a few things to keep in mind while using the Drawer Layout.

  • Swipe Actions: When the drawer is open, swipe actions may overlap. In such cases, event handling should be implemented to improve the user experience.
  • Layout Changes Based on Screen Size: You should consider various layouts to ensure the app functions correctly on different devices.
  • Navigation Type: You need to determine the most suitable navigation pattern that can be used alongside the drawer, taking the user’s experience into account.

Conclusion

The Drawer Layout is a very useful UI component in Android apps. When used properly, it can provide users with an intuitive navigation experience. Through this tutorial, you learned the basic usage and customization methods of the Drawer Layout. Utilize the Drawer Layout in various ways to develop attractive and user-friendly apps.

Java Android App Development Course, Storing in a Database

Data storage is an essential element in Android application development. Various storage methods can be used to securely store user data, but among them, databases are the most commonly used. In this article, we will explore in detail how to create an SQLite database using Java in Android and perform CRUD (Create, Read, Update, Delete) operations on the data.

1. What is a Database?

A database is a system for storing and managing information in an organized manner. In Android, SQLite, a relational database, is primarily used. SQLite is a lightweight database suitable for small applications, operating as a file-based system that can be easily used without a separate server.

2. Setting Up SQLite Database

After creating an Android project, you need to set up the SQLite database. It is common to write a helper class to create and manage the database.

package com.example.myapp.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "myApp.db";
    public static final String TABLE_NAME = "users";
    
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_EMAIL = "email";

    private static final String TABLE_CREATE =
            "CREATE TABLE " + TABLE_NAME + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_NAME + " TEXT, " +
            COLUMN_EMAIL + " TEXT);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}

3. Inserting Data

To add data to the database, use the SQLiteDatabase object to call the insert() method. The example below shows how to add user information to the database.

package com.example.myapp.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public class UserRepository {
    private DatabaseHelper dbHelper;

    public UserRepository(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    public void addUser(String name, String email) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_NAME, name);
        values.put(DatabaseHelper.COLUMN_EMAIL, email);

        db.insert(DatabaseHelper.TABLE_NAME, null, values);
        db.close();
    }
}

4. Retrieving Data

To retrieve stored data, use the query() method. This method returns a Cursor object, through which you can access the data.

package com.example.myapp.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class UserRepository {
    // ... (existing code)

    public List getAllUsers() {
        List users = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        
        Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, null, null, null, null, null, null);
        
        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                user.setId(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID)));
                user.setName(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_EMAIL)));
                users.add(user);
            } while (cursor.moveToNext());
        }
        
        cursor.close();
        db.close();
        return users;
    }
}

5. Updating Data

To update existing data, use the update() method. The example below shows how to change a specific user’s email.

package com.example.myapp.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public class UserRepository {
    // ... (existing code)

    public void updateUser(int id, String email) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_EMAIL, email);

        db.update(DatabaseHelper.TABLE_NAME, values, DatabaseHelper.COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
        db.close();
    }
}

6. Deleting Data

To delete specific data, use the delete() method. The example below explains how to delete a specific user’s data.

package com.example.myapp.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public class UserRepository {
    // ... (existing code)

    public void deleteUser(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper.COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
        db.close();
    }
}

7. Complete Code Example

The complete example, which includes all the methods above, can be compiled as follows.

package com.example.myapp.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class UserRepository {
    private DatabaseHelper dbHelper;

    public UserRepository(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    public void addUser(String name, String email) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_NAME, name);
        values.put(DatabaseHelper.COLUMN_EMAIL, email);

        db.insert(DatabaseHelper.TABLE_NAME, null, values);
        db.close();
    }

    public List getAllUsers() {
        List users = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        
        Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, null, null, null, null, null, null);
        
        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                user.setId(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID)));
                user.setName(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_EMAIL)));
                users.add(user);
            } while (cursor.moveToNext());
        }
        
        cursor.close();
        db.close();
        return users;
    }

    public void updateUser(int id, String email) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_EMAIL, email);

        db.update(DatabaseHelper.TABLE_NAME, values, DatabaseHelper.COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
        db.close();
    }

    public void deleteUser(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper.COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
        db.close();
    }
}

8. Summary and Conclusion

In this tutorial, we learned how to perform basic CRUD operations using the SQLite database in Android. Databases play an essential role in managing data within applications, and SQLite is particularly widely used in the Android environment. If a more complex data storage solution is required, considering the Room Persistence Library is also an option. Room provides an abstraction layer over the SQLite database, making database operations easier.

9. Additional Resources and Reference Links

Java Android App Development Course, Various Dialogs

Dialogs in Android are powerful tools for interacting with users. They are used for various purposes such as alert messages, user input, selections, and displaying information. This article provides a detailed explanation of the concept and implementation of different types of dialogs, along with example code. Through this tutorial, you can learn the skills to effectively use dialogs in Android apps.

What is a Dialog?

A dialog is a small window for interaction with the user. It serves the purpose of providing or confirming necessary information to the user without interfering with the main UI of the app. Android provides several types of dialogs, which can improve user experience.

Types of Dialogs

Dialogs provided by Android can be broadly classified as follows:

  • AlertDialog: A common dialog used for various purposes such as alerts and information provision.
  • ProgressDialog: A dialog that shows the status of a process to the user during ongoing tasks (Note: This class is currently deprecated).
  • DatePickerDialog: A dialog for selecting dates.
  • TimePickerDialog: A dialog for selecting times.
  • Custom Dialog: A dialog with a user-defined UI.

1. AlertDialog

AlertDialog is the most common type of dialog that requests user selection or provides information. Below is a basic implementation example of AlertDialog.

import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Notification");
        builder.setMessage("This is the dialog message.");
        
        // Positive button
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Handle positive button click
            }
        });
       
        // Negative button
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Handle negative button click
            }
        });
        
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

Description: In the above code, AlertDialog.Builder is used to create the dialog. The dialog’s title and message are set, and positive and negative buttons are added. The actions upon button clicks are defined in the internal listeners.

2. ProgressDialog

Note: ProgressDialog is no longer recommended, so it is better to use alternative UI elements. For example, you can combine ProgressBar with DialogFragment to implement similar functionality.

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

public class MainActivity extends AppCompatActivity {

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

    private void showProgressDialog() {
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Loading");
        progressDialog.setMessage("Loading data...");
        progressDialog.setCancelable(false); // Not cancelable
      
        progressDialog.show();

        // Dismiss the dialog after 2 seconds
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                progressDialog.dismiss();
            }
        }, 2000);
    }
}

Description: The above code creates a ProgressDialog that is set to close after 2 seconds. It can visually indicate the loading status to the user.

3. DatePickerDialog

DatePickerDialog is a dialog that helps users select a date. The following example shows the basic usage of DatePickerDialog.

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.widget.DatePicker;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

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

    private void showDatePickerDialog() {
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                // Handle selected date
            }
        }, year, month, day);
        
        datePickerDialog.show();
    }
}

Description: The selected date in DatePickerDialog can be handled in the onDateSet method. When the user selects a date, the selected year, month, and day are passed as parameters.

4. TimePickerDialog

TimePickerDialog helps users select a time. The following code is a basic implementation example of TimePickerDialog.

import android.app.TimePickerDialog;
import android.os.Bundle;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

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

    private void showTimePickerDialog() {
        final Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                // Handle selected time
            }
        }, hour, minute, true);
        
        timePickerDialog.show();
    }
}

Description: The time selected by the user in TimePickerDialog is handled in the onTimeSet method, which receives the hour and minute values as parameters.

5. Custom Dialog

A Custom Dialog has a user-defined UI. You can create a dialog in your desired format using an XML layout. Below is an example of a Custom Dialog.

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

public class MainActivity extends AppCompatActivity {

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

    private void showCustomDialog() {
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.custom_dialog);
        
        TextView dialogText = dialog.findViewById(R.id.dialog_text);
        Button dialogButton = dialog.findViewById(R.id.dialog_button);
        
        dialogText.setText("This is a custom dialog.");
        
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        
        dialog.show();
    }
}

Description: In the above example, custom_dialog.xml is the layout file defined by the user. The layout of the dialog is defined in XML and a dialog is created using the Dialog class.

custom_dialog.xml




    

    


Various Attributes of Dialogs

Dialogs can be adjusted with various attributes to improve user experience. Here are some attributes that can be set on a dialog:

  • Cancelable: You can allow the user to close the dialog by touching outside or pressing the ‘Back’ button.
  • Gravity: You can adjust the dialog’s position to be displayed at a specific spot on the screen.
  • Theme: You can change the dialog’s theme to match the design of the app.

Conclusion

In this tutorial, we learned how to create various types of dialogs in Android app development using Java. Dialogs play an important role in improving interaction with users and effectively conveying information. By learning the implementation of AlertDialog, ProgressDialog, DatePickerDialog, TimePickerDialog, and Custom Dialog, you can choose and use appropriate dialogs as needed. We hope you can create more attractive and user-friendly Android apps by utilizing these dialogs.

Additional Resources

You can find more information related to dialogs in the official Android developer documentation. Referring to the resources to create your own dialogs can also be a good experience.

Java Android App Development Course, Creating a News App

Hello! Today we will embark on an exciting journey to develop an Android app. In this tutorial, we will explain the step-by-step process of creating a simple news app using Java. I hope you gain a deep understanding of app development and learn useful skills through this course.

1. App Planning and Requirements Analysis

Before creating the news app, we will first outline the main features and requirements of the app. Here is a list of basic requirements:

  • Display a list of news articles.
  • Each news item should be clickable.
  • Detailed content of the news should be viewable.
  • News articles will be retrieved from the internet via an API.

2. Setting Up the Development Environment

To develop the app, you must first download and install Android Studio. Android Studio is the official Android IDE and offers various features. Follow the steps below to set up the environment:

  1. Download and install Android Studio from the official website.
  2. After installation, create a new project.
  3. Select ‘Empty Activity’ from the project template.
  4. Name the project ‘NewsApp’ and choose ‘Java’ as the language.
  5. Once the project is created, navigate to the ‘app/src/main’ directory in the file explorer on the left.

3. Choosing an API

There are several news APIs available to fetch news data. We will use the ‘News API’ to retrieve data. To use the news API, you will need an API key. Follow the steps below:

  1. Sign up at the News API website.
  2. Generate an API key.
  3. Store the API key securely.

4. Adding Dependencies

In Android Studio, you can easily add dependencies using Gradle. We will be using the ‘Retrofit’ and ‘Gson’ libraries to access the news API. Please add the following code to the ‘build.gradle (Module: app)’ file:


dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
        

5. Creating the Model Class

To handle news data, it is necessary to define a model class. We will create a class named ‘Article’. Create a ‘model’ package under the ‘java’ directory of your project and create an ‘Article.java’ class inside it.


package com.example.newsapp.model;

public class Article {
    private String title;
    private String description;
    private String url;
    private String urlToImage;

    // Getters and Setters
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrlToImage() {
        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }
}
        

6. Configuring Retrofit

To communicate with the API using Retrofit, you need to create a Service class. Create a package called ‘api’ and create a ‘NewsApiService.java’ file inside it.


package com.example.newsapp.api;

import com.example.newsapp.model.Article;
import com.example.newsapp.model.NewsResponse;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface NewsApiService {
    @GET("top-headlines")
    Call getTopHeadlines(
            @Query("apiKey") String apiKey,
            @Query("country") String country
    );
}
        

7. Creating the News Response Model

To map the JSON data returned by the API, you need to create a class called ‘NewsResponse’. Create a ‘NewsResponse.java’ class inside the previously created ‘model’ package.


package com.example.newsapp.model;

import java.util.List;

public class NewsResponse {
    private String status;
    private List
articles; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List
getArticles() { return articles; } public void setArticles(List
articles) { this.articles = articles; } }

8. Implementing MainActivity

Now we are ready to implement MainActivity to fetch news from the API and display it to the user. Open the ‘MainActivity.java’ file and write the following code.


package com.example.newsapp;

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

import com.example.newsapp.api.NewsApiService;
import com.example.newsapp.model.NewsResponse;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    private static final String BASE_URL = "https://newsapi.org/v2/";
    private static final String API_KEY = "YOUR_API_KEY"; // Enter your API key here

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

        loadNews();
    }

    private void loadNews() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        NewsApiService newsApiService = retrofit.create(NewsApiService.class);
        Call call = newsApiService.getTopHeadlines(API_KEY, "kr");
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    // Process news data
                } else {
                    Toast.makeText(MainActivity.this, "Failed to fetch news.", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Toast.makeText(MainActivity.this, "Network error: " + t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
}
        

9. Displaying the News List

We will use RecyclerView to display the list of news articles. Create a layout file named ‘item_article.xml’ in the ‘res/layout’ folder and write the following code.





    

    

        

10. Creating a RecyclerView Adapter

To use RecyclerView, you need to write an adapter class. Create a package called ‘adapter’ and create an ‘ArticleAdapter.java’ file.


package com.example.newsapp.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.newsapp.R;
import com.example.newsapp.model.Article;
import java.util.List;

public class ArticleAdapter extends RecyclerView.Adapter {
    private List
articleList; static class ArticleViewHolder extends RecyclerView.ViewHolder { TextView textTitle; TextView textDescription; ArticleViewHolder(View itemView) { super(itemView); textTitle = itemView.findViewById(R.id.textTitle); textDescription = itemView.findViewById(R.id.textDescription); } } public ArticleAdapter(List
articleList) { this.articleList = articleList; } @NonNull @Override public ArticleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article, parent, false); return new ArticleViewHolder(view); } @Override public void onBindViewHolder(@NonNull ArticleViewHolder holder, int position) { Article article = articleList.get(position); holder.textTitle.setText(article.getTitle()); holder.textDescription.setText(article.getDescription()); } @Override public int getItemCount() { return articleList.size(); } }

11. Initializing RecyclerView and Setting Data

Initialize the RecyclerView in MainActivity and set the data retrieved from the API to the adapter. Modify ‘MainActivity.java’ and update it as follows.


import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

private RecyclerView recyclerView;
private ArticleAdapter articleAdapter;

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

    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    loadNews();
}

private void loadNews() {
    ...
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if (response.isSuccessful()) {
                articleAdapter = new ArticleAdapter(response.body().getArticles());
                recyclerView.setAdapter(articleAdapter);
            } else {
                ...
            }
        }
        ...
    });
}
        

12. Modifying the MainActivity Layout File

Finally, modify the layout file for MainActivity to add the RecyclerView. Modify the ‘res/layout/activity_main.xml’ file to write the following code.





    

        

13. Trying It Out and Conclusion

Now all settings are complete! When you run the app, you can view the latest news articles in a list. A simple news app that provides useful information to users through data retrieved from the API is now complete.

14. Implementing Additional Features

In this tutorial, we learned the process of creating a basic news app. Furthermore, try implementing additional features such as:

  • Implementing a news detail page
  • Adding a news article search function
  • Adding a favorites feature
  • Adding various news categories

15. Conclusion

By creating a news app, you were able to learn the basic usage of Java and Android. I hope you continue to develop more apps and improve your skills. If you have any questions or comments, please leave them in the comments!

Java Android App Development Course, Navigation View – Drawer Screen Configuration

Author: [Author Name]

Date: [Date]

1. Introduction

In Android app development, the Navigation View is an important UI component that helps users navigate efficiently between different screens within the app. In this tutorial, we will detail how to set up the Navigation View for an Android app using Java. We will also explore how to implement user-friendly navigation by configuring a Drawer Layout with real examples.

2. What is a Navigation View?

The Navigation View is typically a menu that is hidden on the left or right side of the screen, which appears in a sliding manner when a user clicks on a specific icon (hamburger icon). Users can easily navigate to various sections of the app through this Navigation View. According to Google’s Material Design guidelines, the Navigation View plays an important role in enhancing app usability.

3. Project Setup

To implement the Navigation View, create a new Android project. Open Android Studio and follow these steps:

  1. Create a new project: Select “Empty Activity”
  2. Specify the name, package name, and project location
  3. Select “Java” as the language and click “Finish”

After creating the project, modify the build.gradle file to add the necessary libraries and dependencies. The Navigation View requires the following dependency:

implementation 'com.google.android.material:material:1.5.0'

4. Layout Configuration

To set up the Navigation View and Drawer Layout, modify the activity_main.xml file. Use DrawerLayout as the base layout to create a structure that includes the Navigation View. Below is an example of a basic layout configuration.

<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Main content goes here -->

    </FrameLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/drawer_menu" 
        app:headerLayout="@layout/nav_header">
    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

5. Defining Menu Resources

To define the menu to be displayed in the Navigation View, create a new XML file inside the res/menu folder. Add items to the menu XML file (e.g., drawer_menu.xml) to set up the navigation menu.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/nav_home"
        android:title="Home" />
    <item
        android:id="@+id/nav_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:title="Slideshow" />
</menu>

6. Utilizing the Navigation View

Modify the MainActivity.java file to handle item selections from the Navigation View. You can define specific actions for each navigation menu item when a user selects them.

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private NavigationView navigationView;

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

        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();
                switch (id) {
                    case R.id.nav_home:
                        // Action when home item is selected
                        break;
                    case R.id.nav_gallery:
                        // Action when gallery item is selected
                        break;
                    case R.id.nav_slideshow:
                        // Action when slideshow item is selected
                        break;
                }
                drawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
        });
    }
}

7. Improving User Interface

The Navigation View can be configured using a menu and header view by default. You can provide a personalized experience for users by adding a header view. By adding the nav_header.xml file, you can display user information or provide links.

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

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:src="@drawable/header_image" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="User Name"
        android:textColor="@android:color/black" />

</LinearLayout>

8. Drawer Opening and Closing Animations

The animation for opening the drawer is automatically handled each time the user clicks the navigation button. However, you can also set it up so that users can open or close the drawer using swipe gestures. This provides a more natural user experience.

To use this, register a listener through the setDrawerListener method of the DrawerLayout. You can define the actions that occur when the drawer is opened or closed by the user.

drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
                // Animation actions associated with the drawer
            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                // Actions when the drawer is opened
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                // Actions when the drawer is closed
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                // Actions when the drawer state changes
            }
        });

9. Implementing Screen Transition Animations

Depending on the selected menu item in the Navigation View, you can switch to different Activities. At this time, you can enhance the user experience by adding screen transition animations. Below is how to apply animations when transitioning to a new Activity via an Intent.

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
        case R.id.nav_home:
            intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.enter_from_right, R.anim.exit_to_left);
            break;
        case R.id.nav_gallery:
            intent = new Intent(this, GalleryActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.enter_from_right, R.anim.exit_to_left);
            break;
    }
    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
}

10. Testing and Debugging

After completing the app, thoroughly test it on an emulator or real device to ensure that the drawer functions correctly. Verify whether the buttons behave as expected and transition to the correct screen when menu items are selected.
Additionally, test the animation effects when the drawer opens and closes to ensure they work smoothly.

11. Conclusion

In this tutorial, we covered how to implement the Navigation View in Android apps using Java. The Navigation View is a crucial element for user-friendly app organization that provides an enhanced navigation experience for users.
Based on the contents explained in this tutorial, we hope you set up a Navigation View suitable for your app and provide a rich user experience utilizing various UI elements and animations.

© 2023 [Author Name]. All rights reserved.