RE : (Tutorial Android) HTTP Client on Android with Retrofit


Halo semua bagaimana kabarnya?

Pada artikel kali ini saya ingin membahas ulang tutorial Retrofit. Sesuai janji saya memposting ini dikarenakan project dari artikel sebelumnya http://wimsonevel.blogspot.co.id/2016/07/tutorial-android-http-client-on-android.html tidak dapat berfungsi dengan baik. Maka dari itu saya akan membuat ulang project menggunakan Retrofit namun dengan studi kasus yang berbeda.

Pada project kali ini kita menggunakan Free API Database Movie di https://www.themoviedb.org. Untuk mengakses API-nya diperlukan API key, terlebih dahulu harus buat akun. Setelah itu akses ke menu settings di profile, kemudian generate API key di menu API.

Dokumentasi API lengkapnya bisa di https://developers.themoviedb.org/3
Note: API yang kita gunakan versi 3

Beberapa API yang akan kita pakai diantaranya :

1. Popular Movies
Untuk requestnya bisa dilihat di https://developers.themoviedb.org/3/movies/get-popular-movies

Responsenya :
{
"page": 1,
"total_results": 19587,
"total_pages": 980,
"results": [
{
"vote_count": 3593,
"id": 321612,
"video": false,
"vote_average": 6.8,
"title": "Beauty and the Beast",
"popularity": 257.04688,
"poster_path": "/tWqifoYuwLETmmasnGHO7xBjEtt.jpg",
"original_language": "en",
"original_title": "Beauty and the Beast",
"genre_ids": [
10751,
14,
10749
],
"backdrop_path": "/6aUWe0GSl69wMTSWWexsorMIvwU.jpg",
"adult": false,
"overview": "A live-action adaptation of Disney's version of the classic 'Beauty and the Beast' tale of a cursed prince and a beautiful young woman who helps him break the spell.",
"release_date": "2017-03-16"
},

...

]
}
2. Movie Detail
Untuk requestnya bisa dilihat di https://developers.themoviedb.org/3/movies/get-movie-details

Responsenya :
{
"adult": false,
"backdrop_path": "/hA5oCgvgCxj5MEWcLpjXXTwEANF.jpg",
"belongs_to_collection": null,
"budget": 120000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 14,
"name": "Fantasy"
},
{
"id": 878,
"name": "Science Fiction"
}
],
"homepage": "http://www.warnerbros.com/wonder-woman",
"id": 297762,
"imdb_id": "tt0451279",
"original_language": "en",
"original_title": "Wonder Woman",
"overview": "An Amazon princess comes to the world of Man to become the greatest of the female superheroes.",
"popularity": 236.48453,
"poster_path": "/imekS7f1OuHyUP2LAiTEM0zBzUz.jpg",
"production_companies": [
{
"name": "Dune Entertainment",
"id": 444
},
{
"name": "Atlas Entertainment",
"id": 507
},
{
"name": "Warner Bros.",
"id": 6194
},
{
"name": "DC Entertainment",
"id": 9993
},
{
"name": "Cruel & Unusual Films",
"id": 9995
},
{
"name": "TENCENT PICTURES",
"id": 81620
},
{
"name": "Wanda Pictures",
"id": 83838
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "2017-05-30",
"revenue": 573495580,
"runtime": 141,
"spoken_languages": [
{
"iso_639_1": "de",
"name": "Deutsch"
},
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "Power. Grace. Wisdom. Wonder.",
"title": "Wonder Woman",
"video": false,
"vote_average": 7,
"vote_count": 2225
}
3. Trailer
Untuk requestnya bisa dilihat di https://developers.themoviedb.org/3/movies/get-movie-videos

Responsenya :
{
"id": 297762,
"results": [
{
"id": "58ba5869925141609e01849f",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "5lGoQhFb4NM",
"name": "Official Comic-Con Trailer",
"site": "YouTube",
"size": 1080,
"type": "Trailer"
},

...

]
}
4. Review
Untuk requestnya bisa dilihat di https://developers.themoviedb.org/3/movies/get-movie-reviews

Responsenya :
{
"id": 297762,
"page": 1,
"results": [
{
"id": "59303b4c92514166e9000f76",
"author": "Gimly",
"content": "I'd just like to thank Patty Jenkins for making a DCIThoughtSheWasWithUniverse movie that wasn't fucking garbage.\r\n\r\nIf I'm being completely honest, the two people I went to the cinema to watch _Wonder Woman_ with and I did spend the next two hours after coming out of our screening discussing the various problems with the movie, but we also all agreed on one thing: We still loved it.\r\n\r\nMaybe it's just the rose-coloured glasses of comparison, but I had an excellent time with _Wonder Woman_, and I'm excited to go back to the cinema and watch it, at least one more time.\r\n\r\nIt's the first time I've said that about a DC movie since _The Dark Knight Rises_.\r\n\r\n_Final rating:★★★½ - I strongly recommend you make the time._",
"url": "https://www.themoviedb.org/review/59303b4c92514166e9000f76"
},

...

],
"total_pages": 1,
"total_results": 3
}

Buat Project Baru

Buka Android Studio dan buat project baru dengan sistem package sebagai berikut :



Buka gradle, kemudian tambahkan library Retrofit 2. Latest version bisa dilihat di http://square.github.io/retrofit/
compile 'com.squareup.retrofit2:retrofit:2.3.0'
Tambahkan library converter gson agar respon json dapat di-convert dengan gson.
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
Tambahkan library logging untuk memonitor request dan response dari retrofit.
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
Dan juga tambahkan library tambahan lainnya
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
compile 'com.squareup.picasso:picasso:2.5.2'
testCompile 'junit:junit:4.12'
}

Letakkan URL dan API KEY di gradle.properties
BASE_URL = "https://api.themoviedb.org"
MOVIE_API_KEY = "YOUR API KEY"
IMG_URL = "http://image.tmdb.org/t/p/w185"
Letakkan konfigurasi URL dan API KEY di gradle
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "id.co.blogspot.wimsonevel.android_moviedb"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
buildTypes.each {
it.buildConfigField 'String', 'BASE_URL', BASE_URL
it.buildConfigField 'String', 'IMG_URL', IMG_URL
it.buildConfigField 'String', 'MOVIE_API_KEY', MOVIE_API_KEY
}
}

