You are on page 1of 52

2021-22 NEWS APP

CHAPTER 1

INTRODUCTION

Technology is developing and changing in every moment that all domains are patchy
without it. In today’s world everybody have been busy with their business and chores,
So to let them know about what happening around the world, the news platform have begin.
The world with new technology and rising users have initiate the development of new verity
of application suitable to devices.
To know people what is going around in their country and stats or around them news
channels and news papers were distributed but to know the news or information when they
are away from home were difficult in earlier days. Matthew Panzarino, co-editor of
TechCrunch, has charted three phases of app development that took mobile technology from
telephony to gaming and utilities, to apps that wanted to be your “home screen” and
dominate your experience, to apps armed with content that “are more about maximizing
their usefulness without dominating your attention.”
By this many application development started and launched their applications through app
stores in android mobile phones.
Android provides simple application structure and requires Java and Mark-up languages
knowledge to work with. Such as, an discrete movement delivers a solitary screen for a user
interface and a service whole completes work in the contextual . We can work on different
module separately and can combine at the end, we can also add future modules easily
afterwards. API (Application Programming Interface) which is an
intermediate interface between different applications. It provides automation, immediacy,
adaption and personalization.
News api’s provides us the source of news articles from many different sources at one place
and updates it. To expand the sources old fashioned Admin panel can be used where writers
will fill the gap of API.
In 2014, a design language has been created by google named Material Design which is
based on “cards” uses grind based layouts, responsive animation, padding and depth effects
like shadow to create an responsive, attractive and easy user interface. With the use of
different libraries and material design it is possible to use attractive UI.

Dept. of cse 1
2021-22 NEWS APP

1.1 Problem Statement/Aim

The purpose of the project is to develop an application which will display news articles and
videos verified and approved at backend. User can browse news articles and videos through
various categories. App will enable user to view news details, images, and video. Users can
also bookmark any news article/video for future use.
This application is developed using NEWS API which is an Application Programming
Interface that provides access to news sources and databases.
By the use of NEWS API a developer can able to provide the different functionalities, which
gathers the information related to the user input.
This NEWS APP is helpful and provide five different countries information with their own
language. It shows the latest news and articles of the chosen country by the user.

1.2 SCOPE

The scope of the project includes followings


 Functional specification document to describe the complete system in low level
 User interface design for website and mobile phone for both iOS and Android.
 Development of all functional requirements as proposed for the web and mobile
application.
 Setting up the system on live server in ready for use condition
Available features like:
Global Support: Different type of newspaper will be available from all around the world in
different languages with this user will be able to get news from all around the world.
Short News: News will be displayed in short format with title, image and little description in
list view. It will help user to access required news faster.
Search Option: User will be able to search from not only one source but many different
sources available within API. .
Sharing: User will be able to share news easily on social media.

Dept. of cse 2
2021-22 NEWS APP

1.3 Project Description

The “NEWS APP” project is a native an android application is to provide people a handy
android application through which people can access all types of news and the information
of ongoing world. As world’s technology is rapidly growing we has fast connection and
network to instantly connect to other person. Day to day use in mobile, tablets and laptop is
increasing, most of the people already have this facilities. In this fast and information
oriented world we need to stay updated with every incidents and news too. This News app is
android mobile application where user have access to latest news from 120+ newspapers
from 5countries. The main focus of this application is to connect news articles from all
around the world and deliver it to user as fast as possible in best visualize way.
Use case and Button Does: In this project a user can access this application with five
countries namely: United Kingdom, Turkey, Indonesia, Italy Germany, France with its
language proficiency and this app provides the information about heath, science, sports,
Technology, Business, Entertainment.
This application many focus on the information of respected country to reach the users who
are using this application.

Dept. of cse 3
2021-22 NEWS APP

CHAPTER 2
REQUIREMENT ANALYSIS
A software requirement definition is an abstract description of the services which the
system should provide, and the constraints under which the system must operate.
2.1 Hardware Requirements

 64-bit Microsoft® Windows® 8/10.

 x86_64 CPU architecture; 2nd generation Intel Core or newer, or AMD CPU with
support for a Windows Hypervisor.

 8 GB RAM or more.

 8 GB of available disk space minimum (IDE + Android SDK + Android Emulator)

 1280 x 800 minimum screen resolution.


2.2 Software requirements

 Programming Language: Java

 Operating System: Windows

 IDE: Android Studio

 Functional Requirements: Gradle

Dept. of cse 4
2021-22 NEWS APP

CHAPTER 3

DESIGN

3.1 SYSTEM DESIGN


In this mini project by using java as a programming language we are creating an AIDL
(Android Interface Definition Language) service that calculates Car Loan EMI.
Java
Android applications are developed using the Java language. As of now, that’s really
only option for native applications. Java is a very popular programming language
developed by Sun MicroSystems (now owned by Oracle). Developed long after C and
C++, Java incorporates many of the powerful features of those powerful languages while
addressing some of their drawbacks. Still, programming languages are only as powerful
as their libraries. These libraries exist to help developers build applications.
Some of the Java’s important core features are:
• It’s easy to learn and understand
• It’s designed to be platform-independent and secure, using virtual machines.
• It’s object-oriented
Android relies heavily on these Java fundamentals. The Android SDK includes many
standard Java libraries (data structure libraries, math libraries, graphics libraries,
networking libraries and everything else you could want) as well as special Android
libraries that will help you develop awesome Android applications.

MVVM (Model- view-view model)

Model–view–view model is a software architectural pattern that facilitates the separation


of the development of the graphical user interface – be it via a markup language or GUI

code – from the development of the business logic or back-end logic so that the view is
not dependent on any specific model platform.

Dept. of cse 5
2021-22 NEWS APP

3.2 User Interface

For the development of this project, we are using Android Studio Chipmunk | 2021.2.1
Runtime version: 11.0.12+7-b1504.28-7817840 amd64
API: 30
Programming language: Java
User interface: XML
Minimum SDK: API 28 Android 8.0(Oreo)
Gradle JDK: java 11(version_11)
API: newsapi.org

One of the factors in successful news app development is visualization of news and its
feature with user. For the development of an android app material design is very useful
and provides smooth experience with custom layout, views and animations.
For this news app user should be able to select from different categories, countries and
newspaper. Short News as list view with header, little description and image before showing
full article can be helpful to user to determine what type of news they are looking for.
View Holder can be used for this list view for better and fast experience. Library like
Picasso can be used for better image handling.
This User interface will be connected to API which will give full article in form of web
view of that article. Because of this structure the integrity of writer of that article will not be
in harm.
API:
News API has been used for collecting different news sources at one spot. On sending
request it will give response in JSON format which contains source id, title, description,
image URL, article URL, author, time etc. We need to handle and parse this JSON into
string format which is our required format.

