6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | package com.tonytang.demo.constants;
15 |
16 |
17 | public class Constants {
18 |
19 | public static final String API_KEY = "87a901020f496977f9d6d508c5d186ec";
20 | public static final String MOVIE_DB_HOST = "http://api.themoviedb.org/3/";
21 | public static String BASIC_STATIC_URL = "http://image.tmdb.org/t/p/w780/";
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_movie.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 | * Warning: This might not be the best approach to inquiry the network status,
19 | * especially this method will be frequently called in every network request triggered by {@link CacheConfigInterceptor}.
20 | *
21 | * @return true if the device is connected to network or false otherwise.
22 | */
23 | public static boolean isConnected() {
24 | ConnectivityManager connectivity = (ConnectivityManager) AndroidApplication.getInstance()
25 | .getSystemService(Context.CONNECTIVITY_SERVICE);
26 | if (null != connectivity) {
27 | NetworkInfo info = connectivity.getActiveNetworkInfo();
28 | if (null != info && info.isConnected()) {
29 | if (info.getState() == NetworkInfo.State.CONNECTED) {
30 | return true;
31 | }
32 | }
33 | }
34 | return false;
35 | }
36 |
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'me.tatarka.retrolambda'
3 |
4 | android {
5 | compileSdkVersion 25
6 | buildToolsVersion "25.0.2"
7 |
8 | defaultConfig {
9 | applicationId APPPLICATION_ID
10 | minSdkVersion 15
11 | targetSdkVersion 25
12 | versionCode 1
13 | versionName "1.0"
14 | }
15 |
16 | compileOptions {
17 | sourceCompatibility JavaVersion.VERSION_1_8
18 | targetCompatibility JavaVersion.VERSION_1_8
19 | }
20 |
21 | buildTypes {
22 | release {
23 | minifyEnabled false
24 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
25 | }
26 | }
27 |
28 | }
29 |
30 | dependencies {
31 | compile parent.ext.libraries.retrofit
32 | compile parent.ext.libraries.support_v13
33 | compile parent.ext.libraries.appcompat
34 | compile parent.ext.libraries.okhttp_urlconnection
35 | compile parent.ext.libraries.okhttp_logging_interceptor
36 | compile parent.ext.libraries.okhttp
37 | compile parent.ext.libraries.support_annotations
38 | compile parent.ext.libraries.recyclerview
39 | compile parent.ext.libraries.cardview
40 | compile parent.ext.libraries.converter_gson
41 | compile parent.ext.libraries.adapter_rxjava2
42 |
43 | compile 'com.github.JakeWharton.RxBinding:rxbinding:ec6db9d'
44 | compile 'com.google.code.gson:gson:2.8.0'
45 | compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
46 | compile 'com.github.bumptech.glide:glide:3.7.0'
47 | compile 'com.jakewharton:butterknife:7.0.1'
48 | provided 'javax.annotation:jsr250-api:1.0'
49 | compile('com.github.bumptech.glide:okhttp3-integration:1.4.0') {
50 | exclude group: 'glide-parent'
51 | }
52 |
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tonytang/demo/retrofit/service/RestClient.java:
--------------------------------------------------------------------------------
1 | package com.tonytang.demo.retrofit.service;
2 |
3 | import com.tonytang.demo.BuildConfig;
4 | import com.tonytang.demo.constants.Constants;
5 | import com.tonytang.demo.ui.activity.AndroidApplication;
6 |
7 | import java.io.File;
8 |
9 | import okhttp3.Cache;
10 | import okhttp3.OkHttpClient;
11 | import okhttp3.logging.HttpLoggingInterceptor;
12 | import retrofit2.Retrofit;
13 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
14 | import retrofit2.converter.gson.GsonConverterFactory;
15 |
16 | public class RestClient {
17 | private static final String BASE_URL = Constants.MOVIE_DB_HOST;
18 | private static final String CACHE_DIRECTORY_RETROFIT = "cache_directory";
19 | private static final long CACHE_SIZE_RETROFIT = 1000 * 1024;
20 | private final MovieService movieService;
21 |
22 | public RestClient() {
23 | File httpCacheDirectory = new File(AndroidApplication.getInstance().getCacheDir(), CACHE_DIRECTORY_RETROFIT);
24 | Cache httpResponseCache = new Cache(httpCacheDirectory, CACHE_SIZE_RETROFIT);
25 |
26 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
27 | logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BASIC : HttpLoggingInterceptor.Level.NONE);
28 | OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
29 | httpClient.addInterceptor(logging);
30 | httpClient.addInterceptor(new CacheConfigInterceptor());
31 | httpClient.cache(httpResponseCache);
32 | Retrofit retrofit = new Retrofit.Builder()
33 | .baseUrl(BASE_URL).addCallAdapterFactory(RxJava2CallAdapterFactory.create())
34 | .addConverterFactory(GsonConverterFactory.create())
35 | .client(httpClient.build())
36 | .build();
37 |
38 |
39 | movieService = retrofit.create(MovieService.class);
40 |
41 | }
42 |
43 | public MovieService getMovieService() {
44 | return movieService;
45 | }
46 |
47 |
48 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/tonytang/demo/retrofit/service/CacheConfigInterceptor.java:
--------------------------------------------------------------------------------
1 | package com.tonytang.demo.retrofit.service;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import com.tonytang.demo.util.AppUtils;
6 |
7 | import java.io.IOException;
8 |
9 | import okhttp3.Interceptor;
10 | import okhttp3.Request;
11 | import okhttp3.Response;
12 |
13 |
14 | /**
15 | * This is an interceptor to config the cache of the http response.
16 | * Based on network status, the cache valid interval will be configured differently.
17 | * When the network is connected, its valid interval is only 10 seconds as we could always retrieve
18 | * the data from server.
19 | * When the network is disconnected, it will accept the cache response in the past month of such request.
20 | *
21 | *
22 | * You could test it out by searching a keyword. Then cut off all network including mobile network
23 | * and search the same keyword again. You will still get the result.
24 | *
25 | * In this case, we do not have to manage cache by ourselves.
26 | */
27 | public final class CacheConfigInterceptor implements Interceptor {
28 |
29 | public static final long CACHE_DURATION_WITH_NETWORK_IN_SECONDS = 10;//expired in 10 seconds.
30 | public static final long CACHE_DURATION_WITHOUT_NETWORK_IN_SECONDS = 7 * 24 * 60 * 60;//expired in once week.
31 |
32 | @Override
33 | public Response intercept(Chain chain) throws IOException {
34 | Request originalRequest = chain.request();
35 | Request compressedRequest = originalRequest.newBuilder()
36 | .header("Cache-Control", getCacheConfig()).build();
37 | return chain.proceed(compressedRequest);
38 | }
39 |
40 | @NonNull
41 | private String getCacheConfig() {
42 | return AppUtils.isConnected() ? getCacheConfigOnNetworkConnected() : getCacheConfigOnNetworkDisconnected();
43 | }
44 |
45 |
46 | @NonNull
47 | private String getCacheConfigOnNetworkDisconnected() {
48 | //hard code here as it is fixed settings.
49 | return "public, only-if-cached, max-stale=" + CACHE_DURATION_WITHOUT_NETWORK_IN_SECONDS;
50 | }
51 |
52 | @NonNull
53 | private String getCacheConfigOnNetworkConnected() {
54 | //hard code here as it is fixed settings.
55 | return "public, max-age=" + CACHE_DURATION_WITH_NETWORK_IN_SECONDS + ", max-stale=" + CACHE_DURATION_WITH_NETWORK_IN_SECONDS;
56 | }
57 |
58 |
59 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/tonytang/demo/ui/adapter/MovieAdapter.java:
--------------------------------------------------------------------------------
1 | package com.tonytang.demo.ui.adapter;
2 |
3 | import android.content.Context;
4 | import android.support.v7.widget.RecyclerView;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.ImageView;
9 | import android.widget.TextView;
10 |
11 | import com.bumptech.glide.Glide;
12 | import com.tonytang.demo.R;
13 | import com.tonytang.demo.constants.Constants;
14 | import com.tonytang.demo.entity.Movie;
15 |
16 | import java.util.ArrayList;
17 | import java.util.List;
18 |
19 | import butterknife.Bind;
20 | import butterknife.ButterKnife;
21 |
22 | public class MovieAdapter extends RecyclerView.Adapter
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | package com.tonytang.demo.entity;
15 |
16 | import java.io.Serializable;
17 |
18 | public class Movie implements Serializable {
19 |
20 | private String poster_path;
21 | private boolean adult;
22 | private String overview;
23 | private String release_date;
24 | private Number[] genre_ids;
25 | private Number id;
26 | private String original_title;
27 | private String original_language;
28 | private String title;
29 | private String backdrop_path;
30 | private Number popularity;
31 | private Number vote_count;
32 | private boolean video;
33 | private Number vote_average;
34 |
35 |
36 | public String getPoster_path() {
37 | return poster_path;
38 | }
39 |
40 | public void setPoster_path(String poster_path) {
41 | this.poster_path = poster_path;
42 | }
43 |
44 | public boolean isAdult() {
45 | return adult;
46 | }
47 |
48 | public void setAdult(boolean adult) {
49 | this.adult = adult;
50 | }
51 |
52 | public String getOverview() {
53 | return overview;
54 | }
55 |
56 | public void setOverview(String overview) {
57 | this.overview = overview;
58 | }
59 |
60 | public String getRelease_date() {
61 | return release_date;
62 | }
63 |
64 | public void setRelease_date(String release_date) {
65 | this.release_date = release_date;
66 | }
67 |
68 | public Number[] getGenre_ids() {
69 | return genre_ids;
70 | }
71 |
72 | public void setGenre_ids(Number[] genre_ids) {
73 | this.genre_ids = genre_ids;
74 | }
75 |
76 | public Number getId() {
77 | return id;
78 | }
79 |
80 | public void setId(Number id) {
81 | this.id = id;
82 | }
83 |
84 | public String getOriginal_title() {
85 | return original_title;
86 | }
87 |
88 | public void setOriginal_title(String original_title) {
89 | this.original_title = original_title;
90 | }
91 |
92 | public String getOriginal_language() {
93 | return original_language;
94 | }
95 |
96 | public void setOriginal_language(String original_language) {
97 | this.original_language = original_language;
98 | }
99 |
100 | public String getTitle() {
101 | return title;
102 | }
103 |
104 | public void setTitle(String title) {
105 | this.title = title;
106 | }
107 |
108 | public String getBackdrop_path() {
109 | return backdrop_path;
110 | }
111 |
112 | public void setBackdrop_path(String backdrop_path) {
113 | this.backdrop_path = backdrop_path;
114 | }
115 |
116 | public Number getPopularity() {
117 | return popularity;
118 | }
119 |
120 | public void setPopularity(Number popularity) {
121 | this.popularity = popularity;
122 | }
123 |
124 | public Number getVote_count() {
125 | return vote_count;
126 | }
127 |
128 | public void setVote_count(Number vote_count) {
129 | this.vote_count = vote_count;
130 | }
131 |
132 | public boolean isVideo() {
133 | return video;
134 | }
135 |
136 | public void setVideo(boolean video) {
137 | this.video = video;
138 | }
139 |
140 | public Number getVote_average() {
141 | return vote_average;
142 | }
143 |
144 | public void setVote_average(Number vote_average) {
145 | this.vote_average = vote_average;
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tonytang/demo/ui/fragment/MovieSearchFragment.java:
--------------------------------------------------------------------------------
1 | package com.tonytang.demo.ui.fragment;
2 |
3 | import android.app.Fragment;
4 | import android.os.Bundle;
5 | import android.support.annotation.Nullable;
6 | import android.support.v7.widget.LinearLayoutManager;
7 | import android.support.v7.widget.RecyclerView;
8 | import android.text.TextUtils;
9 | import android.util.Log;
10 | import android.view.LayoutInflater;
11 | import android.view.View;
12 | import android.view.ViewGroup;
13 | import android.widget.EditText;
14 | import android.widget.FrameLayout;
15 | import android.widget.ProgressBar;
16 | import android.widget.TextView;
17 |
18 | import com.jakewharton.rxbinding2.widget.RxTextView;
19 | import com.jakewharton.rxbinding2.widget.TextViewTextChangeEvent;
20 | import com.tonytang.demo.BuildConfig;
21 | import com.tonytang.demo.R;
22 | import com.tonytang.demo.constants.Constants;
23 | import com.tonytang.demo.entity.Movie;
24 | import com.tonytang.demo.model.MoviesWrapper;
25 | import com.tonytang.demo.ui.activity.AndroidApplication;
26 | import com.tonytang.demo.ui.adapter.MovieAdapter;
27 | import com.tonytang.demo.ui.decoration.DividerItemDecoration;
28 |
29 | import java.util.List;
30 | import java.util.concurrent.TimeUnit;
31 |
32 | import butterknife.Bind;
33 | import butterknife.ButterKnife;
34 | import io.reactivex.Observable;
35 | import io.reactivex.Observer;
36 | import io.reactivex.android.schedulers.AndroidSchedulers;
37 | import io.reactivex.disposables.CompositeDisposable;
38 | import io.reactivex.disposables.Disposable;
39 | import io.reactivex.schedulers.Schedulers;
40 |
41 |
42 | public class MovieSearchFragment extends Fragment {
43 |
44 | private static final String TAG = "DebounceSearch";
45 | //this will be responsible of managing the callback from network request.
46 | protected final CompositeDisposable networkRequestSubscription = new CompositeDisposable();
47 |
48 | @Bind(R.id.edit_text)
49 | EditText inputSearchText;
50 | @Bind(R.id.recycler_view)
51 | RecyclerView recyclerView;
52 | @Bind(R.id.top_empty_view)
53 | FrameLayout topEmptyView;//It will be shown when the data is loading or the request has error. It will be hiddden if the result is good.
54 | @Bind(R.id.progress_bar)
55 | ProgressBar progressBar;
56 | @Bind(R.id.tv_empty_hint)
57 | TextView tvEmptyViewHint;
58 |
59 |
60 | private Disposable disposable;
61 | private MovieAdapter movieAdapter;
62 |
63 | public static MovieSearchFragment newInstance() {
64 |
65 | return new MovieSearchFragment();
66 | }
67 |
68 |
69 | @Override
70 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
71 | View layout = inflater.inflate(R.layout.fragment_movie, container, false);
72 | ButterKnife.bind(this, layout);
73 | return layout;
74 | }
75 |
76 | @Override
77 | public void onViewCreated(View view, Bundle savedInstanceState) {
78 | super.onViewCreated(view, savedInstanceState);
79 | recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
80 | recyclerView.setHasFixedSize(true);
81 | recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
82 | movieAdapter = new MovieAdapter(getActivity());
83 | recyclerView.setAdapter(movieAdapter);
84 |
85 |
86 | }
87 |
88 | @Override
89 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
90 | super.onActivityCreated(savedInstanceState);
91 | final Observable