Kemudian tambahkan resources yang diperlukan di folder res.

values/strings.xml
<resources>
<string name="app_name">Movie DB</string>
<string name="most_popular">Most Popular</string>
<string name="movie_detail">Movie Detail</string>
<string name="release_date">Release Date</string>
<string name="duration">Duration</string>
<string name="genre">Genre</string>
<string name="homepage">Homepage</string>
<string name="overview">Overview</string>
<string name="trailers">Trailers</string>
<string name="reviews">Reviews</string>
<string name="title">Title</string>
</resources>
values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#4CAF50</color>
<color name="colorPrimaryDark">#43A047</color>
<color name="colorAccent">#FF4081</color>
<color name="colorWhite">#FFFFFF</color>
<color name="colorGray">#E5E5E5</color>
</resources>

Desain Layout

Buat beberapa layout berikut :
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MergeRootFrame" />
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MergeRootFrame" />
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="?colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<include layout="@layout/toolbar" />

<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/refresh"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.RecyclerView
android:id="@+id/rv_movies"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="1dp"
android:scrollbars="vertical"/>

</android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>
fragment_detail.xml
<?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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<include layout="@layout/toolbar" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">

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

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="10dp">

<TextView
android:id="@+id/movie_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/title"/>

</LinearLayout>

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/colorPrimary"/>

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">

<ImageView
android:id="@+id/img_poster"
android:layout_width="130dp"
android:layout_height="180dp"
android:scaleType="centerCrop"
tools:ignore="ContentDescription" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingRight="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/release_date"/>

<TextView
android:id="@+id/movie_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textStyle="bold"
android:text="@string/duration"/>

<TextView
android:id="@+id/movie_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textStyle="bold"
android:text="@string/genre"/>

<TextView
android:id="@+id/movie_genre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textStyle="bold"
android:text="@string/homepage"/>

<TextView
android:id="@+id/movie_homepage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>
</LinearLayout>

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/colorPrimary"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="10dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/overview"/>

<TextView
android:id="@+id/movie_overview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/colorPrimary"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="10dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/trailers"/>

<ProgressBar
android:id="@+id/pg_trailers"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="gone"/>

<LinearLayout
android:id="@+id/view_trailers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>

</LinearLayout>

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/colorPrimary"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="10dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/reviews"/>

<ProgressBar
android:id="@+id/pg_reviews"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="gone"/>

<LinearLayout
android:id="@+id/view_reviews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>

</LinearLayout>

</LinearLayout>
</ScrollView>

</LinearLayout>
list_item_movie.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ImageView
android:id="@+id/img_thumb"
android:layout_width="match_parent"
android:layout_height="270dp"
android:scaleType="centerCrop"
tools:ignore="ContentDescription" />

</RelativeLayout>
list_item_review.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/reviewers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:textStyle="bold"/>

<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"/>

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/colorGray"/>

</LinearLayout>
list_item_trailer.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="4dp">

<ImageView
android:id="@+id/trailer_thumb"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="centerCrop"
tools:ignore="ContentDescription" />

