Use MVVM design pattern to load and display the posts. Minor bugs fixed.

This commit is contained in:
Alex Ning 2018-11-09 12:30:31 +08:00
parent 4373d3aa55
commit cdcb38db51
10 changed files with 358 additions and 331 deletions

View File

@ -1,19 +1,21 @@
package ml.docilealligator.infinityforreddit; package ml.docilealligator.infinityforreddit;
import java.util.ArrayList;
class PaginationSynchronizer { class PaginationSynchronizer {
private boolean loadingState; private boolean loadingState;
private boolean loadSuccess; private boolean loadSuccess;
private PaginationNotifier paginationNotifier; private PaginationNotifier paginationNotifier;
private PaginationRetryNotifier paginationRetryNotifier; private PaginationRetryNotifier paginationRetryNotifier;
private LastItemSynchronizer lastItemSynchronizer; private ArrayList<LastItemSynchronizer> lastItemSynchronizers;
PaginationSynchronizer(LastItemSynchronizer lastItemSynchronizer) { PaginationSynchronizer() {
lastItemSynchronizers = new ArrayList<>();
loadingState = false; loadingState = false;
loadSuccess = true; loadSuccess = true;
this. lastItemSynchronizer = lastItemSynchronizer;
} }
public void setLoadingState(boolean isLoading) { void setLoadingState(boolean isLoading) {
this.loadingState = isLoading; this.loadingState = isLoading;
} }
@ -21,7 +23,7 @@ class PaginationSynchronizer {
return loadingState; return loadingState;
} }
public void loadSuccess(boolean state) { void loadSuccess(boolean state) {
loadSuccess = state; loadSuccess = state;
if(loadSuccess) { if(loadSuccess) {
paginationNotifier.LoadMorePostSuccess(); paginationNotifier.LoadMorePostSuccess();
@ -30,28 +32,34 @@ class PaginationSynchronizer {
} }
} }
public void setLoadSuccess(boolean loadSuccess) { void setLoadSuccess(boolean loadSuccess) {
this.loadSuccess = loadSuccess; this.loadSuccess = loadSuccess;
} }
public boolean isLoadSuccess() { boolean isLoadingMorePostsSuccess() {
return loadSuccess; return loadSuccess;
} }
public void setPaginationNotifier(PaginationNotifier paginationNotifier) { void setPaginationNotifier(PaginationNotifier paginationNotifier) {
this.paginationNotifier = paginationNotifier; this.paginationNotifier = paginationNotifier;
} }
public void setPaginationRetryNotifier(PaginationRetryNotifier paginationRetryNotifier) { void setPaginationRetryNotifier(PaginationRetryNotifier paginationRetryNotifier) {
this.paginationRetryNotifier = paginationRetryNotifier; this.paginationRetryNotifier = paginationRetryNotifier;
} }
public PaginationRetryNotifier getPaginationRetryNotifier() { PaginationRetryNotifier getPaginationRetryNotifier() {
return paginationRetryNotifier; return paginationRetryNotifier;
} }
public LastItemSynchronizer getLastItemSynchronizer() { void addLastItemSynchronizer(LastItemSynchronizer lastItemSynchronizer) {
return lastItemSynchronizer; lastItemSynchronizers.add(lastItemSynchronizer);
}
void notifyLastItemChanged(String lastItem) {
for(LastItemSynchronizer l : lastItemSynchronizers) {
l.lastItemChanged(lastItem);
}
} }
} }

View File