Dept. of cse 6
2021-22 NEWS APP

3.2.1 Use case diagram:

Fig 3.2.1: Use case diagram-News App


This use case diagram show how user can interact with this application and the process of
using this application.

3.3 Process Flow


News App allows user to access the information of newspapers and news channels of latest
news in their devices. When the user click on the application in their device the Home
screen which gives him a default news with language selected with all categories that have
provided by the application developer.

Dept. of cse 7
2021-22 NEWS APP

Fig 3.3.1: Layout design of Home Page.

The users are allowed to choose the country of their own among: United Kingdom, Turkey,
Indonesia, Italy Germany, France. In which users can see the news of their country and get
the required information. By selecting the country icon in the right top of the home page the
app lets user to select their country by clicking on the country name and pressing ok, if not
user can change the country or cancel it.
After this user can see their native language news. When users click on the news headline
that will ask user to just see the headlines or want to see full details of particular news.
If user want to see just headlines he can see and click cancel button or if user want to see
full news or full article about particular news by clicking “Go to website” it will redirect it
to website of the news which it is published with its full details of the particular news.

Dept. of cse 8
2021-22 NEWS APP

Fig 3.3.2: Layout design of viewing full article.

Fig 3.3.3: Layout design of news dashboard.

Dept. of cse 9
2021-22 NEWS APP

CHAPTER 4
4.IMPLIMENTATION

4.1 Code Snippets

Source code
1. MainActivity.java
2. AdapterListNews.java
3. AdapteritemClickListener.java
4. NewsDilogClickListeners.java
5. News.java
6. TotalNews.java
7. Apiclient.java
8. RestInterface.java
9. Util.java
10.MyGlideModule.java
11.UnsafeOKHttpClient.java
12.LocaleHelper.java
13.activity_main.xml
14.dialog_header_polygon.xml
15.item_news_dashboard.xml
16.strings.xml

MainActivity.java
Here we create code for a home screen buttons like section of news to see. here user can
view their selected countries news with their language of selected country. and can view full
short headlines of the latest news and change the country and sections which they want.
package com.project.newsapp.activities;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;

Dept. of cse 10
2021-22 NEWS APP

import android.view.View;
import android.view.Window;
import android.widget.ImageView;

import android.appcompat.app.AlertDialog;
import android.appcompat.app.AppCompatActivity;
import android.appcompat.widget.SearchView;
import android.appcompat.widget.Toolbar;
import android.databinding.DataBindingUtil;
import android.lifecycle.LifecycleOwner;
import android.lifecycle.Observer;
import android.lifecycle.ViewModelProviders;
import android.recyclerview.widget.LinearLayoutManager;
import android.recyclerview.widget.RecyclerView;

import com.project.newsapp.R;
import com.project.newsapp.adapters.AdapterListNews;
import com.project.newsapp.clicklisteners.AdapterItemClickListener;
import com.project.newsapp.clicklisteners.NewsDialogClickListeners;
import com.project.newsapp.databinding.NewsDialogBinding;
import com.project.newsapp.model.News;
import com.project.newsapp.utils.LocaleHelper;
import com.project.newsapp.utils.Util;
import com.project.newsapp.viewmodels.MainViewModel;

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

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements LifecycleOwner,


AdapterItemClickListener {

@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.ivToolbarCountry)
ImageView ivToolbarCountry;

MainActivity context;
MainViewModel viewModel;
AdapterListNews adapterListNews;
List<News> newsList;

private String firstControl = “firstControl”;


private String countryPositionPref = “countryPositionPref”;
SharedPreferences pref;

Dept. of cse 11
2021-22 NEWS APP

private String[] countrys;


private TypedArray countrysIcons;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
pref = getApplicationContext().getSharedPreferences(Util.APP_NAME,
MODE_PRIVATE);
languageControl();
setContentView(R.layout.activity_main);
context = this;
ButterKnife.bind(this);
countrys = getResources().getStringArray(R.array.countrys);
countrysIcons = getResources().obtainTypedArray(R.array.countrysIcons);

initToolbar();

newsList = new ArrayList<>();


adapterListNews = new AdapterListNews(newsList, this);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(adapterListNews);

if (pref.contains(countryPositionPref))

ivToolbarCountry.setImageResource(countrysIcons.getResourceId(pref.getInt(countryP
ositionPref, 0), 0));

viewModel = ViewModelProviders.of(context).get(MainViewModel.class);
viewModel.getNewsLiveData().observe(context, newsListUpdateObserver);
viewModel.setApiKey(getString(R.string.news_api_key));
viewModel.setCountryCode(pref.getString(Util.COUNTRY_PREF, “tr”));

private void languageControl() {


if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N
&& !pref.getBoolean(firstControl, false)) {
Locale primaryLocale = getResources().getConfiguration().getLocales().get(0);
LocaleHelper.setLocale(MainActivity.this, primaryLocale.getLanguage());
int position = getLanguagePosition(primaryLocale.getLanguage());
pref.edit().putInt(countryPositionPref, position).apply();
pref.edit().putBoolean(firstControl, true).apply();
recreate();
}
}

Dept. of cse 12
2021-22 NEWS APP

private int getLanguagePosition(String displayLanguage) {


String[] codes = getResources().getStringArray(R.array.countrysCodes);
for (int I = 0; I < codes.length; i++) {
if (codes[i].equals(displayLanguage)) return I;
}
return 0;
}

private void initToolbar() {


Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setTitle(null);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Util.setSystemBarColor(this, android.R.color.white);
Util.setSystemBarLight(this);
}

private void showLanguageDialog() {


new AlertDialog.Builder(this).setCancelable(false)
.setTitle(“Choose Country”)
.setSingleChoiceItems(countrys, pref.getInt(countryPositionPref, 0), null)
.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss())
.setPositiveButton(R.string.ok, (dialog, whichButton) -> {
int selectedPosition = ((AlertDialog)
dialog).getListView().getCheckedItemPosition();
pref.edit().putInt(countryPositionPref, selectedPosition).apply();
pref.edit().putString(Util.COUNTRY_PREF,
getResources().getStringArray(R.array.countrysCodes)[selectedPosition]).apply();
LocaleHelper.setLocale(MainActivity.this,
getResources().getStringArray(R.array.countrysCodes)[selectedPosition]);
recreate();
dialog.dismiss();
})
.show();
}

@Override
public ndroid onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
Util.changeMenuIconColor(menu, Color.BLACK);
MenuItem searchItem = menu.findItem(R.id.action_search);

SearchManager searchManager = (SearchManager)


MainActivity.this.getSystemService(Context.SEARCH_SERVICE);

SearchView searchView = null;


if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();