<TextView
android:id="@+id/trailer_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:padding="4dp"/>

</LinearLayout>

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/colorGray"/>

</LinearLayout>

Buat Kelas Java

Selanjutnya adalah membuat kelas-kelas java. Kelas-kelas yang kita buat dibagi dibeberapa package berikut.

- package model 

BaseModel.java
import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
* Created by Wim on 5/29/17.
*/

public class BaseModel<T> {

@SerializedName("page")
private int page;
@SerializedName("results")
private List<T> results;

public BaseModel() {
}

public int getPage() {
return page;
}

public void setPage(int page) {
this.page = page;
}

public List<T> getResults() {
return results;
}

public void setResults(List<T> results) {
this.results = results;
}

}
Genre.java
import com.google.gson.annotations.SerializedName;

/**
* Created by Wim on 6/2/17.
*/

public class Genre {

@SerializedName("id")
private int id;
@SerializedName("name")
private String name;

public Genre() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
Movie.java
import com.google.gson.annotations.SerializedName;

/**
* Created by Wim on 5/29/17.
*/

public class Movie extends BaseModel<MovieData> {

@SerializedName("total_results")
private int totalResult;
@SerializedName("total_pages")
private int totalPages;

public Movie() {
}

public int getTotalResult() {
return totalResult;
}

public void setTotalResult(int totalResult) {
this.totalResult = totalResult;
}

public int getTotalPages() {
return totalPages;
}

public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}

}
MovieData.java
import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.SerializedName;

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

/**
* Created by Wim on 5/29/17.
*/

public class MovieData implements Parcelable {

@SerializedName("id")
private int id;
@SerializedName("original_title")
private String originalTitle;
@SerializedName("original_language")
private String originalLanguage;
@SerializedName("title")
private String title;
@SerializedName("poster_path")
private String posterPath;
@SerializedName("adult")
private boolean adult;
@SerializedName("overview")
private String overview;
@SerializedName("release_date")
private String releaseDate;
@SerializedName("genre_ids")
private List<Integer> genreIds;
@SerializedName("backdrop_path")
private String backdropPath;
@SerializedName("popularity")
private double popularity;
@SerializedName("vote_count")
private int voteCount;
@SerializedName("video")
private boolean video;
@SerializedName("vote_average")
private double voteAverage;

public MovieData() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getOriginalTitle() {
return originalTitle;
}

public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}

public String getOriginalLanguage() {
return originalLanguage;
}

public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}

public String getTitle() {
return title;
}

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

public String getPosterPath() {
return posterPath;
}

public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}

public boolean isAdult() {
return adult;
}

public void setAdult(boolean adult) {
this.adult = adult;
}

public String getOverview() {
return overview;
}

public void setOverview(String overview) {
this.overview = overview;
}

public String getReleaseDate() {
return releaseDate;
}

public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}

public List<Integer> getGenreIds() {
return genreIds;
}

public void setGenreIds(List<Integer> genreIds) {
this.genreIds = genreIds;
}

public String getBackdropPath() {
return backdropPath;
}

public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}

public double getPopularity() {
return popularity;
}

public void setPopularity(double popularity) {
this.popularity = popularity;
}

public int getVoteCount() {
return voteCount;
}

public void setVoteCount(int voteCount) {
this.voteCount = voteCount;
}

public boolean isVideo() {
return video;
}

public void setVideo(boolean video) {
this.video = video;
}

public double getVoteAverage() {
return voteAverage;
}

public void setVoteAverage(double voteAverage) {
this.voteAverage = voteAverage;
}

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.originalTitle);
dest.writeString(this.originalLanguage);
dest.writeString(this.title);
dest.writeString(this.posterPath);
dest.writeByte(this.adult ? (byte) 1 : (byte) 0);
dest.writeString(this.overview);
dest.writeString(this.releaseDate);
dest.writeList(this.genreIds);
dest.writeString(this.backdropPath);
dest.writeDouble(this.popularity);
dest.writeInt(this.voteCount);
dest.writeByte(this.video ? (byte) 1 : (byte) 0);
dest.writeDouble(this.voteAverage);
}

protected MovieData(Parcel in) {
this.id = in.readInt();
this.originalTitle = in.readString();
this.originalLanguage = in.readString();
this.title = in.readString();
this.posterPath = in.readString();
this.adult = in.readByte() != 0;
this.overview = in.readString();
this.releaseDate = in.readString();
this.genreIds = new ArrayList<Integer>();
in.readList(this.genreIds, Integer.class.getClassLoader());
this.backdropPath = in.readString();
this.popularity = in.readDouble();
this.voteCount = in.readInt();
this.video = in.readByte() != 0;
this.voteAverage = in.readDouble();
}