@ -19,32 +19,29 @@ import java.util.Locale;
class ParsePost { class ParsePost {
interface ParsePostListener { interface ParsePostListener {
void onParsePostSuccess(ArrayList<PostData> postData, String lastItem); void onParsePostSuccess(ArrayList<Post> newPostData, String lastItem);
void onParsePostFail(); void onParsePostFail();
} }
static void parsePost(String response, ArrayList<PostData> postData, Locale locale, static void parsePost(String response, Locale locale, ParsePostListener parsePostListener) {
ParsePostListener parsePostListener) { new ParsePostDataAsyncTask(response, locale, parsePostListener).execute();
new ParsePostDataAsyncTask(response, postData, locale, parsePostListener).execute();
} }
private static class ParsePostDataAsyncTask extends AsyncTask<Void, Void, Void> { private static class ParsePostDataAsyncTask extends AsyncTask<Void, Void, Void> {
private JSONObject jsonResponse; private JSONObject jsonResponse;
private ArrayList<PostData> postData;
private Locale locale; private Locale locale;
private ParsePostListener parsePostListener; private ParsePostListener parsePostListener;
private ArrayList<PostData> newPostData; private ArrayList<Post> newPosts;
private String lastItem; private String lastItem;
private boolean parseFailed; private boolean parseFailed;
ParsePostDataAsyncTask(String response, ArrayList<PostData> postData, Locale locale, ParsePostDataAsyncTask(String response, Locale locale,
ParsePostListener parsePostListener) { ParsePostListener parsePostListener) {
try { try {
jsonResponse = new JSONObject(response); jsonResponse = new JSONObject(response);
this.postData = postData;
this.locale = locale; this.locale = locale;
this.parsePostListener = parsePostListener; this.parsePostListener = parsePostListener;
newPostData = new ArrayList<>(); newPosts = new ArrayList<>();
parseFailed = false; parseFailed = false;
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
@ -85,6 +82,7 @@ class ParsePost {
int previewWidth = -1; int previewWidth = -1;
int previewHeight = -1; int previewHeight = -1;
if(data.has(JSONUtils.PREVIEW_KEY)) { if(data.has(JSONUtils.PREVIEW_KEY)) {
Log.i("haspreview", Integer.toString(i));
previewUrl = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0) previewUrl = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY); .getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY);
previewWidth = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0) previewWidth = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
@ -96,11 +94,11 @@ class ParsePost {
if(data.has(JSONUtils.CROSSPOST_PARENT_LIST)) { if(data.has(JSONUtils.CROSSPOST_PARENT_LIST)) {
//Cross post //Cross post
data = data.getJSONArray(JSONUtils.CROSSPOST_PARENT_LIST).getJSONObject(0); data = data.getJSONArray(JSONUtils.CROSSPOST_PARENT_LIST).getJSONObject(0);
parseData(data, permalink, newPostData, id, fullName, subredditNamePrefixed, parseData(data, permalink, newPosts, id, fullName, subredditNamePrefixed,
formattedPostTime, title, previewUrl, previewWidth, previewHeight, formattedPostTime, title, previewUrl, previewWidth, previewHeight,
score, voteType, gilded, nsfw, stickied, true, i); score, voteType, gilded, nsfw, stickied, true, i);
} else { } else {
parseData(data, permalink, newPostData, id, fullName, subredditNamePrefixed, parseData(data, permalink, newPosts, id, fullName, subredditNamePrefixed,
formattedPostTime, title, previewUrl, previewWidth, previewHeight, formattedPostTime, title, previewUrl, previewWidth, previewHeight,
score, voteType, gilded, nsfw, stickied, false, i); score, voteType, gilded, nsfw, stickied, false, i);
} }
@ -115,15 +113,14 @@ class ParsePost {
@Override @Override
protected void onPostExecute(Void aVoid) { protected void onPostExecute(Void aVoid) {
if(!parseFailed) { if(!parseFailed) {
postData.addAll(newPostData); parsePostListener.onParsePostSuccess(newPosts, lastItem);
parsePostListener.onParsePostSuccess(postData, lastItem);
} else { } else {
parsePostListener.onParsePostFail(); parsePostListener.onParsePostFail();
} }
} }
} }
private static void parseData(JSONObject data, String permalink, ArrayList<PostData> bestPostData, private static void parseData(JSONObject data, String permalink, ArrayList<Post> bestPostData,
String id, String fullName, String subredditNamePrefixed, String formattedPostTime, String id, String fullName, String subredditNamePrefixed, String formattedPostTime,
String title, String previewUrl, int previewWidth, int previewHeight ,int score, int voteType, int gilded, String title, String previewUrl, int previewWidth, int previewHeight ,int score, int voteType, int gilded,
boolean nsfw, boolean stickied, boolean isCrosspost, int i) throws JSONException { boolean nsfw, boolean stickied, boolean isCrosspost, int i) throws JSONException {
@ -134,55 +131,55 @@ class ParsePost {
if(url.contains(permalink)) { if(url.contains(permalink)) {
//Text post //Text post
Log.i("text", Integer.toString(i)); Log.i("text", Integer.toString(i));
int postType = PostData.TEXT_TYPE; int postType = Post.TEXT_TYPE;
PostData postData = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, Post post = new Post(id, fullName, subredditNamePrefixed, formattedPostTime,
title, permalink, score, postType, voteType, gilded, nsfw, stickied, isCrosspost); title, permalink, score, postType, voteType, gilded, nsfw, stickied, isCrosspost);
if(data.isNull(JSONUtils.SELFTEXT_HTML_KEY)) { if(data.isNull(JSONUtils.SELFTEXT_HTML_KEY)) {
postData.setSelfText(""); post.setSelfText("");
} else { } else {
postData.setSelfText(data.getString(JSONUtils.SELFTEXT_HTML_KEY).trim()); post.setSelfText(data.getString(JSONUtils.SELFTEXT_HTML_KEY).trim());
} }
bestPostData.add(postData); bestPostData.add(post);
} else { } else {
//No preview link post //No preview link post
Log.i("no preview link", Integer.toString(i)); Log.i("no preview link", Integer.toString(i));
int postType = PostData.NO_PREVIEW_LINK_TYPE; int postType = Post.NO_PREVIEW_LINK_TYPE;
PostData linkPostData = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, Post linkPost = new Post(id, fullName, subredditNamePrefixed, formattedPostTime,
title, previewUrl, url, permalink, score, postType, title, previewUrl, url, permalink, score, postType,
voteType, gilded, nsfw, stickied, isCrosspost); voteType, gilded, nsfw, stickied, isCrosspost);
if(data.isNull(JSONUtils.SELFTEXT_HTML_KEY)) { if(data.isNull(JSONUtils.SELFTEXT_HTML_KEY)) {
linkPostData.setSelfText(""); linkPost.setSelfText("");
} else { } else {
linkPostData.setSelfText(data.getString(JSONUtils.SELFTEXT_HTML_KEY).trim()); linkPost.setSelfText(data.getString(JSONUtils.SELFTEXT_HTML_KEY).trim());
} }
bestPostData.add(linkPostData); bestPostData.add(linkPost);
} }
} else if(isVideo) { } else if(isVideo) {
//Video post //Video post
Log.i("video", Integer.toString(i)); Log.i("video", Integer.toString(i));
JSONObject redditVideoObject = data.getJSONObject(JSONUtils.MEDIA_KEY).getJSONObject(JSONUtils.REDDIT_VIDEO_KEY); JSONObject redditVideoObject = data.getJSONObject(JSONUtils.MEDIA_KEY).getJSONObject(JSONUtils.REDDIT_VIDEO_KEY);
int postType = PostData.VIDEO_TYPE; int postType = Post.VIDEO_TYPE;
String videoUrl = redditVideoObject.getString(JSONUtils.DASH_URL_KEY); String videoUrl = redditVideoObject.getString(JSONUtils.DASH_URL_KEY);
PostData videoPostData = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, Post videoPost = new Post(id, fullName, subredditNamePrefixed, formattedPostTime,
title, previewUrl, permalink, score, postType, voteType, title, previewUrl, permalink, score, postType, voteType,
gilded, nsfw, stickied, isCrosspost, true); gilded, nsfw, stickied, isCrosspost, true);
videoPostData.setPreviewWidth(previewWidth); videoPost.setPreviewWidth(previewWidth);
videoPostData.setPreviewHeight(previewHeight); videoPost.setPreviewHeight(previewHeight);
videoPostData.setVideoUrl(videoUrl); videoPost.setVideoUrl(videoUrl);
videoPostData.setDownloadableGifOrVideo(false); videoPost.setDownloadableGifOrVideo(false);
bestPostData.add(videoPostData); bestPostData.add(videoPost);
} else if(data.has(JSONUtils.PREVIEW_KEY)){ } else if(data.has(JSONUtils.PREVIEW_KEY)){
JSONObject variations = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0); JSONObject variations = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0);
if (variations.has(JSONUtils.VARIANTS_KEY) && variations.getJSONObject(JSONUtils.VARIANTS_KEY).has(JSONUtils.MP4_KEY)) { if (variations.has(JSONUtils.VARIANTS_KEY) && variations.getJSONObject(JSONUtils.VARIANTS_KEY).has(JSONUtils.MP4_KEY)) {
//Gif video post (MP4) //Gif video post (MP4)
Log.i("gif video mp4", Integer.toString(i)); Log.i("gif video mp4", Integer.toString(i));
int postType = PostData.GIF_VIDEO_TYPE; int postType = Post.GIF_VIDEO_TYPE;
String videoUrl = variations.getJSONObject(JSONUtils.VARIANTS_KEY).getJSONObject(JSONUtils.MP4_KEY).getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY); String videoUrl = variations.getJSONObject(JSONUtils.VARIANTS_KEY).getJSONObject(JSONUtils.MP4_KEY).getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY);
String gifDownloadUrl = variations.getJSONObject(JSONUtils.VARIANTS_KEY).getJSONObject(JSONUtils.GIF_KEY).getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY); String gifDownloadUrl = variations.getJSONObject(JSONUtils.VARIANTS_KEY).getJSONObject(JSONUtils.GIF_KEY).getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY);
PostData post = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, title, Post post = new Post(id, fullName, subredditNamePrefixed, formattedPostTime, title,
previewUrl, permalink, score, postType, voteType, previewUrl, permalink, score, postType, voteType,
gilded, nsfw, stickied, isCrosspost, false); gilded, nsfw, stickied, isCrosspost, false);
@ -196,11 +193,11 @@ class ParsePost {
} else if(data.getJSONObject(JSONUtils.PREVIEW_KEY).has(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY)) { } else if(data.getJSONObject(JSONUtils.PREVIEW_KEY).has(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY)) {
//Gif video post (Dash) //Gif video post (Dash)
Log.i("gif video dash", Integer.toString(i)); Log.i("gif video dash", Integer.toString(i));
int postType = PostData.GIF_VIDEO_TYPE; int postType = Post.GIF_VIDEO_TYPE;
String videoUrl = data.getJSONObject(JSONUtils.PREVIEW_KEY) String videoUrl = data.getJSONObject(JSONUtils.PREVIEW_KEY)
.getJSONObject(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY).getString(JSONUtils.DASH_URL_KEY); .getJSONObject(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY).getString(JSONUtils.DASH_URL_KEY);
PostData post = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, title, Post post = new Post(id, fullName, subredditNamePrefixed, formattedPostTime, title,
previewUrl, permalink, score, postType, voteType, previewUrl, permalink, score, postType, voteType,
gilded, nsfw, stickied, isCrosspost, true); gilded, nsfw, stickied, isCrosspost, true);
@ -214,69 +211,71 @@ class ParsePost {
if (url.endsWith("jpg") || url.endsWith("png")) { if (url.endsWith("jpg") || url.endsWith("png")) {
//Image post //Image post
Log.i("image", Integer.toString(i)); Log.i("image", Integer.toString(i));
int postType = PostData.IMAGE_TYPE; int postType = Post.IMAGE_TYPE;
PostData imagePostData = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, Post imagePost = new Post(id, fullName, subredditNamePrefixed, formattedPostTime,
title, url, url, permalink, score, postType, title, url, url, permalink, score, postType,
voteType, gilded, nsfw, stickied, isCrosspost); voteType, gilded, nsfw, stickied, isCrosspost);
imagePostData.setPreviewWidth(previewWidth); imagePost.setPreviewWidth(previewWidth);
imagePostData.setPreviewHeight(previewHeight); imagePost.setPreviewHeight(previewHeight);
bestPostData.add(imagePostData); bestPostData.add(imagePost);
} else { } else {
if (url.contains(permalink)) { if (url.contains(permalink)) {
//Text post but with a preview //Text post but with a preview
Log.i("text with image", Integer.toString(i)); Log.i("text with image", Integer.toString(i));
int postType = PostData.TEXT_TYPE; int postType = Post.TEXT_TYPE;
PostData textWithImagePostData = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, Post textWithImagePost = new Post(id, fullName, subredditNamePrefixed, formattedPostTime,
title, permalink, score, postType, voteType, gilded, nsfw, stickied, isCrosspost); title, permalink, score, postType, voteType, gilded, nsfw, stickied, isCrosspost);
textWithImagePostData.setPreviewWidth(previewWidth); textWithImagePost.setPreviewWidth(previewWidth);
textWithImagePostData.setPreviewHeight(previewHeight); textWithImagePost.setPreviewHeight(previewHeight);
if(data.isNull(JSONUtils.SELFTEXT_HTML_KEY)) { if(data.isNull(JSONUtils.SELFTEXT_HTML_KEY)) {
textWithImagePostData.setSelfText(""); textWithImagePost.setSelfText("");
} else { } else {
textWithImagePostData.setSelfText(data.getString(JSONUtils.SELFTEXT_HTML_KEY).trim()); textWithImagePost.setSelfText(data.getString(JSONUtils.SELFTEXT_HTML_KEY).trim());
} }
bestPostData.add(textWithImagePostData); bestPostData.add(textWithImagePost);
} else { } else {
//Link post //Link post
Log.i("link", Integer.toString(i)); Log.i("link", Integer.toString(i));
int postType = PostData.LINK_TYPE; int postType = Post.LINK_TYPE;
PostData linkPostData = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, Post linkPost = new Post(id, fullName, subredditNamePrefixed, formattedPostTime,
title, previewUrl, url, permalink, score, title, previewUrl, url, permalink, score,
postType, voteType, gilded, nsfw, stickied, isCrosspost); postType, voteType, gilded, nsfw, stickied, isCrosspost);
if(data.isNull(JSONUtils.SELFTEXT_HTML_KEY)) { if(data.isNull(JSONUtils.SELFTEXT_HTML_KEY)) {
linkPostData.setSelfText(""); linkPost.setSelfText("");
} else { } else {
linkPostData.setSelfText(data.getString(JSONUtils.SELFTEXT_HTML_KEY).trim()); linkPost.setSelfText(data.getString(JSONUtils.SELFTEXT_HTML_KEY).trim());
} }
linkPostData.setPreviewWidth(previewWidth); linkPost.setPreviewWidth(previewWidth);
linkPostData.setPreviewHeight(previewHeight); linkPost.setPreviewHeight(previewHeight);
bestPostData.add(linkPostData); bestPostData.add(linkPost);
} }
} }
} }
} else { } else {
if (url.endsWith("jpg") || url.endsWith("png")) { if (url.endsWith("jpg") || url.endsWith("png")) {
//Image post //Image post
Log.i("CP no preview image", Integer.toString(i)); Log.i("CP image", Integer.toString(i));
int postType = PostData.IMAGE_TYPE; int postType = Post.IMAGE_TYPE;
bestPostData.add(new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, title, Post linkPost = new Post(id, fullName, subredditNamePrefixed, formattedPostTime,
url, url, permalink, score, postType, voteType, title, previewUrl, url, permalink, score, postType,
gilded, nsfw, stickied, isCrosspost)); voteType, gilded, nsfw, stickied, isCrosspost);
linkPost.setPreviewWidth(previewWidth);
linkPost.setPreviewHeight(previewHeight);
bestPostData.add(linkPost);
} else { } else {
//CP No Preview Link post //CP No Preview Link post
Log.i("CP no preview link", Integer.toString(i)); Log.i("CP no preview link", Integer.toString(i));
int postType = PostData.NO_PREVIEW_LINK_TYPE; int postType = Post.NO_PREVIEW_LINK_TYPE;
PostData linkPostData = new PostData(id, fullName, subredditNamePrefixed, formattedPostTime, bestPostData.add(new Post(id, fullName, subredditNamePrefixed, formattedPostTime, title,
title, previewUrl, url, permalink, score, postType, url, url, permalink, score, postType, voteType,
voteType, gilded, nsfw, stickied, isCrosspost); gilded, nsfw, stickied, isCrosspost));
bestPostData.add(linkPostData);
} }
} }
} }

