How to Build an Android News Reader App - Hive Programmers
Greetings to my favorite Science community online, StemSocial.
It's @skyehi and I'm going to continue my series on Android App development for beginners. In today's tutorial, I'll be introducing you to another API.
We're going to build a basic News Reader App which you can run on your physical Android device and read the news. It's a way to introduce my readers and beginners to the News API.
Let's get started shall we.
Original Image Source by lmonk72 from Pixabay
Setting Up the Project
I would have skipped this step but for the benefit of newcomers to my series I'll be happy to share the project setup step.
Before you can get started, you need to ensure that you have installed both Android Studio IDE which is the platform to write the code and Java Development Kit which is needed for our computer to be able to execute Java codes.
I'll assume my readers are all set with this step, however if you're having trouble downloading or installing the setup, please let me know in the comments section below.
We'll start our work by creating a new Android Studio project. To do that, first open Android Studio and click on "Create a new Android Studio project,"
Choose the App name, the package name and Java as our programming language instead of Kotlin.
Also choose "Empty Activity" as our project template. I'll be using that template. So, to make it easy for you to follow the steps I'll be sharing with you, I'll recommend choosing that template.
Designing the User Interface
As we always do, we'll start with my favorite part, designing the frontend. I'll recommend studying a lot of Apps on the Google play store or Apple Store to look at some modern User Interfaces that would inspire you to create better and more professional UI in the future.
The frontend end or User Interface is the part of our App that the user will see and interact with. The better the User interface, the more appealing our App will be to users.
We would need to create the layout for the News Reader app. This would be done inside the res/layout/activity_main.xml
file.
It would be a very simple interface and we'll be using the listView
element so that the news feed can be inside a scrollable list view.
Here's how your code should look like
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/newsListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dp" />
</RelativeLayout>
Fetching The News Data
We're through with the main User interface and we now need to use the News API to fetch the news Data we would need in our App.
To do this properly, we would need to create a java class to handle the network requests.
Here's a simple example of this class and I'll be using the Retrofit library to do this part;
public interface NewsApi {
@GET("top-headlines")
Call<NewsResponse> getTopHeadlines(
@Query("country") String country,
@Query("apiKey") String apiKey
);
}
public class NewsApiClient {
private static final String BASE_URL = "https://newsapi.org/v2/";
private static final String API_KEY = "YOUR_API_KEY";
public static NewsApi create() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(NewsApi.class);
}
}
If you want to learn more about the Retrofit library, here's a link to their website
Creating our News Model
We also need to define a model class that would represent the news data. We'll be creating a Java class for that step
Here's how your code should look like
public class Article {
private String title;
private String description;
// Add other relevant fields
// Add getters and setters
}
public class NewsResponse {
private List<Article> articles;
public List<Article> getArticles() {
return articles;
}
}
Populating News in ListView
Just like how we had to populate the Grid layout in yesterday's Periodic Table Project, we would need to also populate the list view with News Feed using the News API.
This would be done inside the MainActivity.java
file. What we will do is to fetch and display news in the ListView
Here's how your code in Main Activity should look like.
public class MainActivity extends AppCompatActivity {
private ListView newsListView;
private List<Article> articles = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newsListView = findViewById(R.id.newsListView);
fetchNews();
}
private void fetchNews() {
NewsApi newsApi = NewsApiClient.create();
Call<NewsResponse> call = newsApi.getTopHeadlines("us", NewsApiClient.API_KEY);
call.enqueue(new Callback<NewsResponse>() {
@Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
if (response.isSuccessful() && response.body() != null) {
articles = response.body().getArticles();
displayNews();
}
}
@Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, "Failed to fetch news", Toast.LENGTH_SHORT).show();
}
});
}
private void displayNews() {
ArrayAdapter<Article> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, articles);
newsListView.setAdapter(adapter);
}
}
Requesting Internet Permissions
Now guys, since we're using the internet to display the news in our App, we shouldn't forget to add internet permission to the AndroidManifest.xml
otherwise the App may not work.
Here's how the permission code should look like.
<uses-permission android:name="android.permission.INTERNET" />
API Key
Also guys I would want you to replace "YOUR_API_KEY" in the NewsApiClient
class with your actual News API key. Don't leave it as I have done in that class.
Running The App
Congratulations guys, we have successfully completed an entire News Reader App. You can build and run the App either using your physical Android device or an emulator. Please don't forget to turn uSB Debugging on so that you'll be able to run the App on your android phone.
In the future, we can improve the App by adding features like detailed news views, category filters, and offline support. So as we make progress with this tutorial series I'll be sharing more complex codes with everyone.
If you're having any trouble writing the code or running the App, please let me know in the comments.
Have a lovely day and catch you next time on StemSocial. Goodbye ✍️
You Can Follow Me @skyehi For More Like This And Others
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
Thanks for including @stemsocial as a beneficiary, which gives you stronger support.