public static final Parcelable.Creator<MovieData> CREATOR = new Parcelable.Creator<MovieData>() {
@Override
public MovieData createFromParcel(Parcel source) {
return new MovieData(source);
}

@Override
public MovieData[] newArray(int size) {
return new MovieData[size];
}
};

}
MovieDetail.java
import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
* Created by Wim on 6/2/17.
*/

public class MovieDetail {

@SerializedName("id")
private int id;
@SerializedName("original_language")
private String originalLanguage;
@SerializedName("original_title")
private String originalTitle;
@SerializedName("overview")
private String overview;
@SerializedName("poster_path")
private String posterPath;
@SerializedName("release_date")
private String releaseDate;
@SerializedName("runtime")
private int runtime;
@SerializedName("vote_average")
private double voteAverage;
@SerializedName("homepage")
private String homepage;
@SerializedName("genres")
private List<Genre> genres;

public MovieDetail() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getOriginalLanguage() {
return originalLanguage;
}

public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}

public String getOriginalTitle() {
return originalTitle;
}

public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}

public String getOverview() {
return overview;
}

public void setOverview(String overview) {
this.overview = overview;
}

public String getPosterPath() {
return posterPath;
}

public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}

public String getReleaseDate() {
return releaseDate;
}

public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}

public int getRuntime() {
return runtime;
}

public void setRuntime(int runtime) {
this.runtime = runtime;
}

public double getVoteAverage() {
return voteAverage;
}

public void setVoteAverage(double voteAverage) {
this.voteAverage = voteAverage;
}

public String getHomepage() {
return homepage;
}

public void setHomepage(String homepage) {
this.homepage = homepage;
}

public List<Genre> getGenres() {
return genres;
}

public void setGenres(List<Genre> genres) {
this.genres = genres;
}
}
Review.java
import com.google.gson.annotations.SerializedName;

/**
* Created by Wim on 5/29/17.
*/

public class Review extends BaseModel<ReviewData> {

@SerializedName("id")
private int id;
@SerializedName("total_pages")
private int totalPages;
@SerializedName("total_results")
private int totalResults;

public Review() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public int getTotalPages() {
return totalPages;
}

public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}

public int getTotalResults() {
return totalResults;
}

public void setTotalResults(int totalResults) {
this.totalResults = totalResults;
}
}
ReviewData.java
/**
* Created by Wim on 5/29/17.
*/

public class ReviewData {

private String id;
private String author;
private String content;
private String url;

public ReviewData() {
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getUrl() {
return url;
}

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

}
Trailer.java
import com.google.gson.annotations.SerializedName;

/**
* Created by Wim on 5/29/17.
*/

public class Trailer extends BaseModel<TrailerData> {

@SerializedName("id")
private int id;

public Trailer() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

}
TrailerData.java
import com.google.gson.annotations.SerializedName;

/**
* Created by Wim on 5/29/17.
*/

public class TrailerData {

@SerializedName("id")
private String id;
@SerializedName("key")
private String key;
@SerializedName("name")
private String name;
@SerializedName("site")
private String site;
@SerializedName("size")
private int size;
@SerializedName("type")
private String type;

public TrailerData() {
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSite() {
return site;
}

public void setSite(String site) {
this.site = site;
}

public int getSize() {
return size;
}

public void setSize(int size) {
this.size = size;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

}

- package network

Constant.java
import id.co.blogspot.wimsonevel.android_moviedb.BuildConfig;

/**
* Created by Wim on 5/29/17.
*/

public class Constant {

public static final String BASE_URL = BuildConfig.BASE_URL;
public static final String IMG_URL = BuildConfig.IMG_URL;
public static final String API_KEY = BuildConfig.MOVIE_API_KEY;
public static final String VERSION = "/3";
public static final String MOVIE = "/movie";
public static final String VIDEOS = "videos";
public static final String REVIEWS = "reviews";
public static final String LANG_EN = "en-US";

public static final String MOVIE_PATH = VERSION + MOVIE;

}
ApiInterface.java
import id.co.blogspot.wimsonevel.android_moviedb.model.Movie;
import id.co.blogspot.wimsonevel.android_moviedb.model.MovieDetail;
import id.co.blogspot.wimsonevel.android_moviedb.model.Review;
import id.co.blogspot.wimsonevel.android_moviedb.model.Trailer;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;

/**
* Created by Wim on 6/2/17.
*/

public interface ApiInterface {

@GET(Constant.MOVIE_PATH + "/popular")
Call<Movie> popularMovies(
@Query("page") int page);

@GET(Constant.MOVIE_PATH + "/{movie_id}")
Call<MovieDetail> movieDetail(
@Path("movie_id") int movieId);

@GET(Constant.MOVIE_PATH + "/{movie_id}/" + Constant.VIDEOS)
Call<Trailer> trailers(
@Path("movie_id") int movieId);

@GET(Constant.MOVIE_PATH + "/{movie_id}/" + Constant.REVIEWS)
Call<Review> reviews(
@Path("movie_id") int movieId);

}
ApiService.java
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import id.co.blogspot.wimsonevel.android_moviedb.BuildConfig;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
* Created by Wim on 6/2/17.
*/

public class ApiService {

private ApiInterface apiInterface;

public ApiService(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.client(builder())
.addConverterFactory(GsonConverterFactory.create())
.build();

apiInterface = retrofit.create(ApiInterface.class);
}

private OkHttpClient builder() {
OkHttpClient.Builder okHttpClient = new OkHttpClient().newBuilder();
okHttpClient.connectTimeout(20, TimeUnit.SECONDS);
okHttpClient.writeTimeout(20, TimeUnit.SECONDS);
okHttpClient.readTimeout(90, TimeUnit.SECONDS);

if (BuildConfig.DEBUG) {
okHttpClient.addInterceptor(interceptor());
}

okHttpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url()
.newBuilder()
.addQueryParameter("api_key", Constant.API_KEY)
.addQueryParameter("language", Constant.LANG_EN)
.build();

request = request.newBuilder().url(url).build();
return chain.proceed(request);
}
});

return okHttpClient.build();
}
private static HttpLoggingInterceptor interceptor() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

return interceptor;
}