View File

@ -7,7 +7,7 @@ import android.os.Parcelable;
* Created by alex on 3/1/18. * Created by alex on 3/1/18.
*/ */
class PostData implements Parcelable { class Post implements Parcelable {
static final int TEXT_TYPE = 0; static final int TEXT_TYPE = 0;
static final int IMAGE_TYPE = 1; static final int IMAGE_TYPE = 1;
static final int LINK_TYPE = 2; static final int LINK_TYPE = 2;
@ -38,11 +38,11 @@ class PostData implements Parcelable {
private boolean isCrosspost; private boolean isCrosspost;
private boolean isDashVideo; private boolean isDashVideo;
private boolean isDownloadableGifOrVideo; private boolean isDownloadableGifOrVideo;
private PostData crosspostParentPostData; private Post crosspostParentPost;
PostData(String id, String fullName, String subredditNamePrefixed, String postTime, String title, Post(String id, String fullName, String subredditNamePrefixed, String postTime, String title,
String previewUrl, String permalink, int score, int postType, int voteType, int gilded, String previewUrl, String permalink, int score, int postType, int voteType, int gilded,
boolean nsfw, boolean stickied, boolean isCrosspost, boolean isDashVideo) { boolean nsfw, boolean stickied, boolean isCrosspost, boolean isDashVideo) {
this.id = id; this.id = id;
this.fullName = fullName; this.fullName = fullName;
this.subredditNamePrefixed = subredditNamePrefixed; this.subredditNamePrefixed = subredditNamePrefixed;
@ -60,9 +60,9 @@ class PostData implements Parcelable {
this.isDashVideo = isDashVideo; this.isDashVideo = isDashVideo;
} }
PostData(String id, String fullName, String subredditNamePrefixed, String postTime, String title, Post(String id, String fullName, String subredditNamePrefixed, String postTime, String title,
String previewUrl, String url, String permalink, int score, int postType, int voteType, String previewUrl, String url, String permalink, int score, int postType, int voteType,
int gilded, boolean nsfw, boolean stickied, boolean isCrosspost) { int gilded, boolean nsfw, boolean stickied, boolean isCrosspost) {
this.id = id; this.id = id;
this.fullName = fullName; this.fullName = fullName;
this.subredditNamePrefixed = subredditNamePrefixed; this.subredditNamePrefixed = subredditNamePrefixed;
@ -80,9 +80,9 @@ class PostData implements Parcelable {
this.isCrosspost = isCrosspost; this.isCrosspost = isCrosspost;
} }
PostData(String id, String fullName, String subredditNamePrefixed, String postTime, String title, Post(String id, String fullName, String subredditNamePrefixed, String postTime, String title,
String permalink, int score, int postType, int voteType, int gilded, boolean nsfw, String permalink, int score, int postType, int voteType, int gilded, boolean nsfw,
boolean stickied, boolean isCrosspost) { boolean stickied, boolean isCrosspost) {
this.id = id; this.id = id;
this.fullName = fullName; this.fullName = fullName;
this.subredditNamePrefixed = subredditNamePrefixed; this.subredditNamePrefixed = subredditNamePrefixed;
@ -98,7 +98,7 @@ class PostData implements Parcelable {
this.isCrosspost= isCrosspost; this.isCrosspost= isCrosspost;
} }
protected PostData(Parcel in) { protected Post(Parcel in) {
id = in.readString(); id = in.readString();
fullName = in.readString(); fullName = in.readString();
subredditNamePrefixed = in.readString(); subredditNamePrefixed = in.readString();
@ -124,15 +124,15 @@ class PostData implements Parcelable {
isDownloadableGifOrVideo = in.readByte() != 0; isDownloadableGifOrVideo = in.readByte() != 0;
} }
public static final Creator<PostData> CREATOR = new Creator<PostData>() { public static final Creator<Post> CREATOR = new Creator<Post>() {
@Override @Override
public PostData createFromParcel(Parcel in) { public Post createFromParcel(Parcel in) {
return new PostData(in); return new Post(in);
} }
@Override @Override
public PostData[] newArray(int size) { public Post[] newArray(int size) {
return new PostData[size]; return new Post[size];
} }
}; };

View File

@ -1,12 +1,13 @@
package ml.docilealligator.infinityforreddit; package ml.docilealligator.infinityforreddit;
import android.content.ClipData; import android.arch.lifecycle.Observer;
import android.content.ClipboardManager; import android.arch.lifecycle.ViewModelProviders;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar; import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
@ -52,13 +53,17 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private LinearLayout mFetchPostErrorLinearLayout; private LinearLayout mFetchPostErrorLinearLayout;
private ImageView mFetchPostErrorImageView; private ImageView mFetchPostErrorImageView;
private ArrayList<PostData> mPostData; private ArrayList<Post> mPostData;
private String mLastItem; private String mLastItem;
private PaginationSynchronizer mPaginationSynchronizer; private PaginationSynchronizer mPaginationSynchronizer;
private boolean mIsBestPost; private boolean mIsBestPost;
private String mSubredditName; private String mSubredditName;
private PostRecyclerViewAdapter mAdapter;
private PostViewModel mPostViewModel;
@Inject @Named("no_oauth") @Inject @Named("no_oauth")
Retrofit mRetrofit; Retrofit mRetrofit;
@ -75,12 +80,9 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override @Override
public void onSaveInstanceState(@NonNull Bundle outState) { public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
if(mPostData != null) { outState.putString(LAST_ITEM_STATE, mLastItem);
outState.putParcelableArrayList(POST_DATA_PARCELABLE_STATE, mPostData); outState.putBoolean(LOADING_STATE_STATE, mPaginationSynchronizer.isLoading());
outState.putString(LAST_ITEM_STATE, mLastItem); outState.putBoolean(LOAD_SUCCESS_STATE, mPaginationSynchronizer.isLoadingMorePostsSuccess());
outState.putBoolean(LOADING_STATE_STATE, mPaginationSynchronizer.isLoading());
outState.putBoolean(LOAD_SUCCESS_STATE, mPaginationSynchronizer.isLoadSuccess());
}
} }
@Override @Override
@ -131,42 +133,57 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}); });
} }
if(savedInstanceState != null && savedInstanceState.containsKey(POST_DATA_PARCELABLE_STATE)) { mPaginationSynchronizer = new PaginationSynchronizer();
mPostData = savedInstanceState.getParcelableArrayList(POST_DATA_PARCELABLE_STATE); mPaginationSynchronizer.addLastItemSynchronizer(new LastItemSynchronizer() {
mLastItem = savedInstanceState.getString(LAST_ITEM_STATE); @Override
mPaginationSynchronizer = new PaginationSynchronizer(new LastItemSynchronizer() { public void lastItemChanged(String lastItem) {
@Override mLastItem = lastItem;
public void lastItemChanged(String lastItem) { }
mLastItem = lastItem; });
mPostViewModel = ViewModelProviders.of(this).get(PostViewModel.class);
mPostViewModel.getPosts().observe(this, new Observer<ArrayList<Post>>() {
@Override
public void onChanged(@Nullable ArrayList<Post> posts) {
mAdapter.changeDataSet(posts);
if(posts == null) {
Log.i("datachange", Integer.toString(0));
} else {
Log.i("datachange", Integer.toString(posts.size()));
} }
}); }
});
if(mIsBestPost) {
mAdapter = new PostRecyclerViewAdapter(getActivity(), mOauthRetrofit,
mSharedPreferences, mPaginationSynchronizer, mIsBestPost);
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mOauthRetrofit, mPostViewModel, mLinearLayoutManager,
mLastItem, mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadingMorePostsSuccess(),
getResources().getConfiguration().locale));
} else {
mAdapter = new PostRecyclerViewAdapter(getActivity(), mRetrofit,
mSharedPreferences, mPaginationSynchronizer, mIsBestPost);
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mRetrofit, mPostViewModel, mLinearLayoutManager,
mLastItem, mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadingMorePostsSuccess(),
getResources().getConfiguration().locale));
}
mPostRecyclerView.setAdapter(mAdapter);
if(savedInstanceState != null && savedInstanceState.containsKey(LAST_ITEM_STATE)) {
mLastItem = savedInstanceState.getString(LAST_ITEM_STATE);
mPaginationSynchronizer.notifyLastItemChanged(mLastItem);
mPaginationSynchronizer.setLoadSuccess(savedInstanceState.getBoolean(LOAD_SUCCESS_STATE)); mPaginationSynchronizer.setLoadSuccess(savedInstanceState.getBoolean(LOAD_SUCCESS_STATE));
mPaginationSynchronizer.setLoadingState(savedInstanceState.getBoolean(LOADING_STATE_STATE)); mPaginationSynchronizer.setLoadingState(savedInstanceState.getBoolean(LOADING_STATE_STATE));
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter(getActivity(), mOauthRetrofit,
mSharedPreferences, mPostData, mPaginationSynchronizer, mIsBestPost); mProgressBar.setVisibility(View.GONE);
mPostRecyclerView.setAdapter(adapter);
if(mIsBestPost) {
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mOauthRetrofit, mLinearLayoutManager, adapter, mLastItem, mPostData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));
mProgressBar.setVisibility(View.GONE);
} else {
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mRetrofit, mLinearLayoutManager, adapter, mLastItem, mPostData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));
mProgressBar.setVisibility(View.GONE);
}
} else { } else {
mPaginationSynchronizer = new PaginationSynchronizer(new LastItemSynchronizer() {
@Override
public void lastItemChanged(String lastItem) {
mLastItem = lastItem;
}
});
if(mIsBestPost) { if(mIsBestPost) {
fetchBestPost(); fetchBestPost();
} else { } else {
@ -191,27 +208,14 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
public void onResponse(Call<String> call, retrofit2.Response<String> response) { public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(getActivity() != null) { if(getActivity() != null) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); ParsePost.parsePost(response.body(), getResources().getConfiguration().locale,
ClipData clip = ClipData.newPlainText("response", response.body()); new ParsePost.ParsePostListener() {
clipboard.setPrimaryClip(clip);
ParsePost.parsePost(response.body(), new ArrayList<PostData>(),
getResources().getConfiguration().locale, new ParsePost.ParsePostListener() {
@Override @Override
public void onParsePostSuccess(ArrayList<PostData> postData, String lastItem) { public void onParsePostSuccess(ArrayList<Post> newPosts, String lastItem) {
if(isAdded() && getActivity() != null) { if(isAdded() && getActivity() != null) {
mPostData = postData;
mLastItem = lastItem; mLastItem = lastItem;
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter( mPaginationSynchronizer.notifyLastItemChanged(lastItem);
getActivity(), mOauthRetrofit, mSharedPreferences, mPostViewModel.setPosts(newPosts);
postData, mPaginationSynchronizer, mIsBestPost);
mPostRecyclerView.setAdapter(adapter);
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mOauthRetrofit, mLinearLayoutManager, adapter, lastItem, postData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));
mProgressBar.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE);
} }
} }
@ -247,27 +251,14 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
public void onResponse(Call<String> call, retrofit2.Response<String> response) { public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(getActivity() != null) { if(getActivity() != null) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); ParsePost.parsePost(response.body(), getResources().getConfiguration().locale,
ClipData clip = ClipData.newPlainText("response", response.body()); new ParsePost.ParsePostListener() {
clipboard.setPrimaryClip(clip);
ParsePost.parsePost(response.body(), new ArrayList<PostData>(),
getResources().getConfiguration().locale, new ParsePost.ParsePostListener() {
@Override @Override
public void onParsePostSuccess(ArrayList<PostData> postData, String lastItem) { public void onParsePostSuccess(ArrayList<Post> newPosts, String lastItem) {
if(isAdded() && getActivity() != null) { if(isAdded() && getActivity() != null) {
mPostData = postData;
mLastItem = lastItem; mLastItem = lastItem;
PostRecyclerViewAdapter adapter = new PostRecyclerViewAdapter( mPaginationSynchronizer.notifyLastItemChanged(lastItem);
getActivity(), mRetrofit, mSharedPreferences, mPostViewModel.setPosts(newPosts);
postData, mPaginationSynchronizer, mIsBestPost);
mPostRecyclerView.setAdapter(adapter);
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mRetrofit, mLinearLayoutManager, adapter, lastItem, postData,
mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadSuccess(),
getResources().getConfiguration().locale));
mProgressBar.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE);
} }
} }
@ -318,24 +309,26 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override @Override
public void refresh() { public void refresh() {
mLastItem = null; mLastItem = null;
mPaginationSynchronizer = new PaginationSynchronizer(new LastItemSynchronizer() {
@Override
public void lastItemChanged(String lastItem) {
mLastItem = lastItem;
}
});
mPostRecyclerView.clearOnScrollListeners(); mPostRecyclerView.clearOnScrollListeners();
mPostRecyclerView.getRecycledViewPool().clear(); mPostRecyclerView.getRecycledViewPool().clear();
if(mPostData != null) {
mPostData.clear(); mPostViewModel.setPosts(null);
}
mPostData = null;
if(mPostRecyclerView.getAdapter() != null) {
(mPostRecyclerView.getAdapter()).notifyDataSetChanged();
}
if(mIsBestPost) { if(mIsBestPost) {
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mOauthRetrofit, mPostViewModel, mLinearLayoutManager,
mLastItem, mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadingMorePostsSuccess(),
getResources().getConfiguration().locale));
fetchBestPost(); fetchBestPost();
} else { } else {
mPostRecyclerView.addOnScrollListener(new PostPaginationScrollListener(
getActivity(), mRetrofit, mPostViewModel, mLinearLayoutManager,
mLastItem, mPaginationSynchronizer, mSubredditName, mIsBestPost,
mPaginationSynchronizer.isLoading(), mPaginationSynchronizer.isLoadingMorePostsSuccess(),
getResources().getConfiguration().locale));
fetchPost(); fetchPost();
} }
} }

View File

@ -1,7 +1,5 @@
package ml.docilealligator.infinityforreddit; package ml.docilealligator.infinityforreddit;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context; import android.content.Context;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearLayoutManager;
@ -23,9 +21,8 @@ import retrofit2.Retrofit;
class PostPaginationScrollListener extends RecyclerView.OnScrollListener { class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
private Context mContext; private Context mContext;
private Retrofit mRetrofit; private Retrofit mRetrofit;
private PostViewModel mPostViewModel;
private LinearLayoutManager mLayoutManager; private LinearLayoutManager mLayoutManager;
private PostRecyclerViewAdapter mAdapter;
private ArrayList<PostData> mPostData;
private PaginationSynchronizer mPaginationSynchronizer; private PaginationSynchronizer mPaginationSynchronizer;
private String mSubredditName; private String mSubredditName;
@ -35,19 +32,18 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
private Locale locale; private Locale locale;
private String mLastItem; private String mLastItem;
PostPaginationScrollListener(Context context, Retrofit retrofit, LinearLayoutManager layoutManager, PostRecyclerViewAdapter adapter, PostPaginationScrollListener(Context context, Retrofit retrofit, PostViewModel postViewModel,
String lastItem, ArrayList<PostData> postData, PaginationSynchronizer paginationSynchronizer, LinearLayoutManager layoutManager, String lastItem,
final String subredditName, final boolean isBestPost, boolean isLoading, PaginationSynchronizer paginationSynchronizer, final String subredditName,
boolean loadSuccess, Locale locale) { final boolean isBestPost, boolean isLoading, boolean loadSuccess, Locale locale) {
if(context != null) { if(context != null) {
this.mContext = context; mContext = context;
this.mRetrofit = retrofit; mRetrofit = retrofit;
this.mLayoutManager = layoutManager; mPostViewModel = postViewModel;
this.mAdapter = adapter; mLayoutManager = layoutManager;
this.mLastItem = lastItem; mLastItem = lastItem;
this.mPostData = postData; mPaginationSynchronizer = paginationSynchronizer;
this.mPaginationSynchronizer = paginationSynchronizer; mSubredditName = subredditName;
this.mSubredditName = subredditName;
this.isBestPost = isBestPost; this.isBestPost = isBestPost;
this.isLoading = isLoading; this.isLoading = isLoading;
this.loadSuccess = loadSuccess; this.loadSuccess = loadSuccess;
@ -59,12 +55,17 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
if (isBestPost) { if (isBestPost) {
fetchBestPost(); fetchBestPost();
} else { } else {
fetchPost(subredditName, 1); fetchPost(subredditName);
} }
} }
}; };
mPaginationSynchronizer.setPaginationRetryNotifier(paginationRetryNotifier); mPaginationSynchronizer.setPaginationRetryNotifier(paginationRetryNotifier);
//mLastItemSynchronizer = mPaginationSynchronizer.getLastItemSynchronizer(); mPaginationSynchronizer.addLastItemSynchronizer(new LastItemSynchronizer() {
@Override
public void lastItemChanged(String lastItem) {
mLastItem = lastItem;
}
});
} }
} }
@ -80,7 +81,7 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
if(isBestPost) { if(isBestPost) {
fetchBestPost(); fetchBestPost();
} else { } else {
fetchPost(mSubredditName, 1); fetchPost(mSubredditName);
} }
} }
} }
@ -101,16 +102,16 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
@Override @Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) { public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); ParsePost.parsePost(response.body(), locale, new ParsePost.ParsePostListener() {
ClipData clip = ClipData.newPlainText("response", response.body());
clipboard.setPrimaryClip(clip);
ParsePost.parsePost(response.body(), mPostData, locale, new ParsePost.ParsePostListener() {
@Override @Override
public void onParsePostSuccess(ArrayList<PostData> postData, String lastItem) { public void onParsePostSuccess(ArrayList<Post> newPostData, String lastItem) {
if(mAdapter != null) { if(mPostViewModel != null) {
mAdapter.notifyItemRangeInserted(mPostData.size(), postData.size()); ArrayList<Post> posts = mPostViewModel.getPosts().getValue();
posts.addAll(newPostData);
mPostViewModel.setPosts(posts);
mLastItem = lastItem; mLastItem = lastItem;
mPaginationSynchronizer.getLastItemSynchronizer().lastItemChanged(lastItem); mPaginationSynchronizer.notifyLastItemChanged(lastItem);
isLoading = false; isLoading = false;
loadSuccess = true; loadSuccess = true;
@ -140,12 +141,7 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
}); });
} }
private void fetchPost(final String subredditName, final int refreshTime) { private void fetchPost(final String subredditName) {
if(refreshTime < 0) {
loadFailed();
return;
}
isLoading = true; isLoading = true;
loadSuccess = false; loadSuccess = false;
mPaginationSynchronizer.setLoadingState(true); mPaginationSynchronizer.setLoadingState(true);
@ -156,16 +152,16 @@ class PostPaginationScrollListener extends RecyclerView.OnScrollListener {
@Override @Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) { public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); ParsePost.parsePost(response.body(), locale, new ParsePost.ParsePostListener() {
ClipData clip = ClipData.newPlainText("response", response.body());
clipboard.setPrimaryClip(clip);
ParsePost.parsePost(response.body(), mPostData, locale, new ParsePost.ParsePostListener() {
@Override @Override
public void onParsePostSuccess(ArrayList<PostData> postData, String lastItem) { public void onParsePostSuccess(ArrayList<Post> newPostData, String lastItem) {
if(mAdapter != null) { if(mPostViewModel != null) {
mAdapter.notifyItemRangeInserted(mPostData.size(), postData.size()); ArrayList<Post> posts = mPostViewModel.getPosts().getValue();
posts.addAll(newPostData);
mPostViewModel.setPosts(posts);
mLastItem = lastItem; mLastItem = lastItem;
mPaginationSynchronizer.getLastItemSynchronizer().lastItemChanged(lastItem); mPaginationSynchronizer.notifyLastItemChanged(lastItem);
isLoading = false; isLoading = false;
loadSuccess = true; loadSuccess = true;

View File

@ -47,7 +47,7 @@ import retrofit2.Retrofit;
*/ */
class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<PostData> mPostData; private ArrayList<Post> mPostData;
private Context mContext; private Context mContext;
private Retrofit mOauthRetrofit; private Retrofit mOauthRetrofit;
private SharedPreferences mSharedPreferences; private SharedPreferences mSharedPreferences;
@ -62,12 +62,12 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
private static final int VIEW_TYPE_LOADING = 1; private static final int VIEW_TYPE_LOADING = 1;
PostRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, SharedPreferences sharedPreferences, ArrayList<PostData> postData, PaginationSynchronizer paginationSynchronizer, boolean hasMultipleSubreddits) { PostRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, SharedPreferences sharedPreferences, PaginationSynchronizer paginationSynchronizer, boolean hasMultipleSubreddits) {
if(context != null) { if(context != null) {
mContext = context; mContext = context;
mOauthRetrofit = oauthRetrofit; mOauthRetrofit = oauthRetrofit;
mSharedPreferences = sharedPreferences; mSharedPreferences = sharedPreferences;
mPostData = postData; mPostData = new ArrayList<>();
mPaginationSynchronizer = paginationSynchronizer; mPaginationSynchronizer = paginationSynchronizer;
this.hasMultipleSubreddits = hasMultipleSubreddits; this.hasMultipleSubreddits = hasMultipleSubreddits;
glide = Glide.with(mContext.getApplicationContext()); glide = Glide.with(mContext.getApplicationContext());
@ -113,14 +113,16 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
public void loadIconSuccess(String iconImageUrl) { public void loadIconSuccess(String iconImageUrl) {
if(mContext != null && !mPostData.isEmpty()) { if(mContext != null && !mPostData.isEmpty()) {
if(!iconImageUrl.equals("")) { if(!iconImageUrl.equals("")) {
Glide.with(mContext).load(iconImageUrl) glide.load(iconImageUrl)
.into(((DataViewHolder) holder).subredditIconCircleImageView); .into(((DataViewHolder) holder).subredditIconCircleImageView);
} else { } else {
Glide.with(mContext).load(R.drawable.subreddit_default_icon) glide.load(R.drawable.subreddit_default_icon)
.into(((DataViewHolder) holder).subredditIconCircleImageView); .into(((DataViewHolder) holder).subredditIconCircleImageView);
} }
mPostData.get(holder.getAdapterPosition()).setSubredditIconUrl(iconImageUrl); if(holder.getAdapterPosition() >= 0) {
mPostData.get(holder.getAdapterPosition()).setSubredditIconUrl(iconImageUrl);
}
} }
} }
}).execute(); }).execute();
@ -203,7 +205,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
break; break;
} }
if(mPostData.get(position).getPostType() != PostData.TEXT_TYPE && mPostData.get(position).getPostType() != PostData.NO_PREVIEW_LINK_TYPE) { if(mPostData.get(position).getPostType() != Post.TEXT_TYPE && mPostData.get(position).getPostType() != Post.NO_PREVIEW_LINK_TYPE) {
((DataViewHolder) holder).relativeLayout.setVisibility(View.VISIBLE); ((DataViewHolder) holder).relativeLayout.setVisibility(View.VISIBLE);
((DataViewHolder) holder).progressBar.setVisibility(View.VISIBLE); ((DataViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
((DataViewHolder) holder).imageView.setVisibility(View.VISIBLE); ((DataViewHolder) holder).imageView.setVisibility(View.VISIBLE);
@ -222,7 +224,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
switch (mPostData.get(position).getPostType()) { switch (mPostData.get(position).getPostType()) {
case PostData.IMAGE_TYPE: case Post.IMAGE_TYPE:
((DataViewHolder) holder).typeTextView.setText("IMAGE"); ((DataViewHolder) holder).typeTextView.setText("IMAGE");
final String imageUrl = mPostData.get(position).getUrl(); final String imageUrl = mPostData.get(position).getUrl();
@ -238,7 +240,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
}); });
break; break;
case PostData.LINK_TYPE: case Post.LINK_TYPE:
((DataViewHolder) holder).typeTextView.setText("LINK"); ((DataViewHolder) holder).typeTextView.setText("LINK");
((DataViewHolder) holder).imageView.setOnClickListener(new View.OnClickListener() { ((DataViewHolder) holder).imageView.setOnClickListener(new View.OnClickListener() {
@ -253,7 +255,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
}); });
break; break;
case PostData.GIF_VIDEO_TYPE: case Post.GIF_VIDEO_TYPE:
((DataViewHolder) holder).typeTextView.setText("GIF"); ((DataViewHolder) holder).typeTextView.setText("GIF");
final Uri gifVideoUri = Uri.parse(mPostData.get(position).getVideoUrl()); final Uri gifVideoUri = Uri.parse(mPostData.get(position).getVideoUrl());
@ -274,7 +276,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
}); });
break; break;
case PostData.VIDEO_TYPE: case Post.VIDEO_TYPE:
((DataViewHolder) holder).typeTextView.setText("VIDEO"); ((DataViewHolder) holder).typeTextView.setText("VIDEO");
final Uri videoUri = Uri.parse(mPostData.get(position).getVideoUrl()); final Uri videoUri = Uri.parse(mPostData.get(position).getVideoUrl());
@ -295,7 +297,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
}); });
break; break;
case PostData.NO_PREVIEW_LINK_TYPE: case Post.NO_PREVIEW_LINK_TYPE:
((DataViewHolder) holder).typeTextView.setText("LINK"); ((DataViewHolder) holder).typeTextView.setText("LINK");
final String noPreviewLinkUrl = mPostData.get(position).getUrl(); final String noPreviewLinkUrl = mPostData.get(position).getUrl();
((DataViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE); ((DataViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE);
@ -311,7 +313,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
}); });
break; break;
case PostData.TEXT_TYPE: case Post.TEXT_TYPE:
((DataViewHolder) holder).typeTextView.setText("TEXT"); ((DataViewHolder) holder).typeTextView.setText("TEXT");
break; break;
} }
@ -470,15 +472,15 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
mPaginationSynchronizer.setPaginationNotifier(mPaginationNotifier); mPaginationSynchronizer.setPaginationNotifier(mPaginationNotifier);
if(!mPaginationSynchronizer.isLoadSuccess()) { if(!mPaginationSynchronizer.isLoadingMorePostsSuccess()) {
((LoadingViewHolder) holder).progressBar.setVisibility(View.GONE); ((LoadingViewHolder) holder).progressBar.setVisibility(View.GONE);
((LoadingViewHolder) holder).relativeLayout.setVisibility(View.VISIBLE); ((LoadingViewHolder) holder).relativeLayout.setVisibility(View.VISIBLE);
} }
} }
} }
private void loadImage(final RecyclerView.ViewHolder holder, final PostData postData) { private void loadImage(final RecyclerView.ViewHolder holder, final Post post) {
RequestBuilder imageRequestBuilder = glide.load(postData.getPreviewUrl()).listener(new RequestListener<Drawable>() { RequestBuilder imageRequestBuilder = glide.load(post.getPreviewUrl()).listener(new RequestListener<Drawable>() {
@Override @Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
((DataViewHolder) holder).progressBar.setVisibility(View.GONE); ((DataViewHolder) holder).progressBar.setVisibility(View.GONE);
@ -488,7 +490,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
public void onClick(View view) { public void onClick(View view) {
((DataViewHolder) holder).progressBar.setVisibility(View.VISIBLE); ((DataViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
((DataViewHolder) holder).errorRelativeLayout.setVisibility(View.GONE); ((DataViewHolder) holder).errorRelativeLayout.setVisibility(View.GONE);
loadImage(holder, postData); loadImage(holder, post);
} }
}); });
return false; return false;
@ -502,7 +504,7 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
}); });
if(postData.isNSFW()) { if(post.isNSFW()) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 3))) imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 3)))
.into(((DataViewHolder) holder).imageView); .into(((DataViewHolder) holder).imageView);
} else { } else {
@ -522,6 +524,11 @@ class PostRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
return (position >= mPostData.size() ? VIEW_TYPE_LOADING : VIEW_TYPE_DATA); return (position >= mPostData.size() ? VIEW_TYPE_LOADING : VIEW_TYPE_DATA);
} }
void changeDataSet(ArrayList<Post> posts) {
mPostData = posts;
notifyDataSetChanged();
}
class DataViewHolder extends RecyclerView.ViewHolder { class DataViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.card_view_view_post_detail) CardView cardView; @BindView(R.id.card_view_view_post_detail) CardView cardView;
@BindView(R.id.subreddit_icon_circle_image_view_best_post_item) CircleImageView subredditIconCircleImageView; @BindView(R.id.subreddit_icon_circle_image_view_best_post_item) CircleImageView subredditIconCircleImageView;