Dept. of cse 13
2021-22 NEWS APP

}
if (searchView != null) {

searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getCom
ponentName()));
}
searchView.setQueryHint(getString(R.string.search_in_everything));
if (searchView != null)

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public ndroid onQueryTextSubmit(String query) {
if (viewModel != null) viewModel.searchNews(query);
return false;
}

@Override
public ndroid onQueryTextChange(String newText) {
return false;
}
});
return true;
}

public void categoryClicked(View view) {


viewModel.newsCategoryClick(String.valueOf(view.getTag()));
}

public void countryClick(View view) {


showLanguageDialog();
}

Observer<List<News>> newsListUpdateObserver = new Observer<List<News>>() {


@Override
public void onChanged(List<News> news) {
newsList.clear();
if (news != null) {
newsList.addAll(news);
}
adapterListNews.notifyDataSetChanged();
}
};

@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(LocaleHelper.onAttach(newBase));
}

Dept. of cse 14
2021-22 NEWS APP

@Override
public void onNewsItemClick(News news) {
showDialogPolygon(news);
}

private void showDialogPolygon(News news) {


final Dialog dialog = new Dialog(this);
NewsDialogBinding binding =
DataBindingUtil.inflate(LayoutInflater.from(getApplicationContext()),
R.layout.dialog_header_polygon, null, false);

binding.setNews(news);

binding.setListener(new NewsDialogClickListeners() {

@Override
public void onGotoWebSiteClick(String url) {
Intent I = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}

@Override
public void onDismissClick() {
dialog.dismiss();
}
});

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(binding.getRoot());
dialog.getWindow().setBackgroundDrawable(new
ColorDrawable(Color.TRANSPARENT));
dialog.setCancelable(true);

dialog.show();
}

activity_main.xml

In this xml file we have created the main home page of our application by linear layout,
image view and relative layout.
The horizontal scroll bar is used for the categories or list of the news to select and view.
The text view is used and inside that image view for selecting country.
And the relative layout is used to specify the section of the news.

Dept. of cse 15
2021-22 NEWS APP

<?xml version=”1.0” encoding=”utf-8”?>


<layout xmlns:tools=”http://schemas.android.com/tools”>
<data>
<import type=”android.view.View” />
<variable
name=”viewModel”
type=”com.project.newsapp.viewmodels.MainViewModel” />
</data>
<ndroid.coordinatorlayout.widget.CoordinatorLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:app=”http://schemas.android.com/apk/res-auto”
android:id=”@+id/lyt_parent”
android:layout_width=”match_parent”
android:layout_height=”match_parent”

android:background=”@android:color/white”>
<com.google.android.material.appbar.AppBarLayout

android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:theme=”@style/AppTheme.AppBarOverlay”>

<ndroid.appcompat.widget.Toolbar
android:id=”@+id/toolbar”
android:layout_width=”match_parent”
android:layout_height=”?attr/actionBarSize”
android:background=”@android:color/white”
app:contentInsetStartWithNavigation=”0dp”
app:popupTheme=”@style/ThemeOverlay.AppCompat.Light”
app:theme=”@style/Toolbar.Light”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”
android:weightSum=”1”>

<ImageView
android:id=”@+id/ivToolbarCountry”
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:layout_weight=”0.1”
android:clickable=”true”
android:focusable=”true”
android:onClick=”countryClick”
android:padding=”@dimen/spacing_medium”
android:src=”@drawable/ic_turkey” />

<LinearLayout
android:layout_width=”0dp”

Dept. of cse 16
2021-22 NEWS APP

android:layout_height=”?attr/actionBarSize”
android:layout_marginEnd=”@dimen/spacing_large”
android:layout_marginRight=”@dimen/spacing_large”
android:layout_weight=”0.9”
android:gravity=”center”
android:orientation=”horizontal”>

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:clickable=”true”
android:focusable=”true”
android:onClick=”categoryClicked”
android:tag=””
android:text=”• News App •”

android:textAppearance=”@style/TextAppearance.AppCompat.Title”
android:textColor=”@android:color/black”
app:fontFamily=”sans-serif-medium” />

</LinearLayout>

</LinearLayout>
</ndroid.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>

<ndroid.core.widget.NestedScrollView
android:id=”@+id/nested_scroll_view”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”@color/grey_3”
android:scrollbars=”none”
android:scrollingCache=”true”
app:layout_behavior=”@string/appbar_scrolling_view_behavior”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:focusableInTouchMode=”true”
android:orientation=”vertical”>

<HorizontalScrollView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_mxlarge”
android:scrollbars=”none”>

<LinearLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”

Dept. of cse 17
2021-22 NEWS APP

android:gravity=”center_vertical”
android:orientation=”horizontal”>

<View
android:layout_width=”@dimen/spacing_smlarge”
android:layout_height=”0dp” />

<ndroid.cardview.widget.CardView
android:id=”@+id/cardBusiness”

android:layout_width=”@dimen/dashboardNewsCategoryCardWidth”
android:layout_height=”wrap_content”
android:clickable=”true”
android:focusable=”true”
android:onClick=”categoryClicked”
android:tag=”business”
app:cardBackgroundColor=”@color/light_blue_400”

app:cardCornerRadius=”@dimen/dashboardNewsCategoryCardRadius”
app:cardElevation=”0dp”
app:cardUseCompatPadding=”false”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”?attr/selectableItemBackgroundBorderless”
android:orientation=”vertical”
android:padding=”@dimen/spacing_large”>

<RelativeLayout

android:layout_width=”@dimen/dashboardNewsCategoryCardImageWidthHeight”

android:layout_height=”@dimen/dashboardNewsCategoryCardImageWidthHeight”>

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”
android:tint=”@android:color/white”
app:srcCompat=”@drawable/shape_circle”
tools:ignore=”UseAppTint” />

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”

android:layout_margin=”@dimen/dashboardNewsCategoryCardImageMargin”

Dept. of cse 18
2021-22 NEWS APP

android:src=”@drawable/ic_business”
android:tint=”@color/light_blue_400”
tools:ignore=”UseAppTint” />

</RelativeLayout>

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_middle”
android:text=”@string/category_business”
android:textAllCaps=”true”

android:textAppearance=”@style/Base.TextAppearance.AppCompat.Body2”
android:textColor=”@android:color/white”
app:fontFamily=”sans-serif-medium” />

</LinearLayout>

</ndroid.cardview.widget.CardView>

<View

android:layout_width=”@dimen/spacing_middle”
android:layout_height=”0dp” />

<ndroid.cardview.widget.CardView
android:id=”@+id/cardEntertainment”

android:layout_width=”@dimen/dashboardNewsCategoryCardWidth”
android:layout_height=”wrap_content”
android:clickable=”true”
android:focusable=”true”
android:onClick=”categoryClicked”
android:tag=”entertainment”
app:cardBackgroundColor=”@color/pink_300”