public void getPopularMovies(int page, Callback callback) {
apiInterface.popularMovies(page).enqueue(callback);
}

public void getMovieDetail(int movieId, Callback callback) {
apiInterface.movieDetail(movieId).enqueue(callback);
}

public void getTrailers(int movieId, Callback callback) {
apiInterface.trailers(movieId).enqueue(callback);
}

public void getReviews(int movieId, Callback callback) {
apiInterface.reviews(movieId).enqueue(callback);
}
}

- package util

ConnectionUtil.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
* Created by Wim on 5/29/17.
*/

public class ConnectionUtil {

public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

}

EndlessRecyclerOnScrollListener.java
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
* Created by Wim on 5/29/17.
*/

public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {

private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 1;
int firstVisibleItem, visibleItemCount, totalItemCount;

private int offset = 0;
private int limit = 0;

private RecyclerView.LayoutManager mLayoutManager;
private boolean isUseLinearLayoutManager = false;

public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager, int offset, int limit) {
this.mLayoutManager = linearLayoutManager;
isUseLinearLayoutManager = true;
this.offset = offset;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);

if (isUseLinearLayoutManager && mLayoutManager instanceof LinearLayoutManager) {
firstVisibleItem = ((LinearLayoutManager) mLayoutManager).findFirstVisibleItemPosition();
}

visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();

if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)
&& totalItemCount >= limit) {
// End has been reached

// Do something
offset++;
onLoadMore(offset);

loading = true;
}
}

public abstract void onLoadMore(int offset);
}
GridMarginDecoration.java
import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
* Created by Wim on 5/29/17.
*/

public class GridMarginDecoration extends RecyclerView.ItemDecoration {

private int left;
private int right;
private int top;
private int bottom;

public GridMarginDecoration(Context context, int left, int right, int top, int bottom) {
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
}

@Override
public void getItemOffsets(
Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.set(left, top, right, bottom);
}

}


- package adapter 

MovieListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

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

import id.co.blogspot.wimsonevel.android_moviedb.R;
import id.co.blogspot.wimsonevel.android_moviedb.model.MovieData;
import id.co.blogspot.wimsonevel.android_moviedb.network.Constant;

/**
* Created by Wim on 5/29/17.
*/

public class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.MovieViewHolder> {

private List<MovieData> movieDatas;
private Context context;

private OnMovieItemSelectedListener onMovieItemSelectedListener;

public MovieListAdapter(Context context) {
this.context = context;
movieDatas = new ArrayList<>();
}

private void add(MovieData item) {
movieDatas.add(item);
notifyItemInserted(movieDatas.size() - 1);
}

public void addAll(List<MovieData> movieDatas) {
for (MovieData movieData : movieDatas) {
add(movieData);
}
}

public void remove(MovieData item) {
int position = movieDatas.indexOf(item);
if (position > -1) {
movieDatas.remove(position);
notifyItemRemoved(position);
}
}

public void clear() {
while (getItemCount() > 0) {
remove(getItem(0));
}
}

public MovieData getItem(int position) {
return movieDatas.get(position);
}

@Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
final MovieViewHolder movieViewHolder = new MovieViewHolder(view);
movieViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int adapterPos = movieViewHolder.getAdapterPosition();
if (adapterPos != RecyclerView.NO_POSITION) {
if (onMovieItemSelectedListener != null) {
onMovieItemSelectedListener.onItemClick(movieViewHolder.itemView, adapterPos);
}
}
}
});

