Tutorial Membuat Aplikasi Berita Indonesia Android |
Pada sampel aplikasi berita ini, saya menyematkan beberapa topik berita antara lain :
- Berita Utama / Headlines
- Berita Olahraga
- Berita Teknologi
- Berita Bisnis
- Berita Kesehatan
- dan Berita Hiburan
- Menggunakan API dari News API https://newsapi.org/
- Menggunakan Fast Android Networking untuk Rest API
- Menggunakan Glide untuk menampilkan gambar
- Menggunakan Webview untuk View Berita
Untuk kalian yang ingin mencoba tutorial aplikasi ini dengan versi video, berikut saya berikan Videonya:
Jangan lupa subscribe Channel Youtube saya juga ya Azhar Rivaldi, karena disana ada banyak tutorial-tutorial untuk membuat aplikasi lainnya. Oke langsung saja tanpa basa-basi lagi kita langsung ke langkah pertama :
1. Buat project baru di Android Studio dengan cara klik File ⇒ Project Baru. Ketika diminta untuk memilih Default Activity, pilih Empty Activity dan klik next. Untuk minSDK, disini saya set API 21 ya.
2. Tambahkan beberapa library di build.gradle :
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
implementation 'com.amitshekhar.android:android-networking:1.0.2'
}
3. Ubah AndroidManifest.xml menjadi seperti ini :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.azhar.indonews">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="AllowBackup,GoogleAppIndexingWarning,UnusedAttribute">
<activity android:name=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activities.EntertaimentActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activities.HealthActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activities.BusinessActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activities.TechnologyActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activities.HeadLineActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activities.SportsNewsActivity"
android:screenOrientation="portrait" />
<activity
android:name=".activities.OpenNewsActivity"
android:screenOrientation="portrait" />
</application>
</manifest>
4. Ubah MainActivity.java menjadi seperti ini :
package com.azhar.indonews.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.TextView;
import com.azhar.indonews.R;
import com.google.android.material.card.MaterialCardView;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MaterialCardView cvHead, cvSports, cvTechno, cvBusiness, cvHealth, cvEntertaiment;
TextView tvToday;
String hariIni;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cvHead = findViewById(R.id.cardHeadLine);
cvSports = findViewById(R.id.cardSports);
cvTechno = findViewById(R.id.cardTechno);
cvBusiness = findViewById(R.id.cardBusiness);
cvHealth = findViewById(R.id.cardHealth);
cvEntertaiment = findViewById(R.id.cardEnter);
cvHead.setOnClickListener(this);
cvSports.setOnClickListener(this);
cvTechno.setOnClickListener(this);
cvBusiness.setOnClickListener(this);
cvHealth.setOnClickListener(this);
cvEntertaiment.setOnClickListener(this);
tvToday = findViewById(R.id.tvDate);
Date dateNow = Calendar.getInstance().getTime();
hariIni = (String) DateFormat.format("EEEE", dateNow);
if (hariIni.equalsIgnoreCase("sunday")) {
hariIni = "Minggu";
} else if (hariIni.equalsIgnoreCase("monday")) {
hariIni = "Senin";
} else if (hariIni.equalsIgnoreCase("tuesday")) {
hariIni = "Selasa";
} else if (hariIni.equalsIgnoreCase("wednesday")) {
hariIni = "Rabu";
} else if (hariIni.equalsIgnoreCase("thursday")) {
hariIni = "Kamis";
} else if (hariIni.equalsIgnoreCase("friday")) {
hariIni = "Jumat";
} else if (hariIni.equalsIgnoreCase("saturday")) {
hariIni = "Sabtu";
}
getToday();
}
private void getToday() {
Date date = Calendar.getInstance().getTime();
String tanggal = (String) DateFormat.format("d", date);
String monthNumber = (String) DateFormat.format("M", date);
String year = (String) DateFormat.format("yyyy", date);
int month = Integer.parseInt(monthNumber);
String bulan = null;
if (month == 1) {
bulan = "Januari";
} else if (month == 2) {
bulan = "Februari";
} else if (month == 3) {
bulan = "Maret";
} else if (month == 4) {
bulan = "April";
} else if (month == 5) {
bulan = "Mei";
} else if (month == 6) {
bulan = "Juni";
} else if (month == 7) {
bulan = "Juli";
} else if (month == 8) {
bulan = "Agustus";
} else if (month == 9) {
bulan = "September";
} else if (month == 10) {
bulan = "Oktober";
} else if (month == 11) {
bulan = "November";
} else if (month == 12) {
bulan = "Desember";
}
String formatFix = hariIni + ", " + tanggal + " " + bulan + " " + year;
tvToday.setText(formatFix);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.cardHeadLine) {
Intent intent = new Intent(MainActivity.this, HeadLineActivity.class);
startActivity(intent);
} else if (v.getId() == R.id.cardSports) {
Intent intent = new Intent(MainActivity.this, SportsNewsActivity.class);
startActivity(intent);
} else if (v.getId() == R.id.cardTechno) {
Intent intent = new Intent(MainActivity.this, TechnologyActivity.class);
startActivity(intent);
} else if (v.getId() == R.id.cardBusiness) {
Intent intent = new Intent(MainActivity.this, BusinessActivity.class);
startActivity(intent);
} else if (v.getId() == R.id.cardHealth) {
Intent intent = new Intent(MainActivity.this, HealthActivity.class);
startActivity(intent);
} else if (v.getId() == R.id.cardEnter) {
Intent intent = new Intent(MainActivity.this, EntertaimentActivity.class);
startActivity(intent);
}
}
}
5. Untuk tampilan menu utama, buat activity_main.xml dan item_main_grid.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/toolbarMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_home_wave"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="@+id/rlAppName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="10dp"
android:text="@string/title_header_main"
android:textColor="@android:color/white"
android:textSize="16sp" />
</RelativeLayout>
<com.google.android.material.card.MaterialCardView
android:id="@+id/cvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center"
android:layout_marginEnd="-20dp"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imgDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:src="@drawable/ic_date" />
<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginStart="5dp"
android:layout_marginEnd="25dp"
android:layout_toEndOf="@id/imgDate"
android:text="Minggu, 20 Oktober 2020"
android:textColor="@color/colorPrimary"
android:textSize="12sp" />
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
</FrameLayout>
<LinearLayout
android:id="@+id/llCurved"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_below="@+id/toolbarMain"
android:background="@drawable/bg_home_curve"
android:orientation="horizontal" />
<include layout="@layout/item_main_grid" />
<TextView
android:id="@+id/appName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:elevation="5dp"
android:text="Apps Berita Indonesia by Azhar Rivaldi"
android:textColor="@color/colorAccent"
android:textSize="10sp" />
</RelativeLayout>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/llCurved">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardHeadLine"
android:layout_width="150.0dip"
android:layout_height="150.0dip"
android:layout_margin="10dp"
app:cardCornerRadius="10.0dip"
app:cardElevation="5.0dip"
app:strokeColor="@android:color/holo_orange_light"
app:strokeWidth="2.0dip">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:padding="10dp"
android:src="@drawable/ic_headlines"
android:tint="@android:color/holo_orange_light" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Berita Utama"
android:textColor="@android:color/holo_orange_light"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_margin="5dp"
android:orientation="horizontal">
<View
android:layout_width="100dp"
android:layout_height="3dp"
android:background="@android:color/holo_orange_light" />
<View
android:layout_width="10dp"
android:layout_height="3dp"
android:layout_marginStart="3dp"
android:background="@android:color/holo_orange_light" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardSports"
android:layout_width="150.0dip"
android:layout_height="150.0dip"
android:layout_margin="10dp"
app:cardCornerRadius="10.0dip"
app:cardElevation="5.0dip"
app:strokeColor="@android:color/holo_red_dark"
app:strokeWidth="2.0dip">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:padding="10dp"
android:src="@drawable/ic_sports"
android:tint="@android:color/holo_red_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Olahraga"
android:textColor="@android:color/holo_red_dark"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_margin="5dp"
android:orientation="horizontal">
<View
android:layout_width="100dp"
android:layout_height="3dp"
android:background="@android:color/holo_red_dark" />
<View
android:layout_width="10dp"
android:layout_height="3dp"
android:layout_marginStart="3dp"
android:background="@android:color/holo_red_dark" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardTechno"
android:layout_width="150.0dip"
android:layout_height="150.0dip"
android:layout_margin="10dp"
app:cardCornerRadius="10.0dip"
app:cardElevation="5.0dip"
app:strokeColor="@android:color/holo_purple"
app:strokeWidth="2.0dip">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:padding="10dp"
android:src="@drawable/ic_technology"
android:tint="@android:color/holo_purple" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Teknologi"
android:textColor="@android:color/holo_purple"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_margin="5dp"
android:orientation="horizontal">
<View
android:layout_width="100dp"
android:layout_height="3dp"
android:background="@android:color/holo_purple" />
<View
android:layout_width="10dp"
android:layout_height="3dp"
android:layout_marginStart="3dp"
android:background="@android:color/holo_purple" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardBusiness"
android:layout_width="150.0dip"
android:layout_height="150.0dip"
android:layout_margin="10dp"
app:cardCornerRadius="10.0dip"
app:cardElevation="5.0dip"
app:strokeColor="@android:color/black"
app:strokeWidth="2.0dip">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:padding="10dp"
android:src="@drawable/ic_business"
android:tint="@android:color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Bisnis"
android:textColor="@android:color/black"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_margin="5dp"
android:orientation="horizontal">
<View
android:layout_width="100dp"
android:layout_height="3dp"
android:background="@android:color/black" />
<View
android:layout_width="10dp"
android:layout_height="3dp"
android:layout_marginStart="3dp"
android:background="@android:color/black" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardHealth"
android:layout_width="150.0dip"
android:layout_height="150.0dip"
android:layout_margin="10dp"
app:cardCornerRadius="10.0dip"
app:cardElevation="5.0dip"
app:strokeColor="@android:color/holo_green_dark"
app:strokeWidth="2.0dip">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:padding="10dp"
android:src="@drawable/ic_health"
android:tint="@android:color/holo_green_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Kesehatan"
android:textColor="@android:color/holo_green_dark"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_margin="5dp"
android:orientation="horizontal">
<View
android:layout_width="100dp"
android:layout_height="3dp"
android:background="@android:color/holo_green_dark" />
<View
android:layout_width="10dp"
android:layout_height="3dp"
android:layout_marginStart="3dp"
android:background="@android:color/holo_green_dark" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardEnter"
android:layout_width="150.0dip"
android:layout_height="150.0dip"
android:layout_margin="10dp"
app:cardCornerRadius="10.0dip"
app:cardElevation="5.0dip"
app:strokeColor="@color/colorPrimary"
app:strokeWidth="2.0dip">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:padding="10dp"
android:src="@drawable/ic_entertaiment"
android:tint="@color/colorPrimary" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Hiburan"
android:textColor="@color/colorPrimary"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_margin="5dp"
android:orientation="horizontal">
<View
android:layout_width="100dp"
android:layout_height="3dp"
android:background="@color/colorPrimary" />
<View
android:layout_width="10dp"
android:layout_height="3dp"
android:layout_marginStart="3dp"
android:background="@color/colorPrimary" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
</LinearLayout>
</ScrollView>
6. Buat Class BusinessActivity.java untuk berita bisnis :
package com.azhar.indonews.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.azhar.indonews.R;
import com.azhar.indonews.adapter.NewsAdapter;
import com.azhar.indonews.api.NewsApi;
import com.azhar.indonews.model.ModelNews;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class BusinessActivity extends AppCompatActivity implements NewsAdapter.onSelectData {
RecyclerView rvBusiness;
NewsAdapter newsAdapter;
List modelNews = new ArrayList<>();
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Mohon tunggu");
progressDialog.setCancelable(false);
progressDialog.setMessage("Sedang menampilkan data");
rvBusiness = findViewById(R.id.rvNews);
rvBusiness.setHasFixedSize(true);
rvBusiness.setLayoutManager(new LinearLayoutManager(this));
setupToolbar();
loadJSON();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.tbNews);
toolbar.setTitle("Berita Bisnis");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadJSON() {
progressDialog.show();
AndroidNetworking.get(NewsApi.GET_CATEGORY_BUSINESS)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONArray playerArray = response.getJSONArray("articles");
for (int i = 0; i < playerArray.length(); i++) {
JSONObject temp = playerArray.getJSONObject(i);
ModelNews dataApi = new ModelNews();
dataApi.setTitle(temp.getString("title"));
dataApi.setUrl(temp.getString("url"));
dataApi.setPublishedAt(temp.getString("publishedAt"));
dataApi.setUrlToImage(temp.getString("urlToImage"));
modelNews.add(dataApi);
showNews();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(BusinessActivity.this, "Gagal menampilkan data!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(ANError anError) {
progressDialog.dismiss();
Toast.makeText(BusinessActivity.this, "Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show();
}
});
}
private void showNews() {
newsAdapter = new NewsAdapter(BusinessActivity.this, modelNews, this);
rvBusiness.setAdapter(newsAdapter);
}
@Override
public void onSelected(ModelNews mdlNews) {
startActivity(new Intent(BusinessActivity.this, OpenNewsActivity.class).putExtra("url", mdlNews.getUrl()));
}
}
7. Buat Class EntertaimentActivity.java untuk berita hiburan :
package com.azhar.indonews.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.azhar.indonews.R;
import com.azhar.indonews.adapter.NewsAdapter;
import com.azhar.indonews.api.NewsApi;
import com.azhar.indonews.model.ModelNews;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class EntertaimentActivity extends AppCompatActivity implements NewsAdapter.onSelectData {
RecyclerView rvEntertaiment;
NewsAdapter newsAdapter;
List modelNews = new ArrayList<>();
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Mohon tunggu");
progressDialog.setCancelable(false);
progressDialog.setMessage("Sedang menampilkan data");
rvEntertaiment = findViewById(R.id.rvNews);
rvEntertaiment.setHasFixedSize(true);
rvEntertaiment.setLayoutManager(new LinearLayoutManager(this));
setupToolbar();
loadJSON();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.tbNews);
toolbar.setTitle("Berita Hiburan");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadJSON() {
progressDialog.show();
AndroidNetworking.get(NewsApi.GET_CATEGORY_ENTERTAINMENT)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONArray playerArray = response.getJSONArray("articles");
for (int i = 0; i < playerArray.length(); i++) {
JSONObject temp = playerArray.getJSONObject(i);
ModelNews dataApi = new ModelNews();
dataApi.setTitle(temp.getString("title"));
dataApi.setUrl(temp.getString("url"));
dataApi.setPublishedAt(temp.getString("publishedAt"));
dataApi.setUrlToImage(temp.getString("urlToImage"));
modelNews.add(dataApi);
showNews();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(EntertaimentActivity.this, "Gagal menampilkan data!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(ANError anError) {
progressDialog.dismiss();
Toast.makeText(EntertaimentActivity.this, "Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show();
}
});
}
private void showNews() {
newsAdapter = new NewsAdapter(EntertaimentActivity.this, modelNews, this);
rvEntertaiment.setAdapter(newsAdapter);
}
@Override
public void onSelected(ModelNews mdlNews) {
startActivity(new Intent(EntertaimentActivity.this, OpenNewsActivity.class).putExtra("url", mdlNews.getUrl()));
}
}
8. Buat Class HeadLineActivity.java untuk berita utama :
package com.azhar.indonews.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.azhar.indonews.R;
import com.azhar.indonews.adapter.NewsAdapter;
import com.azhar.indonews.api.NewsApi;
import com.azhar.indonews.model.ModelNews;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class HeadLineActivity extends AppCompatActivity implements NewsAdapter.onSelectData {
RecyclerView rvHeadNews;
NewsAdapter newsAdapter;
List modelNews = new ArrayList<>();
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Mohon tunggu");
progressDialog.setCancelable(false);
progressDialog.setMessage("Sedang menampilkan data");
rvHeadNews = findViewById(R.id.rvNews);
rvHeadNews.setHasFixedSize(true);
rvHeadNews.setLayoutManager(new LinearLayoutManager(this));
setupToolbar();
loadJSON();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.tbNews);
toolbar.setTitle("Berita Utama");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadJSON() {
progressDialog.show();
AndroidNetworking.get(NewsApi.GET_TOP_HEADLINES)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONArray playerArray = response.getJSONArray("articles");
for (int i = 0; i < playerArray.length(); i++) {
JSONObject temp = playerArray.getJSONObject(i);
ModelNews dataApi = new ModelNews();
dataApi.setTitle(temp.getString("title"));
dataApi.setUrl(temp.getString("url"));
dataApi.setPublishedAt(temp.getString("publishedAt"));
dataApi.setUrlToImage(temp.getString("urlToImage"));
modelNews.add(dataApi);
showNews();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(HeadLineActivity.this, "Gagal menampilkan data!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(ANError anError) {
progressDialog.dismiss();
Toast.makeText(HeadLineActivity.this, "Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show();
}
});
}
private void showNews() {
newsAdapter = new NewsAdapter(HeadLineActivity.this, modelNews, this);
rvHeadNews.setAdapter(newsAdapter);
}
@Override
public void onSelected(ModelNews mdlNews) {
startActivity(new Intent(HeadLineActivity.this, OpenNewsActivity.class).putExtra("url", mdlNews.getUrl()));
}
}
9. Buat Class HealthActivity.java untuk berita kesehatan :
package com.azhar.indonews.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.azhar.indonews.R;
import com.azhar.indonews.adapter.NewsAdapter;
import com.azhar.indonews.api.NewsApi;
import com.azhar.indonews.model.ModelNews;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class HealthActivity extends AppCompatActivity implements NewsAdapter.onSelectData {
RecyclerView rvHealth;
NewsAdapter newsAdapter;
List modelNews = new ArrayList<>();
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Mohon tunggu");
progressDialog.setCancelable(false);
progressDialog.setMessage("Sedang menampilkan data");
rvHealth = findViewById(R.id.rvNews);
rvHealth.setHasFixedSize(true);
rvHealth.setLayoutManager(new LinearLayoutManager(this));
setupToolbar();
loadJSON();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.tbNews);
toolbar.setTitle("Berita Kesehatan");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadJSON() {
progressDialog.show();
AndroidNetworking.get(NewsApi.GET_CATEGORY_HEALTH)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONArray playerArray = response.getJSONArray("articles");
for (int i = 0; i < playerArray.length(); i++) {
JSONObject temp = playerArray.getJSONObject(i);
ModelNews dataApi = new ModelNews();
dataApi.setTitle(temp.getString("title"));
dataApi.setUrl(temp.getString("url"));
dataApi.setPublishedAt(temp.getString("publishedAt"));
dataApi.setUrlToImage(temp.getString("urlToImage"));
modelNews.add(dataApi);
showNews();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(HealthActivity.this, "Gagal menampilkan data!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(ANError anError) {
progressDialog.dismiss();
Toast.makeText(HealthActivity.this, "Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show();
}
});
}
private void showNews() {
newsAdapter = new NewsAdapter(HealthActivity.this, modelNews, this);
rvHealth.setAdapter(newsAdapter);
}
@Override
public void onSelected(ModelNews mdlNews) {
startActivity(new Intent(HealthActivity.this, OpenNewsActivity.class).putExtra("url", mdlNews.getUrl()));
}
}
10. Buat Class SportsNewsActivity.java untuk berita olahraga :
package com.azhar.indonews.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.azhar.indonews.R;
import com.azhar.indonews.adapter.NewsAdapter;
import com.azhar.indonews.api.NewsApi;
import com.azhar.indonews.model.ModelNews;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class SportsNewsActivity extends AppCompatActivity implements NewsAdapter.onSelectData {
RecyclerView rvSportNews;
NewsAdapter newsAdapter;
List modelNews = new ArrayList<>();
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Mohon tunggu");
progressDialog.setCancelable(false);
progressDialog.setMessage("Sedang menampilkan data");
rvSportNews = findViewById(R.id.rvNews);
rvSportNews.setHasFixedSize(true);
rvSportNews.setLayoutManager(new LinearLayoutManager(this));
setupToolbar();
loadJSON();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.tbNews);
toolbar.setTitle("Berita Olahraga");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadJSON() {
progressDialog.show();
AndroidNetworking.get(NewsApi.GET_CATEGORY_SPORTS)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONArray playerArray = response.getJSONArray("articles");
for (int i = 0; i < playerArray.length(); i++) {
JSONObject temp = playerArray.getJSONObject(i);
ModelNews dataApi = new ModelNews();
dataApi.setTitle(temp.getString("title"));
dataApi.setUrl(temp.getString("url"));
dataApi.setPublishedAt(temp.getString("publishedAt"));
dataApi.setUrlToImage(temp.getString("urlToImage"));
modelNews.add(dataApi);
showNews();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SportsNewsActivity.this, "Gagal menampilkan data!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(ANError anError) {
progressDialog.dismiss();
Toast.makeText(SportsNewsActivity.this, "Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show();
}
});
}
private void showNews() {
newsAdapter = new NewsAdapter(SportsNewsActivity.this, modelNews, this);
rvSportNews.setAdapter(newsAdapter);
}
@Override
public void onSelected(ModelNews mdlNews) {
startActivity(new Intent(SportsNewsActivity.this, OpenNewsActivity.class).putExtra("url", mdlNews.getUrl()));
}
}
11. Yang terakhir buat Class TechnologyActivity.java untuk berita teknologi :
package com.azhar.indonews.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.azhar.indonews.R;
import com.azhar.indonews.adapter.NewsAdapter;
import com.azhar.indonews.api.NewsApi;
import com.azhar.indonews.model.ModelNews;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class TechnologyActivity extends AppCompatActivity implements NewsAdapter.onSelectData {
RecyclerView rvTechno;
NewsAdapter newsAdapter;
List modelNews = new ArrayList<>();
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Mohon tunggu");
progressDialog.setCancelable(false);
progressDialog.setMessage("Sedang menampilkan data");
rvTechno = findViewById(R.id.rvNews);
rvTechno.setHasFixedSize(true);
rvTechno.setLayoutManager(new LinearLayoutManager(this));
setupToolbar();
loadJSON();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.tbNews);
toolbar.setTitle("Berita Teknologi");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadJSON() {
progressDialog.show();
AndroidNetworking.get(NewsApi.GET_CATEGORY_TECHNOLOGY)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONArray playerArray = response.getJSONArray("articles");
for (int i = 0; i < playerArray.length(); i++) {
JSONObject temp = playerArray.getJSONObject(i);
ModelNews dataApi = new ModelNews();
dataApi.setTitle(temp.getString("title"));
dataApi.setUrl(temp.getString("url"));
dataApi.setPublishedAt(temp.getString("publishedAt"));
dataApi.setUrlToImage(temp.getString("urlToImage"));
modelNews.add(dataApi);
showNews();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(TechnologyActivity.this, "Gagal menampilkan data!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(ANError anError) {
progressDialog.dismiss();
Toast.makeText(TechnologyActivity.this, "Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show();
}
});
}
private void showNews() {
newsAdapter = new NewsAdapter(TechnologyActivity.this, modelNews, this);
rvTechno.setAdapter(newsAdapter);
}
@Override
public void onSelected(ModelNews mdlNews) {
startActivity(new Intent(TechnologyActivity.this, OpenNewsActivity.class).putExtra("url", mdlNews.getUrl()));
}
}
12. Untuk menampilkan berita-berita dari source diatas, buat activity_news.xml. Disini saya menggunakan satu XML untuk digunakan beberapa source java berita tadi :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="@android:color/white"
android:fitsSystemWindows="true"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/tbNews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:orientation="vertical"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvNews"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
13. Buat Class OpenNewsActivity.java dan activity_open_news.xml untuk menampilkan detail berita :
package com.azhar.indonews.activities;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.azhar.indonews.R;
/**
* Created by Azhar Rivaldi on 22-12-2019.
*/
public class OpenNewsActivity extends AppCompatActivity {
private ProgressBar mProgressBar;
private WebView mWebView;
String url = "https://www.google.com";
@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//android theme
setContentView(R.layout.activity_open_news);
//android toolbar
setupToolbar();
mProgressBar = findViewById(R.id.progress_bar);
mProgressBar.setMax(100);
url = getIntent().getStringExtra("url");
mWebView = findViewById(R.id.read_news);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
mProgressBar.setProgress(0);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String newUrl) {
view.loadUrl(newUrl);
mProgressBar.setProgress(0);
return true;
}
@Override
public void onPageStarted(WebView view, String urlStart, Bitmap favicon) {
//mProgressBar.setProgress(0);
url = urlStart;
invalidateOptionsMenu();
}
@Override
public void onPageFinished(WebView view, String urlPage) {
mProgressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_open_news, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.share) {//share news
shareUrl(url);
}
return super.onOptionsItemSelected(item);
}
//back pressed
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
//setup toolbar
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.tbOpenNews);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
}
});
}
//share news
private void shareUrl(String url) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
share.putExtra(Intent.EXTRA_TEXT, url);
startActivity(Intent.createChooser(share, "Bagikan ke : "));
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<com.google.android.material.card.MaterialCardView
android:id="@+id/cvNews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardCornerRadius="10dp"
app:cardElevation="3dp"
app:strokeColor="@color/colorPrimary"
app:strokeWidth="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:orientation="horizontal">
<RelativeLayout
android:id="@+id/rl_imgList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerInParent="true">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ImageView
android:id="@+id/image"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="@drawable/ic_image_list" />
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_toEndOf="@id/rl_imgList"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="false"
android:text="Title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="12sp" />
<TextView
android:id="@+id/publishedAt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:singleLine="true"
android:text="Time"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="8sp" />
</LinearLayout>
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
14. Buat Class NewsApi.java untuk API-nya :
package com.azhar.indonews.api;
public class NewsApi {
public static String GET_TOP_HEADLINES = "https://newsapi.org/v2/top-headlines?country=id&apiKey=f3aa09e2f1d7494e9fded68f30d4e4c1";
public static String GET_CATEGORY_SPORTS = "https://newsapi.org/v2/top-headlines?country=id&category=sports&apiKey=f3aa09e2f1d7494e9fded68f30d4e4c1";
public static String GET_CATEGORY_TECHNOLOGY = "https://newsapi.org/v2/top-headlines?country=id&category=technology&apiKey=f3aa09e2f1d7494e9fded68f30d4e4c1";
public static String GET_CATEGORY_BUSINESS = "https://newsapi.org/v2/top-headlines?country=id&category=business&apiKey=f3aa09e2f1d7494e9fded68f30d4e4c1";
public static String GET_CATEGORY_HEALTH = "https://newsapi.org/v2/top-headlines?country=id&category=health&apiKey=f3aa09e2f1d7494e9fded68f30d4e4c1";
public static String GET_CATEGORY_ENTERTAINMENT = "https://newsapi.org/v2/top-headlines?country=id&category=entertainment&apiKey=f3aa09e2f1d7494e9fded68f30d4e4c1";
}
15. Untuk holdernya, buat Class NewsViewHolder.java :
package com.azhar.indonews.holder;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.azhar.indonews.R;
import com.google.android.material.card.MaterialCardView;
/**
* Created by Azhar Rivaldi on 22-12-2019.
*/
public class NewsViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView title;
public TextView publishedAt;
public MaterialCardView cvNews;
public View view;
public NewsViewHolder(View view) {
super(view);
cvNews = view.findViewById(R.id.cvNews);
image = view.findViewById(R.id.image);
title = view.findViewById(R.id.title);
publishedAt = view.findViewById(R.id.publishedAt);
this.view = view;
}
}
16. Untuk modelnya, buat Class ModelNews.java :
package com.azhar.indonews.model;
/**
* Created by Azhar Rivaldi on 22-12-2019.
*/
public class ModelNews {
private String title;
private String publishedAt;
private String url;
private String urlToImage;
public void setTitle(String title) {
this.title = title;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public void setUrl(String url) {
this.url = url;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getTitle() {
return title;
}
public String getPublishedAt() {
return publishedAt;
}
public String getUrl() {
return url;
}
public String getUrlToImage() {
return urlToImage;
}
}
17. Terakhir, buat Class TimeUnits.java untuk konvert waktu berita dari API :
package com.azhar.indonews.utils;
import java.util.Calendar;
public class TimeUnits {
//convert timestamp to time ago
public static String getTimeAgo(String timeStamp) {
String timeAgo = "";
String[] date = timeStamp.replace("T", "-")
.replace("Z", "-")
.replace(":", "-")
.split("-");
int year_a = Integer.parseInt(date[0]);
int month_a = Integer.parseInt(date[1]);
int day_a = Integer.parseInt(date[2]);
int hour_a = Integer.parseInt(getHour(date[3]));
int minute_a = Integer.parseInt(date[4]);
//calendar a / time a (last time / published at )
Calendar cal_a = Calendar.getInstance();
cal_a.set(year_a, month_a, day_a, hour_a, minute_a);
//calendar b / time b (time now)
Calendar cal_b = Calendar.getInstance();
int year_b = cal_b.get(Calendar.YEAR);
int month_b = cal_b.get(Calendar.MONTH) + 1;
int day_b = cal_b.get(Calendar.DAY_OF_MONTH);
int hour_b = cal_b.get(Calendar.HOUR_OF_DAY);
int minute_b = cal_b.get(Calendar.MINUTE);
cal_b.set(year_b, month_b, day_b, hour_b, minute_b);
final long MILIDETIK_SATU_MENIT = 60 * 1000;
long wA = cal_a.getTimeInMillis();
long wB = cal_b.getTimeInMillis();
//selisih
long selisih = wB - wA;
int selisih_menit = (int) (selisih / MILIDETIK_SATU_MENIT);
if (selisih_menit > 0) {
if (selisih_menit > 60 && selisih_menit < 1440) {
int jam = selisih_menit / 60;
timeAgo = jam + " jam yang lalu";
} else if (selisih_menit > 1440) {
int hari = selisih_menit / 1440;
timeAgo = hari + " hari yang lalu";
} else {
timeAgo = selisih_menit + " menit yang lalu";
}
}
return timeAgo;
}
public static String getHour(String hour) {
String result = "";
if (hour.equals("00")) {
result = "07";
} else if (hour.equals("01")) {
result = "08";
} else if (hour.equals("02")) {
result = "09";
} else if (hour.equals("03")) {
result = "10";
} else if (hour.equals("04")) {
result = "11";
} else if (hour.equals("05")) {
result = "12";
} else if (hour.equals("06")) {
result = "13";
} else if (hour.equals("07")) {
result = "14";
} else if (hour.equals("08")) {
result = "15";
} else if (hour.equals("09")) {
result = "16";
} else if (hour.equals("10")) {
result = "17";
} else if (hour.equals("11")) {
result = "18";
} else if (hour.equals("12")) {
result = "19";
} else if (hour.equals("13")) {
result = "20";
} else if (hour.equals("14")) {
result = "21";
} else if (hour.equals("15")) {
result = "22";
} else if (hour.equals("16")) {
result = "23";
} else if (hour.equals("17")) {
result = "00";
} else if (hour.equals("18")) {
result = "01";
} else if (hour.equals("19")) {
result = "02";
} else if (hour.equals("20")) {
result = "03";
} else if (hour.equals("21")) {
result = "04";
} else if (hour.equals("22")) {
result = "05";
} else if (hour.equals("23")) {
result = "06";
}
return result;
}
}
18. Selesai dan kalian Run. Jika kalian mengikuti langkah-langkah diatas dengan baik, pasti aplikasi yang kalian buat akan berjalan sebagaimana mestinya. Namun jika mengalami Error, silahkan berikan komentar dan kita diskusikan bersama.
Untuk hasilnya nanti akan seperti ini :
Tutorial Membuat Aplikasi Berita Indonesia |
Tutorial Membuat Aplikasi Berita Indonesia |
Tags:
Tutorial Android Studio