app:cardCornerRadius=”@dimen/dashboardNewsCategoryCardRadius”
app:cardElevation=”0dp”
app:cardUseCompatPadding=”false”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”?attr/selectableItemBackgroundBorderless”

android:orientation=”vertical”
android:padding=”@dimen/spacing_large”

Dept. of cse 19
2021-22 NEWS APP

android:tag=”entertainment”>

<RelativeLayout

android:layout_width=”@dimen/dashboardNewsCategoryCardImageWidthHeight”

android:layout_height=”@dimen/dashboardNewsCategoryCardImageWidthHeight”>

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”
android:tint=”@android:color/white”
app:srcCompat=”@drawable/shape_circle”
tools:ignore=”UseAppTint” />

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”
android:layout_margin=”7dp”
android:src=”@drawable/ic_entertainment”
android:tint=”@color/pink_300”
tools:ignore=”UseAppTint” />

</RelativeLayout>

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_middle”
android:text=”@string/category_entertainment”
android:textAllCaps=”true”

android:textAppearance=”@style/Base.TextAppearance.AppCompat.Body2”
android:textColor=”@android:color/white”
app:fontFamily=”sans-serif-medium” />

</LinearLayout>

</ndroid.cardview.widget.CardView>

<View
android:layout_width=”@dimen/spacing_middle”
android:layout_height=”0dp” />

<ndroid.cardview.widget.CardView
android:id=”@+id/cardHealth”

Dept. of cse 20
2021-22 NEWS APP

android:layout_width=”@dimen/dashboardNewsCategoryCardWidth”
android:layout_height=”wrap_content”
android:clickable=”true”
android:focusable=”true”
android:onClick=”categoryClicked”
android:tag=”health”
app:cardBackgroundColor=”@color/light_green_300”

app:cardCornerRadius=”@dimen/dashboardNewsCategoryCardRadius”
app:cardElevation=”0dp”
app:cardUseCompatPadding=”false”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”?attr/selectableItemBackgroundBorderless”
android:orientation=”vertical”
android:padding=”@dimen/spacing_large”>

<RelativeLayout

android:layout_width=”@dimen/dashboardNewsCategoryCardImageWidthHeight”

android:layout_height=”@dimen/dashboardNewsCategoryCardImageWidthHeight”>

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”

android:layout_centerInParent=”true”
android:tint=”@android:color/white”
app:srcCompat=”@drawable/shape_circle”
tools:ignore=”UseAppTint” />

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”

android:layout_margin=”@dimen/dashboardNewsCategoryCardImageMargin”
android:src=”@drawable/ic_health”
android:tint=”@color/light_green_300”
tools:ignore=”UseAppTint” />

</RelativeLayout>

<TextView
android:layout_width=”wrap_content”

Dept. of cse 21
2021-22 NEWS APP

android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_middle”
android:text=”@string/category_health”
android:textAllCaps=”true”

android:textAppearance=”@style/Base.TextAppearance.AppCompat.Body2”
android:textColor=”@android:color/white”
app:fontFamily=”sans-serif-medium” />

</LinearLayout>

</ndroid.cardview.widget.CardView>

<View
android:layout_width=”@dimen/spacing_middle”
android:layout_height=”0dp” />

<ndroid.cardview.widget.CardView
android:id=”@+id/cardScience”

android:layout_width=”@dimen/dashboardNewsCategoryCardWidth”
android:layout_height=”wrap_content”
android:clickable=”true”
android:focusable=”true”
android:onClick=”categoryClicked”
android:tag=”science”
app:cardBackgroundColor=”@color/purple_300”

app:cardCornerRadius=”@dimen/dashboardNewsCategoryCardRadius”
app:cardElevation=”0dp”
app:cardUseCompatPadding=”false”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”?attr/selectableItemBackgroundBorderless”
android:orientation=”vertical”
android:padding=”@dimen/spacing_large”>

<RelativeLayout

android:layout_width=”@dimen/dashboardNewsCategoryCardImageWidthHeight”

android:layout_height=”@dimen/dashboardNewsCategoryCardImageWidthHeight”>

<ImageView
android:layout_width=”match_parent”

Dept. of cse 22
2021-22 NEWS APP

android:layout_height=”match_parent”
android:layout_centerInParent=”true”
android:tint=”@android:color/white”
app:srcCompat=”@drawable/shape_circle”
tools:ignore=”UseAppTint” />

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”

android:layout_margin=”@dimen/dashboardNewsCategoryCardImageMargin”
android:src=”@drawable/ic_science”
android:tint=”@color/purple_300”
tools:ignore=”UseAppTint” />

</RelativeLayout>

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_middle”
android:text=”@string/category_science”
android:textAllCaps=”true”

android:textAppearance=”@style/Base.TextAppearance.AppCompat.Body2”
android:textColor=”@android:color/white”
app:fontFamily=”sans-serif-medium” />

</LinearLayout>

</ndroid.cardview.widget.CardView>

<View

android:layout_width=”@dimen/spacing_middle”

android:layout_height=”0dp” />
<ndroid.cardview.widget.CardView
android:id=”@+id/cardSports”

android:layout_width=”@dimen/dashboardNewsCategoryCardWidth”
android:layout_height=”wrap_content”
android:clickable=”true”
android:focusable=”true”
android:onClick=”categoryClicked”
android:tag=”sports”
app:cardBackgroundColor=”@color/red_300”

Dept. of cse 23
2021-22 NEWS APP

app:cardCornerRadius=”@dimen/dashboardNewsCategoryCardRadius”
app:cardElevation=”0dp”
app:cardUseCompatPadding=”false”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”?attr/selectableItemBackgroundBorderless”
android:orientation=”vertical”
android:padding=”@dimen/spacing_large”>

<RelativeLayout

android:layout_width=”@dimen/dashboardNewsCategoryCardImageWidthHeight”

android:layout_height=”@dimen/dashboardNewsCategoryCardImageWidthHeight”>

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”
android:tint=”@android:color/white”
app:srcCompat=”@drawable/shape_circle”
tools:ignore=”UseAppTint” />

<ImageView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”

android:layout_margin=”@dimen/dashboardNewsCategoryCardImageMargin”
android:src=”@drawable/ic_sports”
android:tint=”@color/red_300”
tools:ignore=”UseAppTint” />

</RelativeLayout>

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_middle”
android:text=”@string/category_sports”
android:textAllCaps=”true”

android:textAppearance=”@style/Base.TextAppearance.AppCompat.Body2”
android:textColor=”@android:color/white”
app:fontFamily=”sans-serif-medium” />

</LinearLayout>

Dept. of cse 24
2021-22 NEWS APP

</ndroid.cardview.widget.CardView>

<View
android:layout_width=”@dimen/spacing_middle”
android:layout_height=”0dp” />