return movieViewHolder;
}

@Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
final MovieData movieData = movieDatas.get(position);
holder.bind(movieData);
}

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

public void setOnMovieItemSelectedListener(OnMovieItemSelectedListener onMovieItemSelectedListener) {
this.onMovieItemSelectedListener = onMovieItemSelectedListener;
}

public class MovieViewHolder extends RecyclerView.ViewHolder {
ImageView img;

public MovieViewHolder(View itemView) {
super(itemView);

img = (ImageView) itemView.findViewById(R.id.img_thumb);
}

public void bind(MovieData movieData) {
Picasso.with(context)
.load(Constant.IMG_URL + movieData.getPosterPath())
.into(img);
}
}

public interface OnMovieItemSelectedListener {
void onItemClick(View v, int position);
}

}

- package fragment 

MainFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.net.SocketTimeoutException;

import id.co.blogspot.wimsonevel.android_moviedb.DetailActivity;
import id.co.blogspot.wimsonevel.android_moviedb.R;
import id.co.blogspot.wimsonevel.android_moviedb.adapter.MovieListAdapter;
import id.co.blogspot.wimsonevel.android_moviedb.model.Movie;
import id.co.blogspot.wimsonevel.android_moviedb.network.ApiService;
import id.co.blogspot.wimsonevel.android_moviedb.util.EndlessRecyclerOnScrollListener;
import id.co.blogspot.wimsonevel.android_moviedb.util.GridMarginDecoration;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
* Created by Wim on 5/29/17.
*/

public class MainFragment extends Fragment implements MovieListAdapter.OnMovieItemSelectedListener {

private Toolbar toolbar;
private RecyclerView rvMovies;
private GridLayoutManager gridLayoutManager;
private MovieListAdapter movieListAdapter;
private SwipeRefreshLayout refreshLayout;

private ActionBar actionBar;
private int page = 1;
private int limit = 20;

private EndlessRecyclerOnScrollListener endlessRecyclerOnScrollListener;

private ApiService apiService;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);

toolbar = (Toolbar) view.findViewById(R.id.toolbar);
refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
rvMovies = (RecyclerView) view.findViewById(R.id.rv_movies);

return view;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

if(savedInstanceState == null) {
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.app_name);
actionBar.setSubtitle(R.string.most_popular);
}

movieListAdapter = new MovieListAdapter(getContext());
movieListAdapter.setOnMovieItemSelectedListener(this);

gridLayoutManager = new GridLayoutManager(getContext(), 2);
rvMovies.setLayoutManager(gridLayoutManager);

rvMovies.addItemDecoration(new GridMarginDecoration(getContext(), 1, 1, 1, 1));
rvMovies.setHasFixedSize(true);
rvMovies.setAdapter(movieListAdapter);

addScroll();

refreshLayout.setColorSchemeResources(R.color.colorPrimary);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshData();
}
});

loadData();
}
}

private void addScroll() {
endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(gridLayoutManager, page, limit) {
@Override
public void onLoadMore(int next) {
page = next;
loadData();
}
};

rvMovies.addOnScrollListener(endlessRecyclerOnScrollListener);
}

private void removeScroll() {
rvMovies.removeOnScrollListener(endlessRecyclerOnScrollListener);
}

private void loadData(){
if (refreshLayout != null) {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(true);
}
});
}

apiService = new ApiService();
apiService.getPopularMovies(page, new Callback() {
@Override
public void onResponse(Call call, Response response) {
Movie movie = (Movie) response.body();

if(movie != null) {
if(movieListAdapter != null) {
movieListAdapter.addAll(movie.getResults());
}
}else{
Toast.makeText(getContext(), "No Data!", Toast.LENGTH_LONG).show();
}

if (refreshLayout != null)
refreshLayout.setRefreshing(false);
}

@Override
public void onFailure(Call call, Throwable t) {
if(t instanceof SocketTimeoutException) {
Toast.makeText(getContext(), "Request Timeout. Please try again!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getContext(), "Connection Error!", Toast.LENGTH_LONG).show();
}

if (refreshLayout != null)
refreshLayout.setRefreshing(false);
}
});
}

private void refreshData() {
if(movieListAdapter != null) {
movieListAdapter.clear();
}
page = 1;

limit = 20;

removeScroll();
addScroll();

loadData();
}

@Override
public void onItemClick(View v, int position) {
DetailActivity.start(getContext(), movieListAdapter.getItem(position));
}

}
DetailFragment.java
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.net.SocketTimeoutException;
import java.util.List;

