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!