<ndroid.cardview.widget.CardView
android:id=”@+id/cardTechnology”

android:layout_width=”@dimen/dashboardNewsCategoryCardWidth”
android:layout_height=”wrap_content”
android:clickable=”true”
android:focusable=”true”
android:onClick=”categoryClicked”
android:tag=”technology”
app:cardBackgroundColor=”@color/orange_300”

app:cardCornerRadius=”@dimen/dashboardNewsCategoryCardRadius”
app:cardElevation=”0dp”
app:cardUseCompatPadding=”false”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”?attr/selectableItemBackgroundBorderless”
android:orientation=”vertical”
android:padding=”@dimen/spacing_large”>

<RelativeLayout

android:layout_width=”@dimen/dashboardNewsCategoryCardImageWidthHeight”

android:layout_height=”@dimen/dashboardNewsCategoryCardImageWidthHeight”>

<ImageView

android:layout_width=”match_parent”

android:layout_height=”match_parent”
android:layout_centerInParent=”true”
android:tint=”@android:color/white”
app:srcCompat=”@drawable/shape_circle”
tools:ignore=”UseAppTint” />

<ImageView

Dept. of cse 25
2021-22 NEWS APP

android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”

android:layout_margin=”@dimen/dashboardNewsCategoryCardImageMargin”
android:src=”@drawable/ic_technology”
android:tint=”@color/orange_300”
tools:ignore=”UseAppTint” />

</RelativeLayout>

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_middle”
android:text=”@string/category_technology”
android:textAllCaps=”true”

android:textAppearance=”@style/Base.TextAppearance.AppCompat.Body2”
android:textColor=”@android:color/white”
app:fontFamily=”sans-serif-medium” />

</LinearLayout>

</ndroid.cardview.widget.CardView>

<View
android:layout_width=”@dimen/spacing_smlarge”
android:layout_height=”0dp” />

</LinearLayout>

</HorizontalScrollView>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”@dimen/spacing_smlarge”
android:layout_marginTop=”@dimen/spacing_mlarge”
android:layout_marginRight=”@dimen/spacing_smlarge”
android:layout_marginBottom=”@dimen/spacing_middle”

android:orientation=”horizontal”>

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”@string/news”

Dept. of cse 26
2021-22 NEWS APP

android:textAppearance=”@style/Base.TextAppearance.AppCompat.Title”
android:textColor=”@android:color/black”
app:fontFamily=”sans-serif-medium” />

</LinearLayout>

<ndroid.recyclerview.widget.RecyclerView
android:id=”@+id/recyclerView”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_margin=”@dimen/spacing_medium”
android:fillViewport=”true”
android:scrollbars=”vertical”
android:scrollingCache=”true” />

</LinearLayout>
</ndroid.core.widget.NestedScrollView>
</ndroid.coordinatorlayout.widget.CoordinatorLayout>
</layout>

AdapterListNews.java

In this java file we tried to give the bridge between UI component and data source that helps
us to fill data in UI component. It holds the data and sends the data to the adopter view the
view can takes the data from the adopter view and shows the view in different view in list
view and grid view. And we have used recycler view here.

package com.project.newsapp.adapters;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import android.databinding.DataBindingUtil;
import android.recyclerview.widget.RecyclerView;

import com.project.newsapp.R;
import com.project.newsapp.clicklisteners.AdapterItemClickListener;

import com.project.newsapp.databinding.NewsBinding;

import com.project.newsapp.model.News;

import java.util.List;

Dept. of cse 27
2021-22 NEWS APP

public class AdapterListNews extends


RecyclerView.Adapter<AdapterListNews.NewsViewHolder> {

private List<News> items;


private AdapterItemClickListener adapterItemClickListener;

public AdapterListNews(List<News> items, AdapterItemClickListener


adapterItemClickListener) {
this.items = items;
this.adapterItemClickListener = adapterItemClickListener;
}

@Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
NewsBinding newsBinding =
DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),
R.layout.item_news_dashboard, parent, false);
return new NewsViewHolder(newsBinding);
}

// Replace the contents of a view (invoked by the layout manager)


@Override
public void onBindViewHolder(NewsViewHolder holder, final int position) {
holder.bind(getItem(position), adapterItemClickListener);
}

@Override
public int getItemCount() {
return items.size();
}

private News getItem(int position) {


return items.get(position);
}