import id.co.blogspot.wimsonevel.android_moviedb.R;
import id.co.blogspot.wimsonevel.android_moviedb.model.Genre;
import id.co.blogspot.wimsonevel.android_moviedb.model.MovieData;
import id.co.blogspot.wimsonevel.android_moviedb.model.MovieDetail;
import id.co.blogspot.wimsonevel.android_moviedb.model.Review;
import id.co.blogspot.wimsonevel.android_moviedb.model.ReviewData;
import id.co.blogspot.wimsonevel.android_moviedb.model.Trailer;
import id.co.blogspot.wimsonevel.android_moviedb.model.TrailerData;
import id.co.blogspot.wimsonevel.android_moviedb.network.ApiService;
import id.co.blogspot.wimsonevel.android_moviedb.network.Constant;
import id.co.blogspot.wimsonevel.android_moviedb.util.ConnectionUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
* Created by Wim on 5/29/17.
*/

public class DetailFragment extends Fragment {

private Toolbar toolbar;
private ImageView imgPoster;
private TextView tvMovieTitle;
private TextView tvMovieDate;
private TextView tvMovieDuration;
private TextView tvMovieGenre;
private TextView tvMovieHomepage;
private TextView tvMovieOverview;
private LinearLayout viewTrailers;
private LinearLayout viewReviews;

private ProgressBar pgTrailers;
private ProgressBar pgReviews;

private MovieData movieData;

private ApiService apiService;

public static DetailFragment newInstance(MovieData movieData) {
Bundle bundle = new Bundle();
bundle.putParcelable(DetailFragment.class.getSimpleName(), movieData);
DetailFragment detailFragment = new DetailFragment();
detailFragment.setArguments(bundle);
return detailFragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);

toolbar = (Toolbar) view.findViewById(R.id.toolbar);
imgPoster = (ImageView) view.findViewById(R.id.img_poster);
tvMovieTitle = (TextView) view.findViewById(R.id.movie_title);
tvMovieDate = (TextView) view.findViewById(R.id.movie_date);
tvMovieDuration = (TextView) view.findViewById(R.id.movie_duration);
tvMovieGenre = (TextView) view.findViewById(R.id.movie_genre);
tvMovieHomepage = (TextView) view.findViewById(R.id.movie_homepage);
tvMovieOverview = (TextView) view.findViewById(R.id.movie_overview);
viewTrailers = (LinearLayout) view.findViewById(R.id.view_trailers);
viewReviews = (LinearLayout) view.findViewById(R.id.view_reviews);

pgTrailers = (ProgressBar) view.findViewById(R.id.pg_trailers);
pgReviews = (ProgressBar) view.findViewById(R.id.pg_reviews);

return view;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.app_name);
actionBar.setSubtitle(R.string.movie_detail);
}

movieData = getArguments().getParcelable(DetailFragment.class.getSimpleName());

apiService = new ApiService();