View File

@ -0,0 +1,22 @@
package ml.docilealligator.infinityforreddit;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import java.util.ArrayList;
class PostViewModel extends ViewModel {
private MutableLiveData<ArrayList<Post>> posts = new MutableLiveData<>();
LiveData<ArrayList<Post>> getPosts() {
if(posts == null) {
setPosts(new ArrayList<Post>());
}
return posts;
}
void setPosts(ArrayList<Post> posts) {
this.posts.postValue(posts);
}
}

View File

@ -57,7 +57,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
private String orientationState = "OS"; private String orientationState = "OS";
private int mMoreCommentCount; private int mMoreCommentCount;
private PostData mPostData; private Post mPost;
@BindView(R.id.coordinator_layout_view_post_detail) CoordinatorLayout mCoordinatorLayout; @BindView(R.id.coordinator_layout_view_post_detail) CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.subreddit_icon_circle_image_view_view_post_detail) CircleImageView mSubredditIconCircleImageView; @BindView(R.id.subreddit_icon_circle_image_view_view_post_detail) CircleImageView mSubredditIconCircleImageView;
@ -112,14 +112,14 @@ public class ViewPostDetailActivity extends AppCompatActivity {
orientation = getResources().getConfiguration().orientation; orientation = getResources().getConfiguration().orientation;
mPostData = getIntent().getExtras().getParcelable(EXTRA_POST_DATA); mPost = getIntent().getExtras().getParcelable(EXTRA_POST_DATA);
TextView titleTextView = findViewById(R.id.title_text_view_view_post_detail); TextView titleTextView = findViewById(R.id.title_text_view_view_post_detail);
titleTextView.setText(mPostData.getTitle()); titleTextView.setText(mPost.getTitle());
if(mPostData.getSubredditIconUrl() == null) { if(mPost.getSubredditIconUrl() == null) {
mLoadSubredditIconAsyncTask = new LoadSubredditIconAsyncTask( mLoadSubredditIconAsyncTask = new LoadSubredditIconAsyncTask(
SubredditRoomDatabase.getDatabase(this).subredditDao(), mPostData.getSubredditNamePrefixed(), SubredditRoomDatabase.getDatabase(this).subredditDao(), mPost.getSubredditNamePrefixed(),
new LoadSubredditIconAsyncTask.LoadSubredditIconAsyncTaskListener() { new LoadSubredditIconAsyncTask.LoadSubredditIconAsyncTaskListener() {
@Override @Override
public void loadIconSuccess(String iconImageUrl) { public void loadIconSuccess(String iconImageUrl) {
@ -131,12 +131,12 @@ public class ViewPostDetailActivity extends AppCompatActivity {
.into(mSubredditIconCircleImageView); .into(mSubredditIconCircleImageView);
} }
mPostData.setSubredditIconUrl(iconImageUrl); mPost.setSubredditIconUrl(iconImageUrl);
} }
}); });
mLoadSubredditIconAsyncTask.execute(); mLoadSubredditIconAsyncTask.execute();
} else if(!mPostData.getSubredditIconUrl().equals("")) { } else if(!mPost.getSubredditIconUrl().equals("")) {
Glide.with(this).load(mPostData.getSubredditIconUrl()).into(mSubredditIconCircleImageView); Glide.with(this).load(mPost.getSubredditIconUrl()).into(mSubredditIconCircleImageView);
} else { } else {
Glide.with(this).load(R.drawable.subreddit_default_icon).into(mSubredditIconCircleImageView); Glide.with(this).load(R.drawable.subreddit_default_icon).into(mSubredditIconCircleImageView);
} }
@ -146,15 +146,15 @@ public class ViewPostDetailActivity extends AppCompatActivity {
public void onClick(View view) { public void onClick(View view) {
Intent intent = new Intent(ViewPostDetailActivity.this, ViewSubredditDetailActivity.class); Intent intent = new Intent(ViewPostDetailActivity.this, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY,
mPostData.getSubredditNamePrefixed().substring(2)); mPost.getSubredditNamePrefixed().substring(2));
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY, intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY,
mPostData.getSubredditNamePrefixed()); mPost.getSubredditNamePrefixed());
intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, false); intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, false);
startActivity(intent); startActivity(intent);
} }
}); });
switch (mPostData.getVoteType()) { switch (mPost.getVoteType()) {
case 1: case 1:
//Upvote //Upvote
mUpvoteButton.setColorFilter(ContextCompat.getColor(this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); mUpvoteButton.setColorFilter(ContextCompat.getColor(this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN);
@ -165,14 +165,14 @@ public class ViewPostDetailActivity extends AppCompatActivity {
break; break;
} }
if(mPostData.getPostType() != PostData.TEXT_TYPE && mPostData.getPostType() != PostData.NO_PREVIEW_LINK_TYPE) { if(mPost.getPostType() != Post.TEXT_TYPE && mPost.getPostType() != Post.NO_PREVIEW_LINK_TYPE) {
mRelativeLayout.setVisibility(View.VISIBLE); mRelativeLayout.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.VISIBLE); mImageView.setVisibility(View.VISIBLE);
mImageView.setRatio((float) mPostData.getPreviewHeight() / (float) mPostData.getPreviewWidth()); mImageView.setRatio((float) mPost.getPreviewHeight() / (float) mPost.getPreviewWidth());
loadImage(); loadImage();
} }
if(mPostData.isCrosspost()) { if(mPost.isCrosspost()) {
mCrosspostImageView.setVisibility(View.VISIBLE); mCrosspostImageView.setVisibility(View.VISIBLE);
} }
@ -180,62 +180,62 @@ public class ViewPostDetailActivity extends AppCompatActivity {
mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
mSubredditTextView.setText(mPostData.getSubredditNamePrefixed()); mSubredditTextView.setText(mPost.getSubredditNamePrefixed());
mSubredditTextView.setOnClickListener(new View.OnClickListener() { mSubredditTextView.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Intent intent = new Intent(ViewPostDetailActivity.this, ViewSubredditDetailActivity.class); Intent intent = new Intent(ViewPostDetailActivity.this, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY,
mPostData.getSubredditNamePrefixed().substring(2)); mPost.getSubredditNamePrefixed().substring(2));
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY, intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY,
mPostData.getSubredditNamePrefixed()); mPost.getSubredditNamePrefixed());
intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, false); intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, false);
startActivity(intent); startActivity(intent);
} }
}); });
mPostTimeTextView.setText(mPostData.getPostTime()); mPostTimeTextView.setText(mPost.getPostTime());
if(mPostData.getGilded() > 0) { if(mPost.getGilded() > 0) {
mGildedImageView.setVisibility(View.VISIBLE); mGildedImageView.setVisibility(View.VISIBLE);
Glide.with(this).load(R.drawable.gold).into(mGildedImageView); Glide.with(this).load(R.drawable.gold).into(mGildedImageView);
mGildedNumberTextView.setVisibility(View.VISIBLE); mGildedNumberTextView.setVisibility(View.VISIBLE);
String gildedNumber = getResources().getString(R.string.gilded, mPostData.getGilded()); String gildedNumber = getResources().getString(R.string.gilded, mPost.getGilded());
mGildedNumberTextView.setText(gildedNumber); mGildedNumberTextView.setText(gildedNumber);
} }
if(mPostData.isNSFW()) { if(mPost.isNSFW()) {
mNSFWTextView.setVisibility(View.VISIBLE); mNSFWTextView.setVisibility(View.VISIBLE);
} }
mScoreTextView.setText(Integer.toString(mPostData.getScore())); mScoreTextView.setText(Integer.toString(mPost.getScore()));
mShareButton.setOnClickListener(new View.OnClickListener() { mShareButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain"); intent.setType("text/plain");
String extraText = mPostData.getTitle() + "\n" + mPostData.getPermalink(); String extraText = mPost.getTitle() + "\n" + mPost.getPermalink();
intent.putExtra(Intent.EXTRA_TEXT, extraText); intent.putExtra(Intent.EXTRA_TEXT, extraText);
startActivity(Intent.createChooser(intent, "Share")); startActivity(Intent.createChooser(intent, "Share"));
} }
}); });
switch (mPostData.getPostType()) { switch (mPost.getPostType()) {
case PostData.IMAGE_TYPE: case Post.IMAGE_TYPE:
mTypeTextView.setText("IMAGE"); mTypeTextView.setText("IMAGE");
mImageView.setOnClickListener(new View.OnClickListener() { mImageView.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Intent intent = new Intent(ViewPostDetailActivity.this, ViewImageActivity.class); Intent intent = new Intent(ViewPostDetailActivity.this, ViewImageActivity.class);
intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, mPostData.getUrl()); intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, mPost.getUrl());
intent.putExtra(ViewImageActivity.TITLE_KEY, mPostData.getTitle()); intent.putExtra(ViewImageActivity.TITLE_KEY, mPost.getTitle());
intent.putExtra(ViewImageActivity.FILE_NAME_KEY, mPostData.getSubredditNamePrefixed().substring(2) intent.putExtra(ViewImageActivity.FILE_NAME_KEY, mPost.getSubredditNamePrefixed().substring(2)
+ "-" + mPostData.getId().substring(3)); + "-" + mPost.getId().substring(3));
startActivity(intent); startActivity(intent);
} }
}); });
break; break;
case PostData.LINK_TYPE: case Post.LINK_TYPE:
mTypeTextView.setText("LINK"); mTypeTextView.setText("LINK");
mImageView.setOnClickListener(new View.OnClickListener() { mImageView.setOnClickListener(new View.OnClickListener() {
@ -246,57 +246,57 @@ public class ViewPostDetailActivity extends AppCompatActivity {
builder.addDefaultShareMenuItem(); builder.addDefaultShareMenuItem();
builder.setToolbarColor(getResources().getColor(R.color.colorPrimary)); builder.setToolbarColor(getResources().getColor(R.color.colorPrimary));
CustomTabsIntent customTabsIntent = builder.build(); CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(ViewPostDetailActivity.this, Uri.parse(mPostData.getUrl())); customTabsIntent.launchUrl(ViewPostDetailActivity.this, Uri.parse(mPost.getUrl()));
} }
}); });
break; break;
case PostData.GIF_VIDEO_TYPE: case Post.GIF_VIDEO_TYPE:
mTypeTextView.setText("GIF"); mTypeTextView.setText("GIF");
final Uri gifVideoUri = Uri.parse(mPostData.getVideoUrl()); final Uri gifVideoUri = Uri.parse(mPost.getVideoUrl());
mImageView.setOnClickListener(new View.OnClickListener() { mImageView.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Intent intent = new Intent(ViewPostDetailActivity.this, ViewVideoActivity.class); Intent intent = new Intent(ViewPostDetailActivity.this, ViewVideoActivity.class);
intent.setData(gifVideoUri); intent.setData(gifVideoUri);
intent.putExtra(ViewVideoActivity.TITLE_KEY, mPostData.getTitle()); intent.putExtra(ViewVideoActivity.TITLE_KEY, mPost.getTitle());
intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, mPostData.isDashVideo()); intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, mPost.isDashVideo());
intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, mPostData.isDownloadableGifOrVideo()); intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, mPost.isDownloadableGifOrVideo());
if(mPostData.isDownloadableGifOrVideo()) { if(mPost.isDownloadableGifOrVideo()) {
intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, mPostData.getGifOrVideoDownloadUrl()); intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, mPost.getGifOrVideoDownloadUrl());
intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, mPostData.getSubredditNamePrefixed()); intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, mPost.getSubredditNamePrefixed());
intent.putExtra(ViewVideoActivity.ID_KEY, mPostData.getId()); intent.putExtra(ViewVideoActivity.ID_KEY, mPost.getId());
} }
startActivity(intent); startActivity(intent);
} }
}); });
break; break;
case PostData.VIDEO_TYPE: case Post.VIDEO_TYPE:
mTypeTextView.setText("VIDEO"); mTypeTextView.setText("VIDEO");
final Uri videoUri = Uri.parse(mPostData.getVideoUrl()); final Uri videoUri = Uri.parse(mPost.getVideoUrl());
mImageView.setOnClickListener(new View.OnClickListener() { mImageView.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Intent intent = new Intent(ViewPostDetailActivity.this, ViewVideoActivity.class); Intent intent = new Intent(ViewPostDetailActivity.this, ViewVideoActivity.class);
intent.setData(videoUri); intent.setData(videoUri);
intent.putExtra(ViewVideoActivity.TITLE_KEY, mPostData.getTitle()); intent.putExtra(ViewVideoActivity.TITLE_KEY, mPost.getTitle());
intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, mPostData.isDashVideo()); intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, mPost.isDashVideo());
intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, mPostData.isDownloadableGifOrVideo()); intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, mPost.isDownloadableGifOrVideo());
if(mPostData.isDownloadableGifOrVideo()) { if(mPost.isDownloadableGifOrVideo()) {
intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, mPostData.getGifOrVideoDownloadUrl()); intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, mPost.getGifOrVideoDownloadUrl());
intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, mPostData.getSubredditNamePrefixed()); intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, mPost.getSubredditNamePrefixed());
intent.putExtra(ViewVideoActivity.ID_KEY, mPostData.getId()); intent.putExtra(ViewVideoActivity.ID_KEY, mPost.getId());
} }
startActivity(intent); startActivity(intent);
} }
}); });
break; break;
case PostData.NO_PREVIEW_LINK_TYPE: case Post.NO_PREVIEW_LINK_TYPE:
mTypeTextView.setText("LINK"); mTypeTextView.setText("LINK");
if(!mPostData.getSelfText().equals("")) { if(!mPost.getSelfText().equals("")) {
mContentTextView.setVisibility(View.VISIBLE); mContentTextView.setVisibility(View.VISIBLE);
mContentTextView.setHtml(mPostData.getSelfText()); mContentTextView.setHtml(mPost.getSelfText());
} }
mNoPreviewLinkImageView.setVisibility(View.VISIBLE); mNoPreviewLinkImageView.setVisibility(View.VISIBLE);
mNoPreviewLinkImageView.setOnClickListener(new View.OnClickListener() { mNoPreviewLinkImageView.setOnClickListener(new View.OnClickListener() {
@ -307,15 +307,15 @@ public class ViewPostDetailActivity extends AppCompatActivity {
builder.addDefaultShareMenuItem(); builder.addDefaultShareMenuItem();
builder.setToolbarColor(getResources().getColor(R.color.colorPrimary)); builder.setToolbarColor(getResources().getColor(R.color.colorPrimary));
CustomTabsIntent customTabsIntent = builder.build(); CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(ViewPostDetailActivity.this, Uri.parse(mPostData.getUrl())); customTabsIntent.launchUrl(ViewPostDetailActivity.this, Uri.parse(mPost.getUrl()));
} }
}); });
break; break;
case PostData.TEXT_TYPE: case Post.TEXT_TYPE:
mTypeTextView.setText("TEXT"); mTypeTextView.setText("TEXT");
if(!mPostData.getSelfText().equals("")) { if(!mPost.getSelfText().equals("")) {
mContentTextView.setVisibility(View.VISIBLE); mContentTextView.setVisibility(View.VISIBLE);
mContentTextView.setHtml(mPostData.getSelfText()); mContentTextView.setHtml(mPost.getSelfText());
} }
break; break;
} }
@ -325,7 +325,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
new ObservableOnSubscribe<Integer>() { new ObservableOnSubscribe<Integer>() {
@Override @Override
public void subscribe(ObservableEmitter<Integer> emitter) throws Exception { public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
emitter.onNext(mPostData.getVoteType()); emitter.onNext(mPost.getVoteType());
emitter.onComplete(); emitter.onComplete();
Log.i("asdasdf", "adasdfasdf"); Log.i("asdasdf", "adasdfasdf");
Toast.makeText(ViewPostDetailActivity.this, "observable", Toast.LENGTH_SHORT).show(); Toast.makeText(ViewPostDetailActivity.this, "observable", Toast.LENGTH_SHORT).show();
@ -367,19 +367,19 @@ public class ViewPostDetailActivity extends AppCompatActivity {
if (mUpvoteButton.getColorFilter() == null) { if (mUpvoteButton.getColorFilter() == null) {
mUpvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); mUpvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN);
if(isDownvotedBefore) { if(isDownvotedBefore) {
mScoreTextView.setText(Integer.toString(mPostData.getScore() + 2)); mScoreTextView.setText(Integer.toString(mPost.getScore() + 2));
} else { } else {
mScoreTextView.setText(Integer.toString(mPostData.getScore() + 1)); mScoreTextView.setText(Integer.toString(mPost.getScore() + 1));
} }
VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() {
@Override @Override
public void onVoteThingSuccess() { public void onVoteThingSuccess() {
mPostData.setVoteType(1); mPost.setVoteType(1);
if(isDownvotedBefore) { if(isDownvotedBefore) {
mPostData.setScore(mPostData.getScore() + 2); mPost.setScore(mPost.getScore() + 2);
} else { } else {
mPostData.setScore(mPostData.getScore() + 1); mPost.setScore(mPost.getScore() + 1);
} }
} }
@ -387,30 +387,30 @@ public class ViewPostDetailActivity extends AppCompatActivity {
public void onVoteThingFail() { public void onVoteThingFail() {
Toast.makeText(ViewPostDetailActivity.this, "Cannot upvote this post", Toast.LENGTH_SHORT).show(); Toast.makeText(ViewPostDetailActivity.this, "Cannot upvote this post", Toast.LENGTH_SHORT).show();
mUpvoteButton.clearColorFilter(); mUpvoteButton.clearColorFilter();
mScoreTextView.setText(Integer.toString(mPostData.getScore())); mScoreTextView.setText(Integer.toString(mPost.getScore()));
mDownvoteButton.setColorFilter(downVoteButtonColorFilter); mDownvoteButton.setColorFilter(downVoteButtonColorFilter);
} }
}, mPostData.getFullName(), RedditUtils.DIR_UPVOTE); }, mPost.getFullName(), RedditUtils.DIR_UPVOTE);
} else { } else {
//Upvoted before //Upvoted before
mUpvoteButton.clearColorFilter(); mUpvoteButton.clearColorFilter();
mScoreTextView.setText(Integer.toString(mPostData.getScore() - 1)); mScoreTextView.setText(Integer.toString(mPost.getScore() - 1));
VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() {
@Override @Override
public void onVoteThingSuccess() { public void onVoteThingSuccess() {
mPostData.setVoteType(0); mPost.setVoteType(0);
mPostData.setScore(mPostData.getScore() - 1); mPost.setScore(mPost.getScore() - 1);
} }
@Override @Override
public void onVoteThingFail() { public void onVoteThingFail() {
Toast.makeText(ViewPostDetailActivity.this, "Cannot unvote this post", Toast.LENGTH_SHORT).show(); Toast.makeText(ViewPostDetailActivity.this, "Cannot unvote this post", Toast.LENGTH_SHORT).show();
mScoreTextView.setText(Integer.toString(mPostData.getScore() + 1)); mScoreTextView.setText(Integer.toString(mPost.getScore() + 1));
mUpvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); mUpvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN);
mPostData.setScore(mPostData.getScore() + 1); mPost.setScore(mPost.getScore() + 1);
} }
}, mPostData.getFullName(), RedditUtils.DIR_UNVOTE); }, mPost.getFullName(), RedditUtils.DIR_UNVOTE);
} }
} }
}); });
@ -427,19 +427,19 @@ public class ViewPostDetailActivity extends AppCompatActivity {
if (mDownvoteButton.getColorFilter() == null) { if (mDownvoteButton.getColorFilter() == null) {
mDownvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN); mDownvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN);
if (isUpvotedBefore) { if (isUpvotedBefore) {
mScoreTextView.setText(Integer.toString(mPostData.getScore() - 2)); mScoreTextView.setText(Integer.toString(mPost.getScore() - 2));
} else { } else {
mScoreTextView.setText(Integer.toString(mPostData.getScore() - 1)); mScoreTextView.setText(Integer.toString(mPost.getScore() - 1));
} }
VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() {
@Override @Override
public void onVoteThingSuccess() { public void onVoteThingSuccess() {
mPostData.setVoteType(-1); mPost.setVoteType(-1);
if(isUpvotedBefore) { if(isUpvotedBefore) {
mPostData.setScore(mPostData.getScore() - 2); mPost.setScore(mPost.getScore() - 2);
} else { } else {
mPostData.setScore(mPostData.getScore() - 1); mPost.setScore(mPost.getScore() - 1);
} }
} }
@ -447,30 +447,30 @@ public class ViewPostDetailActivity extends AppCompatActivity {
public void onVoteThingFail() { public void onVoteThingFail() {
Toast.makeText(ViewPostDetailActivity.this, "Cannot downvote this post", Toast.LENGTH_SHORT).show(); Toast.makeText(ViewPostDetailActivity.this, "Cannot downvote this post", Toast.LENGTH_SHORT).show();
mDownvoteButton.clearColorFilter(); mDownvoteButton.clearColorFilter();
mScoreTextView.setText(Integer.toString(mPostData.getScore())); mScoreTextView.setText(Integer.toString(mPost.getScore()));
mUpvoteButton.setColorFilter(upvoteButtonColorFilter); mUpvoteButton.setColorFilter(upvoteButtonColorFilter);
} }
}, mPostData.getFullName(), RedditUtils.DIR_DOWNVOTE); }, mPost.getFullName(), RedditUtils.DIR_DOWNVOTE);
} else { } else {
//Down voted before //Down voted before
mDownvoteButton.clearColorFilter(); mDownvoteButton.clearColorFilter();
mScoreTextView.setText(Integer.toString(mPostData.getScore() + 1)); mScoreTextView.setText(Integer.toString(mPost.getScore() + 1));
VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() {
@Override @Override
public void onVoteThingSuccess() { public void onVoteThingSuccess() {
mPostData.setVoteType(0); mPost.setVoteType(0);
mPostData.setScore(mPostData.getScore()); mPost.setScore(mPost.getScore());
} }
@Override @Override
public void onVoteThingFail() { public void onVoteThingFail() {
Toast.makeText(ViewPostDetailActivity.this, "Cannot unvote this post", Toast.LENGTH_SHORT).show(); Toast.makeText(ViewPostDetailActivity.this, "Cannot unvote this post", Toast.LENGTH_SHORT).show();
mDownvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN); mDownvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN);
mScoreTextView.setText(Integer.toString(mPostData.getScore())); mScoreTextView.setText(Integer.toString(mPost.getScore()));
mPostData.setScore(mPostData.getScore()); mPost.setScore(mPost.getScore());
} }
}, mPostData.getFullName(), RedditUtils.DIR_UNVOTE); }, mPost.getFullName(), RedditUtils.DIR_UNVOTE);
} }
} }
}); });
@ -479,7 +479,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
private void queryComment() { private void queryComment() {
mCommentProgressbar.setVisibility(View.VISIBLE); mCommentProgressbar.setVisibility(View.VISIBLE);
mNoCommentWrapperLinearLayout.setVisibility(View.GONE); mNoCommentWrapperLinearLayout.setVisibility(View.GONE);
FetchComment.fetchComment(mRetrofit, mPostData.getSubredditNamePrefixed(), mPostData.getId(), FetchComment.fetchComment(mRetrofit, mPost.getSubredditNamePrefixed(), mPost.getId(),
null, new FetchComment.FetchCommentListener() { null, new FetchComment.FetchCommentListener() {
@Override @Override
public void onFetchCommentSuccess(String response) { public void onFetchCommentSuccess(String response) {
@ -494,8 +494,8 @@ public class ViewPostDetailActivity extends AppCompatActivity {
CommentMultiLevelRecyclerViewAdapter adapter = new CommentMultiLevelRecyclerViewAdapter( CommentMultiLevelRecyclerViewAdapter adapter = new CommentMultiLevelRecyclerViewAdapter(
ViewPostDetailActivity.this, mRetrofit, mOauthRetrofit, ViewPostDetailActivity.this, mRetrofit, mOauthRetrofit,
mSharedPreferences, (ArrayList<CommentData>) commentData, mSharedPreferences, (ArrayList<CommentData>) commentData,
mRecyclerView, mPostData.getSubredditNamePrefixed(), mRecyclerView, mPost.getSubredditNamePrefixed(),
mPostData.getId(), getResources().getConfiguration().locale); mPost.getId(), getResources().getConfiguration().locale);
mRecyclerView.removeItemClickListeners(); mRecyclerView.removeItemClickListeners();
mRecyclerView.setToggleItemOnClick(false); mRecyclerView.setToggleItemOnClick(false);
mRecyclerView.setAccordion(false); mRecyclerView.setAccordion(false);
@ -524,8 +524,8 @@ public class ViewPostDetailActivity extends AppCompatActivity {
} }
private void loadImage() { private void loadImage() {
RequestBuilder imageRequestBuilder = Glide.with(this).load(mPostData.getPreviewUrl()) RequestBuilder imageRequestBuilder = Glide.with(this).load(mPost.getPreviewUrl())
.apply(new RequestOptions().override(mPostData.getPreviewWidth(), mPostData.getPreviewHeight())) .apply(new RequestOptions().override(mPost.getPreviewWidth(), mPost.getPreviewHeight()))
.listener(new RequestListener<Drawable>() { .listener(new RequestListener<Drawable>() {
@Override @Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
@ -549,7 +549,7 @@ public class ViewPostDetailActivity extends AppCompatActivity {
} }
}); });
if(mPostData.isNSFW()) { if(mPost.isNSFW()) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 3))) imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 3)))
.into(mImageView); .into(mImageView);
} else { } else {

View File

@ -50,6 +50,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_centerVertical="true" android:layout_centerVertical="true"
android:layout_marginStart="16dp" android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_toEndOf="@id/subreddit_icon_circle_image_view_view_post_detail" android:layout_toEndOf="@id/subreddit_icon_circle_image_view_view_post_detail"
android:layout_toStartOf="@id/post_time_text_view_view_post_detail" android:layout_toStartOf="@id/post_time_text_view_view_post_detail"
android:textColor="#E91E63" /> android:textColor="#E91E63" />

View File

@ -45,6 +45,7 @@
android:layout_toStartOf="@id/post_time_text_view_best_post_item" android:layout_toStartOf="@id/post_time_text_view_best_post_item"
android:layout_marginStart="8dp" android:layout_marginStart="8dp"
android:layout_marginEnd="8dp" android:layout_marginEnd="8dp"
android:layout_centerVertical="true"
android:tint="@color/colorPrimary" android:tint="@color/colorPrimary"
android:visibility="gone"/> android:visibility="gone"/>