public class NewsViewHolder extends RecyclerView.ViewHolder {


private NewsBinding newsBinding;

public NewsViewHolder(NewsBinding newsBinding) {


super(newsBinding.getRoot());
this.newsBinding = newsBinding;
}

public void bind(News news, AdapterItemClickListener adapterItemClickListener) {


this.newsBinding.setNews(news);

this.newsBinding.setClickListener(adapterItemClickListener);

Dept. of cse 28
2021-22 NEWS APP

}
AdopteritemClickListener.java

package com.project.newsapp.clicklisteners;

import com.project.newsapp.model.News;

public interface AdapterItemClickListener {

void onNewsItemClick(News news);

NewsDialogClickListeners.java

In this java file we are getting the url for the news article.

package com.project.newsapp.clicklisteners;

public interface NewsDialogClickListeners {

void onGotoWebSiteClick(String url);


void onDismissClick();

News.java

In this java file we are specifying the information that news article should have like date
time, published at, url of the article etc.
package com.project.newsapp.model;

import android.widget.ImageView;

import ndroid.annotation.NonNull;
import ndroid.databinding.BindingAdapter;

import com.bumptech.glide.Glide;
import com.google.gson.annotations.SerializedName;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class News {

Dept. of cse 29
2021-22 NEWS APP

@NonNull
@SerializedName(“source”)
private Source source;

@NonNull
@SerializedName(“title”)
private String newsTitle;

@NonNull
@SerializedName(“description”)
private String newsDescription;

@NonNull
@SerializedName(“url”)
private String newsUrl;

@NonNull
@SerializedName(“urlToImage”)
private String newsImage;

@NonNull
@SerializedName(“publishedAt”)
private Date newsPublishedDate;

@NonNull
public Source getSource() {
return source;
}

public void setSource(@NonNull Source source) {


this.source = source;
}

@NonNull
public String getNewsTitle() {
return newsTitle;
}

public void setNewsTitle(@NonNull String newsTitle) {


this.newsTitle = newsTitle;
}

@NonNull
public String getNewsDescription() {
return newsDescription;
}

public void setNewsDescription(@NonNull String newsDescription) {


this.newsDescription = newsDescription;

Dept. of cse 30
2021-22 NEWS APP

@NonNull

public String getNewsUrl() {


return newsUrl;
}

public void setNewsUrl(@NonNull String newsUrl) {


this.newsUrl = newsUrl;
}

@NonNull
public String getNewsImage() {
return newsImage;
}

public void setNewsImage(@NonNull String newsImage) {


this.newsImage = newsImage;
}

@NonNull
public String getNewsPublishedDate() {
return new SimpleDateFormat(“dd/MM/yyyy HH:mm:ss”,
Locale.getDefault()).format(newsPublishedDate);
}

public void setNewsPublishedDate(@NonNull Date newsPublishedDate) {


this.newsPublishedDate = newsPublishedDate;
}

//Added for Child JSON Object


public class Source {
@SerializedName(“name”)
private String sourceName;

public String getSourceName() {


return sourceName;
}

public void setSourceName(String sourceName) {


this.sourceName = sourceName;
}
}

//Image Binding – I didn’t write newsviewmodel for just this method


@BindingAdapter({“bind:imgUrl”})
public static void setImage(ImageView imageView, String imgUrl) {
Glide.with(imageView.getContext()).load(imgUrl).into(imageView);

Dept. of cse 31
2021-22 NEWS APP

}
}

TotalNews.java

In this java file we are giving the annotation to our application to display the contents in the
app. Which provide total news of the news article.
package com.project.newsapp.model;

import ndroid.annotation.NonNull;

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class TotalNews {

@NonNull
private String status;

@NonNull
@SerializedName(“totalResults”)
private int totalNewsCount;

@NonNull
@SerializedName(“articles”)
private List<News> newsList;

public TotalNews() {
}

@NonNull
public String getStatus() {
return status;
}

public void setStatus(@NonNull String status) {


this.status = status;
}

public int getTotalNewsCount() {


return totalNewsCount;
}
public void setTotalNewsCount(int totalNewsCount) {
this.totalNewsCount = totalNewsCount;
}
@NonNull

Dept. of cse 32
2021-22 NEWS APP

public List<News> getNewsList() {


return newsList;
}
public void setNewsList(@NonNull List<News> newsList) {
this.newsList = newsList;
}
}

ApiClient.java
In this java file we are implemented the ok Http client and retrofit to convert the gson file
It will provide access to the client and server interaction.
package com.project.newsapp.restapi;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {

private static Retrofit retrofit = null;

public static Retrofit getClient(String apiBaseUrl) {


if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(apiBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient())
.build();
}
return retrofit;
}

RestInterface.java

It is an interface java file

Dept. of cse 33
2021-22 NEWS APP

package com.project.newsapp.restapi;

import com.project.newsapp.model.TotalNews;

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

public interface RestInterface {

@GET(“v2/top-headlines”)
Call<TotalNews> getTotalNews(@Query(“country”) String country,
@Query(“apiKey”) String apiKey);

@GET(“v2/top-headlines”)
Call<TotalNews> getTotalNews(@Query(“country”) String country,
@Query(“category”) String category, @Query(“apiKey”) String apiKey);

@GET(“v2/everything”)
Call<TotalNews> getSearchedTotalNews(@Query(“q”) String country,
@Query(“apiKey”) String apiKey);
}
MyGlideModule.java
In this java file we can load the images from the server or from the websites for the news.
By importing the glide and its library we can able to load the images.

package com.project.newsapp.utils.glidessl;

import android.content.Context;

import ndroid.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.AppGlideModule;

import java.io.InputStream;

import okhttp3.OkHttpClient;

@GlideModule
public class MyGlideModule extends AppGlideModule {

@Override

Dept. of cse 34
2021-22 NEWS APP

public void applyOptions(Context context, GlideBuilder builder) {


super.applyOptions(context, builder);
}

@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide,
@NonNull Registry registry) {
OkHttpClient okHttpClient= UnsafeOkHttpClient.getUnsafeOkHttpClient();
registry.replace(GlideUrl.class, InputStream.class, new
OkHttpUrlLoader.Factory(okHttpClient));
}
}

UnsafeHttpClient.java
In this java file by using the unsafe ok Http client in android application to make call from
the Api’s with SSL and trust manager and X509Trust Manager.
SSL is a transport layer for encrypted communication between client and servers.
X509 Trust Manager is to authenticate. with we can ensure that application to communicate
with the server.

package com.project.newsapp.utils.glidessl;

import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

public class UnsafeOkHttpClient {

public static OkHttpClient getUnsafeOkHttpClient() {


try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {

Dept. of cse 35
2021-22 NEWS APP

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};

// Install the all-trusting trust manager


final SSLContext sslContext = SSLContext.getInstance(“SSL”);
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

// Create an ssl socket factory with our all-trusting manager


final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

OkHttpClient.Builder builder = new OkHttpClient.Builder();


builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier((hostname, session) -> true);

OkHttpClient okHttpClient = builder.build();


return okHttpClient;
} catch (Exception e) {
throw new RuntimeExceptionI;
}
}

LocaleHelper.java

In this java file we have specified the language of the country provided to get the persisted
data and updated data and by SharedPreferencesData allows us to save, retrive the data in
the form of key : value pair.

package com.project.newsapp.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

public class LocaleHelper {

private static final String SELECTED_LANGUAGE =

Dept. of cse 36
2021-22 NEWS APP

“Locale.Helper.Selected.Language”;

public static Context onAttach(Context context) {


String lang = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, lang);
}

public static Context onAttach(Context context, String defaultLanguage) {


String lang = getPersistedData(context, defaultLanguage);
return setLocale(context, lang);
}

public static String getLanguage(Context context) {


return getPersistedData(context, Locale.getDefault().getLanguage());
}

public static Context setLocale(Context context, String language) {


persist(context, language);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {


return updateResources(context, language);
}

return updateResourcesLegacy(context, language);


}

private static String getPersistedData(Context context, String defaultLanguage) {


SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}

private static void persist(Context context, String language) {


SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();

editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}

@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);

Configuration configuration = context.getResources().getConfiguration();


configuration.setLocale(locale);

return context.createConfigurationContext(configuration);

Dept. of cse 37
2021-22 NEWS APP

@SuppressWarnings(“deprecation”)
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);

Resources resources = context.getResources();

Configuration configuration = resources.getConfiguration();


configuration.locale = locale;

resources.updateConfiguration(configuration, resources.getDisplayMetrics());

return context;
}
}

Util.java

This java file specifies utility such as color and graphics utilities for the application. Here
we have given the Color specification, Draw system bar background and Translucent status.
package com.project.newsapp.utils;
import android.app.Activity;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import ndroid.annotation.ColorInt;
import ndroid.annotation.ColorRes;

public class Util {


public static final String APP_NAME = “NEWS_APP”;
public static final String API_BASE_URL = “http://newsapi.org/”;
public static final String COUNTRY_PREF = “countryPref”;
public static void setSystemBarColor(Activity act, @ColorRes int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = act.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BAC
KGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(act.getResources().getColor(color));
}
}

public static void setSystemBarLight(Activity act) {

Dept. of cse 38
2021-22 NEWS APP

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


View view = act.findViewById(android.R.id.content);
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
}
}

public static void changeMenuIconColor(Menu menu, @ColorInt int color) {


for (int I = 0; I < menu.size(); i++) {
Drawable drawable = menu.getItem(i).getIcon();
if (drawable == null) continue;
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}
}

MainModelView.java

In this java file we are going to define Model View of the application with help of retrofit
library and it is imported in the gradle build. And importing the all the java files created
above. Retrofit is a type-safe HTTP client for java and Android. It is super fast and better
functionality, and simpler syntax. here it get the access to the News Api Id of the developers
as the client and it request through the news api.org and provide the news with the website
from the server.

package com.project.newsapp.viewmodels;

import android.lifecycle.MutableLiveData;
import android.lifecycle.ViewModel;

import com.project.newsapp.model.News;
import com.project.newsapp.model.TotalNews;
import com.project.newsapp.restapi.ApiClient;
import com.project.newsapp.restapi.RestInterface;
import com.project.newsapp.utils.Util;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainViewModel extends ViewModel {

private MutableLiveData<List<News>> newsLiveData;


private List<News> newsList;

Dept. of cse 39
2021-22 NEWS APP

private String countryCode;


private String apiKey;

public MainViewModel() {
newsLiveData = new MutableLiveData<>();
newsList = new ArrayList<>();
}

public void setApiKey(String apiKey) {


this.apiKey = apiKey;
}

public void setCountryCode(String countryCode) {


this.countryCode = countryCode;
getNews(countryCode, “”);
}

public MutableLiveData<List<News>> getNewsLiveData() {


return newsLiveData;
}

private RestInterface getRestInterface() {


RestInterface[] restInterface = new RestInterface[1];
restInterface[0] =
ApiClient.getClient(Util.API_BASE_URL).create(RestInterface.class);
return restInterface[0];
}

private void getNews(String langCode, String category) {


RestInterface restInterface = getRestInterface();
Call<TotalNews> call;
newsList.clear();
newsLiveData.setValue(null);
if (!category.equals(“”)) {
call = restInterface.getTotalNews(langCode, category, apiKey);
} else {
call = restInterface.getTotalNews(langCode, apiKey);
}
call.enqueue(new Callback<TotalNews>() {
@Override
public void onResponse(Call<TotalNews> call, Response<TotalNews> response) {
if (response.body() != null) {
TotalNews totalNews = response.body();
fillNewsList(totalNews);
}
}

@Override
public void onFailure(Call<TotalNews> call, Throwable t) {
newsLiveData.setValue(null);

Dept. of cse 40
2021-22 NEWS APP

}
});
}

private void getSearchedNews(String keyword) {


RestInterface restInterface = getRestInterface();
Call<TotalNews> call;
newsList.clear();
newsLiveData.setValue(null);
call = restInterface.getSearchedTotalNews(keyword, apiKey);

call.enqueue(new Callback<TotalNews>() {
@Override
public void onResponse(Call<TotalNews> call, Response<TotalNews> response) {
if (response.body() != null) {
TotalNews totalNews = response.body();
fillNewsList(totalNews);
}
}

@Override
public void onFailure(Call<TotalNews> call, Throwable t) {
newsLiveData.setValue(null);
}
});
}

private void fillNewsList(TotalNews totalNews) {


newsList.addAll(totalNews.getNewsList());
newsLiveData.setValue(newsList);
}

public void newsCategoryClick(Object category) {


getNews(countryCode, String.valueOf(category));
}

public void searchNews(String keyword) {


getSearchedNews(keyword);
}
}
dialog_header_polygon.xml

In this xml file we are going to create a dialog header for displaying the short
news and asking user to click “cancel” or “Go to website”. Which indeed
redirect the page to particular website with the help of developers News Api
Id.

Dept. of cse 41
2021-22 NEWS APP

<?xml version=”1.0” encoding=”utf-8”?>


<layout xmlns:bind=”http://schemas.android.com/tools”>

<data class=”NewsDialogBinding”>

<variable
name=”listener”
type=”com.project.newsapp.clicklisteners.NewsDialogClickListeners” />

<variable
name=”news”
type=”com.project.newsapp.model.News” />
</data>

<ndroid.cardview.widget.CardView
xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:app=”http://schemas.android.com/apk/res-auto”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
app:cardBackgroundColor=”@android:color/white”
app:cardCornerRadius=”@dimen/spacing_xmedium”
app:cardElevation=”3dp”
app:cardUseCompatPadding=”true”>

<LinearLayout
android:layout_width=”320dp”
android:layout_height=”wrap_content”
android:orientation=”vertical”>

<ImageView
android:layout_width=”match_parent”
android:layout_height=”220dp”
android:scaleType=”centerCrop”
bind:imgUrl=”@{news.newsImage}” />

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”
android:padding=”@dimen/spacing_large”>

<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”@{news.newsTitle}”
android:textAppearance=”@style/TextAppearance.AppCompat.Title”
android:textColor=”@color/grey_90” />

<TextView

Dept. of cse 42
2021-22 NEWS APP

android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_medium”
android:text=”@{news.newsDescription}”
android:textAppearance=”@style/TextAppearance.AppCompat.Subhead”
android:textColor=”@color/grey_60” />

<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”@dimen/spacing_medium”
android:textStyle=”bold”
android:gravity=”center”
android:text=”@string/news_dialog_info”
android:textAppearance=”@style/TextAppearance.AppCompat.Subhead”
android:textColor=”@color/grey_60” />

</LinearLayout>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_margin=”@dimen/spacing_medium”
android:gravity=”end”
android:orientation=”horizontal”>

<ndroid.appcompat.widget.AppCompatButton
android:id=”@+id/bt_decline”
style=”@style/Button.Primary.Borderless”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:gravity=”center”
android:text=”@string/cancel”
android:onClick=”@{()->listener.onDismissClick()}”
android:textColor=”@color/colorAccent” />

<ndroid.appcompat.widget.AppCompatButton
style=”@style/Button.Primary.Borderless”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:gravity=”center”
android:onClick=”@{()-> listener.onGotoWebSiteClick(news.newsUrl)}”
android:text=”@string/goto_website”
android:textColor=”@color/colorPrimary” />

</LinearLayout>

</LinearLayout>

Dept. of cse 43
2021-22 NEWS APP

</ndroid.cardview.widget.CardView>

</layout>

item_news_dashboard.xml
In this xml file we will put dashboard settings for the news displaying with linear layout and
the image view at the top right corner of the layout.
<?xml version=”1.0” encoding=”utf-8”?>
<layout xmlns:bind=”http://schemas.android.com/tools”>

<data class=”NewsBinding”>

<variable
name=”news”
type=”com.project.newsapp.model.News” />

<variable
name=”clickListener”
type=”com.project.newsapp.clicklisteners.AdapterItemClickListener” />

</data>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:app=”http://schemas.android.com/apk/res-auto”
android:id=”@+id/lyt_parent”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:background=”?attr/selectableItemBackground”
android:clickable=”true”
android:focusable=”true”
android:onClick=”@{()-> clickListener.onNewsItemClick(news)}”
android:orientation=”vertical”
android:paddingLeft=”@dimen/spacing_large”
android:paddingTop=”@dimen/spacing_medium”
android:paddingRight=”@dimen/spacing_large”
android:paddingBottom=”@dimen/spacing_medium”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”100dp”
android:orientation=”horizontal”>

<ndroid.cardview.widget.CardView
android:layout_width=”100dp”
android:layout_height=”match_parent”
android:clipToPadding=”true”
app:cardCornerRadius=”8dp”
app:cardElevation=”0dp”
app:cardPreventCornerOverlap=”false”

Dept. of cse 44
2021-22 NEWS APP

app:cardUseCompatPadding=”false”>

<ImageView
android:id=”@+id/newsImage”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:scaleType=”centerCrop”
bind:imgUrl=”@{news.newsImage}” />

</ndroid.cardview.widget.CardView>

<View
android:layout_width=”@dimen/spacing_large”
android:layout_height=”0dp” />

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”>

<TextView
android:id=”@+id/newsTitle”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:maxLines=”3”
android:text=”@{news.newsTitle}”
android:textAppearance=”@style/TextAppearance.AppCompat.Subhead”
android:textColor=”@color/grey_80”
app:fontFamily=”sans-serif-medium” />

<View
android:layout_width=”0dp”
android:layout_height=”0dp”
android:layout_weight=”1” />

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”>

<TextView
android:id=”@+id/newsSourceName”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”@{news.source.sourceName}”
android:textAllCaps=”true”

android:textAppearance=”@style/TextAppearance.AppCompat.Caption”
android:textColor=”@color/grey_40”
app:fontFamily=”sans-serif-medium” />

Dept. of cse 45
2021-22 NEWS APP

<View
android:layout_width=”0dp”
android:layout_height=”0dp”
android:layout_weight=”1” />

<TextView
android:id=”@+id/newsPublishDate”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”@{news.newsPublishedDate}”

android:textAppearance=”@style/TextAppearance.AppCompat.Caption”
android:textColor=”@color/grey_40” />

</LinearLayout>

</LinearLayout>

</LinearLayout>

<View
android:layout_width=”match_parent”
android:layout_height=”1dp”
android:layout_marginTop=”@dimen/spacing_middle”
android:background=”@color/grey_5” />

</LinearLayout>

</layout>

Strings.xml
In this xml file, it describes the country and language for this application, and given the
developers News Api Id to translate and get news from the website or browser.
<resources>
<string name=”app_name”>News App</string>
<string name=”news_api_key”
translatable=”false”>d7645b075ced4727aa4e9480105b4777</string>
<string name=”cancel”>Cancel</string>
<string name=”ok”>OK</string>
<string name=”category_business”>Business</string>
<string name=”category_entertainment”>Entertainment</string>
<string name=”category_health”>Health</string>
<string name=”category_science”>Science</string>
<string name=”category_sports”>Sports</string>
<string name=”category_technology”>Technology</string>
<string name=”news”>News</string>
<string name=”news_dialog_info”>Go to Website for more details.</string>

Dept. of cse 46
2021-22 NEWS APP

<string name=”goto_website”>Go to Website</string>


<string name=”search_in_everything”>Search in everything…</string>
</resources>

CHAPTER 5

RESULT AND DISCUSSION


5.1 Screen Shots

The Fig 5.1 shows the Home page. Here the user can view the news of their region with the
categories like Business, science, Sports, health, technology. And user can view the latest
news headlines here and able to change the language by changing the country at the top

Dept. of cse 47
2021-22 NEWS APP

right side of the layout. And at the top left side of the layout user can search the news by
clicking search icon.

Fig 5.1 Home page

The Fig 5.2 shows the search engine to search for the news in the Home Page of the app.

Fig 5.2 Search engine

The Fig 5.3 shows the dialog box for selecting the country to view the respected country
news by clicking on the Radio Button where country name is specified that country news or
latest news of that country will display in the home screen.

Dept. of cse 48
2021-22 NEWS APP

Fig 5.3 choose Country

The Fig 5.4 showing the news headlines from the home page and it is the header part of the
news article which is showing short news of the article and asking user to view or cancel the
page. If user want to see the full article by clicking the “Go to website” the user can view
the full article from the website of the news publication.

Fig 5.4 Short news

Dept. of cse 49
2021-22 NEWS APP

The Fig 5.5 shows the security and conformation of the website for the user experiences.
In this application every news which is clicked to “Go to website” will ask the user to
Accept the cookies from the website for security of user action. after accepting cookies the
news article will be displayed.

Fig 5.5 User permission

the Fig 5.6 showing full news article.

Fig 5.6 Full Article


Dept. of cse 50
2021-22 NEWS APP

CHAPTER 6

CONCLUSION AND FUTURE ENHANCEMENTS

Currently there are many news application in the market and which provide the latest
information about the events business sports education culture and many more sectors in the
entire world and this is fastest way that people can able to know or educate themselves.
In this application we tried to implement the basic categories that the people should be
aware of. And with the country language the native reader can read the news article in their
own language. And able analyse the facts and the actions of the world which is moving
faster in every second. this allocation make sures that the news is from trusted website and
asks user to get the information if they needed or not. And user can enjoy the news and get
educated and get awareness and make awareness among themselves by sharing the news
with their friends, family etc.
Generally news lets us to know more about world and provide us every single information
of every region. To know more to be good among.
Future Enhancements
Location feature with automation can be implemented which means as user move from one
city to other local news will change as per it. Offline Reading can be improve will more
efficient way on full articles. Data quality check needed. If API can’t reach to certain article
source it gives null value which can cause problem in JSON parsing

Dept. of cse 51
2021-22 NEWS APP

BIBLIOGRAPHY

1. Google Developer Training, "Android Developer Fundamentals Course – Concept


Reference”, Google Developer Training Team, 2017.
https://www.gitbook.com/book/googledeveloper- training/android
developer fundamentals-course-concepts/details.
2. Erik Hellman, “Android Programming – Pushing the Limits”.
3. Dawn Griffiths and David Griffiths, “Head First Android Development”.
4. J F DiMarzio, “Beginning Android Programming with Android Studio”.
5. Anubhav Pradhan, Anil V Deshpande, “Composing Mobile Apps” using Android.
www.github,com
https://newsapi.org
www.google.com
https://stackoverflow.com

Dept. of cse 52

You might also like