if(ConnectionUtil.isConnected(getContext())) {
if(movieData != null) {
loadMovieDetail(movieData.getId());
loadTrailer(movieData.getId());
loadReviews(movieData.getId());
}
}else{
Toast.makeText(getContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}

private void loadMovieDetail(int id) {
apiService.getMovieDetail(id, new Callback() {
@Override
public void onResponse(Call call, Response response) {
MovieDetail movieDetail = (MovieDetail) response.body();

if(movieDetail != null) {
Picasso.with(getContext())
.load(Constant.IMG_URL + movieDetail.getPosterPath())
.into(imgPoster);

tvMovieTitle.setText(movieDetail.getOriginalTitle());
tvMovieDate.setText(movieDetail.getReleaseDate());
tvMovieDuration.setText(movieDetail.getRuntime() + " Minutes");

for (int i = 0; i < movieDetail.getGenres().size(); i++) {
Genre genre = movieDetail.getGenres().get(i);

if(i < movieDetail.getGenres().size() - 1) {
tvMovieGenre.append(genre.getName() + ",");
}else{
tvMovieGenre.append(genre.getName());
}
}

tvMovieHomepage.setText(movieDetail.getHomepage());
tvMovieOverview.setText(movieDetail.getOverview());
}else{
Toast.makeText(getContext(), "No Data!", Toast.LENGTH_LONG).show();
}
}

@Override
public void onFailure(Call call, Throwable t) {
if(t instanceof SocketTimeoutException) {
Toast.makeText(getContext(), "Request Timeout. Please try again!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getContext(), "Connection Error!", Toast.LENGTH_LONG).show();
}

}
});
}

private void loadTrailer(int id) {
pgTrailers.setVisibility(View.VISIBLE);

apiService.getTrailers(id, new Callback() {
@Override
public void onResponse(Call call, Response response) {
Trailer trailer = (Trailer) response.body();

if(trailer != null) {
showTrailers(trailer.getResults());
}else{
Toast.makeText(getContext(), "No Data!", Toast.LENGTH_LONG).show();
}

pgTrailers.setVisibility(View.GONE);
}

@Override
public void onFailure(Call call, Throwable t) {
if(t instanceof SocketTimeoutException) {
Toast.makeText(getContext(), "Request Timeout. Please try again!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getContext(), "Connection Error!", Toast.LENGTH_LONG).show();
}

pgTrailers.setVisibility(View.GONE);
}
});
}

private void loadReviews(int id) {
pgReviews.setVisibility(View.VISIBLE);

apiService.getReviews(id, new Callback() {
@Override
public void onResponse(Call call, Response response) {
Review review = (Review) response.body();

if(review != null) {
showReviews(review.getResults());
}else{
Toast.makeText(getContext(), "No Data!", Toast.LENGTH_LONG).show();
}

pgReviews.setVisibility(View.GONE);
}

@Override
public void onFailure(Call call, Throwable t) {
if(t instanceof SocketTimeoutException) {
Toast.makeText(getContext(), "Request Timeout. Please try again!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getContext(), "Connection Error!", Toast.LENGTH_LONG).show();
}

pgReviews.setVisibility(View.GONE);
}
});
}

private void showTrailers(List<TrailerData> trailerDatas) {
viewTrailers.removeAllViews();

for (int i = 0; i < trailerDatas.size(); i++) {

final TrailerData trailerData = trailerDatas.get(i);
View view = LayoutInflater.from(getContext()).inflate(R.layout.list_item_trailer, viewTrailers, false);

ImageView trailerThumb = (ImageView) view.findViewById(R.id.trailer_thumb);
TextView trailerName = (TextView) view.findViewById(R.id.trailer_name);

if(trailerData.getSite().equalsIgnoreCase("youtube")) {
Picasso.with(getContext())
.load("http://img.youtube.com/vi/" + trailerData.getKey() + "/default.jpg")
.into(trailerThumb);
}

view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
watchYoutubeVideo(trailerData.getKey());
}
});


trailerName.setText(trailerData.getName());
viewTrailers.addView(view);
}
}

public void watchYoutubeVideo(String id){
Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + id));
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v=" + id));
try {
startActivity(appIntent);
} catch (ActivityNotFoundException ex) {
startActivity(webIntent);
}
}

private void showReviews(List<ReviewData> reviewDatas) {
viewReviews.removeAllViews();

for (int i = 0; i < reviewDatas.size(); i++) {

ReviewData reviewData = reviewDatas.get(i);
View view = LayoutInflater.from(getContext()).inflate(R.layout.list_item_review, viewReviews, false);

TextView reviewers = (TextView) view.findViewById(R.id.reviewers);
TextView content = (TextView) view.findViewById(R.id.content);

reviewers.setText(reviewData.getAuthor());
content.setText(reviewData.getContent().length() > 100 ?
reviewData.getContent().substring(0, 100) + "..." : reviewData.getContent());

viewReviews.addView(view);
}
}

}

Langkah selanjutnya adalah buat activity berikut :

MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import id.co.blogspot.wimsonevel.android_moviedb.fragment.MainFragment;

public class MainActivity extends AppCompatActivity {

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

if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MainFragment())
.commit();
}
}

@Override
public void onBackPressed() {
super.onBackPressed();
}

}
DetailActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import id.co.blogspot.wimsonevel.android_moviedb.fragment.DetailFragment;
import id.co.blogspot.wimsonevel.android_moviedb.model.MovieData;

/**
* Created by Wim on 5/29/17.
*/

public class DetailActivity extends AppCompatActivity {

public static void start(Context context, MovieData movieData) {
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra(DetailActivity.class.getSimpleName(), movieData);
context.startActivity(intent);
}

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

MovieData movieData = getIntent().getParcelableExtra(DetailActivity.class.getSimpleName());

if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, DetailFragment.newInstance(movieData))
.commit();
}
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home) {
onBackPressed();
return true;
}

return super.onOptionsItemSelected(item);
}

}
Terakhir, tambahkan permission di AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="id.co.blogspot.wimsonevel.android_moviedb">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name=".DetailActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden"/>

</application>

</manifest>

Build dan jalankan maka tampilan aplikasinya seperti ini :




Selesai akhirnyaaaa...

Project Lengkap dapat di download di https://github.com/wimsonevel/Android-MovieDB

Sekian dari saya kali ini semoga bermanfaat :)

Berlangganan update artikel terbaru via email: