From 38be0ba01f6dd08c0be1a830e0d0389405949a56 Mon Sep 17 00:00:00 2001 From: Alex Ning Date: Mon, 7 Jan 2019 19:03:49 +0800 Subject: [PATCH] New feature: Subscribe or unsubscribe to a subreddit. Allow clear text traffic in Android Pie. Rewrite some code in lambda. --- .idea/caches/build_file_checksums.ser | Bin 533 -> 533 bytes app/src/main/AndroidManifest.xml | 3 +- .../java/SubredditDatabase/SubredditDao.java | 5 +- .../java/SubredditDatabase/SubredditData.java | 35 +- .../SubredditRepository.java | 9 +- .../SubredditDatabase/SubredditViewModel.java | 14 +- .../SubscribedSubredditDao.java | 6 + .../infinityforreddit/JSONUtils.java | 1 - .../LastItemSynchronizer.java | 5 - .../infinityforreddit/PaginationNotifier.java | 6 - .../PaginationRetryNotifier.java | 5 - .../PaginationSynchronizer.java | 65 --- .../infinityforreddit/ParseSubredditData.java | 4 +- .../ParseSubscribedThing.java | 2 +- .../PostRecyclerViewAdapter.java | 332 +++++++-------- .../infinityforreddit/RedditAPI.java | 4 + .../infinityforreddit/RedditUtils.java | 3 + .../SubredditSubscription.java | 127 ++++++ ...ubscribedSubredditRecyclerViewAdapter.java | 17 +- .../ViewPostDetailActivity.java | 378 ++++++++---------- .../ViewSubredditDetailActivity.java | 262 ++++++++---- .../layout/activity_view_subreddit_detail.xml | 43 +- app/src/main/res/values/strings.xml | 7 + 23 files changed, 699 insertions(+), 634 deletions(-) delete mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/LastItemSynchronizer.java delete mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/PaginationNotifier.java delete mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/PaginationRetryNotifier.java delete mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/PaginationSynchronizer.java create mode 100644 app/src/main/java/ml/docilealligator/infinityforreddit/SubredditSubscription.java diff --git a/.idea/caches/build_file_checksums.ser b/.idea/caches/build_file_checksums.ser index 36e49c1771b06e378932e35f7456756a4383b487..3ba2f49b93fe803bda173a6b8c23b22f642cf9d3 100644 GIT binary patch delta 16 YcmbQrGL>b*bk+=|pd(2e=TtHR05WI>C;$Ke delta 16 YcmbQrGL>b*bk_7AQ + android:theme="@style/AppTheme" + android:usesCleartextTraffic="true"> getSubredditLiveDataById(String id); - @Query("SELECT * from subreddits WHERE name = :namePrefixed") - LiveData getSubredditLiveDataByNamePrefixed(String namePrefixed); + LiveData getSubredditLiveDataByName(String namePrefixed); @Query("SELECT * from subreddits WHERE name = :namePrefixed LIMIT 1") SubredditData getSubredditData(String namePrefixed); diff --git a/app/src/main/java/SubredditDatabase/SubredditData.java b/app/src/main/java/SubredditDatabase/SubredditData.java index bbd9f7d8..973eda18 100644 --- a/app/src/main/java/SubredditDatabase/SubredditData.java +++ b/app/src/main/java/SubredditDatabase/SubredditData.java @@ -2,23 +2,13 @@ package SubredditDatabase; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; -import android.arch.persistence.room.PrimaryKey; import android.support.annotation.NonNull; +import SubscribedSubredditDatabase.SubscribedSubredditData; + @Entity(tableName = "subreddits") -public class SubredditData { - @PrimaryKey - @NonNull - @ColumnInfo(name = "id") - private String id; - - @ColumnInfo(name = "name") - private String name; - - @ColumnInfo(name = "icon_url") - private String iconUrl; - - @ColumnInfo(name = "banner_url") +public class SubredditData extends SubscribedSubredditData { + @ColumnInfo(name = "banner") private String bannerUrl; @ColumnInfo(name = "description") @@ -28,27 +18,12 @@ public class SubredditData { private int nSubscribers; public SubredditData(@NonNull String id, String name, String iconUrl, String bannerUrl, String description, int nSubscribers) { - this.id = id; - this.name = name; - this.iconUrl = iconUrl; + super(id, name, iconUrl); this.bannerUrl = bannerUrl; this.description = description; this.nSubscribers = nSubscribers; } - @NonNull - public String getId() { - return id; - } - - public String getName() { - return name; - } - - public String getIconUrl() { - return iconUrl; - } - public String getBannerUrl() { return bannerUrl; } diff --git a/app/src/main/java/SubredditDatabase/SubredditRepository.java b/app/src/main/java/SubredditDatabase/SubredditRepository.java index 20eb617a..495f6e3d 100644 --- a/app/src/main/java/SubredditDatabase/SubredditRepository.java +++ b/app/src/main/java/SubredditDatabase/SubredditRepository.java @@ -8,14 +8,11 @@ public class SubredditRepository { private SubredditDao mSubredditDao; private LiveData mSubredditLiveData; - SubredditRepository(Application application, String value, boolean isId) { + SubredditRepository(Application application, String subredditName) { SubredditRoomDatabase db = SubredditRoomDatabase.getDatabase(application); mSubredditDao = db.subredditDao(); - if(isId) { - mSubredditLiveData = mSubredditDao.getSubredditLiveDataById(value); - } else { - mSubredditLiveData = mSubredditDao.getSubredditLiveDataByNamePrefixed(value); - } + + mSubredditLiveData = mSubredditDao.getSubredditLiveDataByName(subredditName); } LiveData getSubredditLiveData() { diff --git a/app/src/main/java/SubredditDatabase/SubredditViewModel.java b/app/src/main/java/SubredditDatabase/SubredditViewModel.java index 10135401..a9d176b3 100644 --- a/app/src/main/java/SubredditDatabase/SubredditViewModel.java +++ b/app/src/main/java/SubredditDatabase/SubredditViewModel.java @@ -11,9 +11,9 @@ public class SubredditViewModel extends AndroidViewModel { private SubredditRepository mSubredditRepository; private LiveData mSubredditLiveData; - SubredditViewModel(Application application, String id, boolean isId) { + SubredditViewModel(Application application, String id) { super(application); - mSubredditRepository = new SubredditRepository(application, id, isId); + mSubredditRepository = new SubredditRepository(application, id); mSubredditLiveData = mSubredditRepository.getSubredditLiveData(); } @@ -30,19 +30,17 @@ public class SubredditViewModel extends AndroidViewModel { @NonNull private final Application mApplication; - private final String value; - private final boolean isId; + private final String subredditName; - public Factory(@NonNull Application application, String value, boolean isId) { + public Factory(@NonNull Application application, String subredditName) { mApplication = application; - this.value = value; - this.isId = isId; + this.subredditName = subredditName; } @Override public T create(Class modelClass) { //noinspection unchecked - return (T) new SubredditViewModel(mApplication, value, isId); + return (T) new SubredditViewModel(mApplication, subredditName); } } } diff --git a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditDao.java b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditDao.java index 7837aa42..ed77c65c 100644 --- a/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditDao.java +++ b/app/src/main/java/SubscribedSubredditDatabase/SubscribedSubredditDao.java @@ -18,4 +18,10 @@ public interface SubscribedSubredditDao { @Query("SELECT * from subscribed_subreddits ORDER BY name COLLATE NOCASE ASC") LiveData> getAllSubscribedSubreddits(); + + @Query("SELECT * from subscribed_subreddits WHERE name = :subredditName LIMIT 1") + SubscribedSubredditData getSubscribedSubreddit(String subredditName); + + @Query("DELETE FROM subscribed_subreddits WHERE name = :subredditName") + void deleteSubscribedSubreddit(String subredditName); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/JSONUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/JSONUtils.java index 163de76d..7e3a2aa5 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/JSONUtils.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/JSONUtils.java @@ -64,7 +64,6 @@ public class JSONUtils { static final String SUBSCRIBERS_KEY = "subscribers"; static final String PUBLIC_DESCRIPTION_KEY = "public_description"; static final String ACTIVE_USER_COUNT_KEY = "active_user_count"; - static final String DISPLAY_NAME_PREFIXED_KEY = "display_name_prefixed"; static final String LINK_ID_KEY = "link_id"; public static final String IS_GOLD_KEY = "is_gold"; public static final String IS_FRIEND_KEY = "is_friend"; diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/LastItemSynchronizer.java b/app/src/main/java/ml/docilealligator/infinityforreddit/LastItemSynchronizer.java deleted file mode 100644 index 3feef840..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/LastItemSynchronizer.java +++ /dev/null @@ -1,5 +0,0 @@ -package ml.docilealligator.infinityforreddit; - -interface LastItemSynchronizer { - void lastItemChanged(String lastItem); -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationNotifier.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationNotifier.java deleted file mode 100644 index 433daa15..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationNotifier.java +++ /dev/null @@ -1,6 +0,0 @@ -package ml.docilealligator.infinityforreddit; - -interface PaginationNotifier { - void LoadMorePostSuccess(); - void LoadMorePostFail(); -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationRetryNotifier.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationRetryNotifier.java deleted file mode 100644 index b9a93f73..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationRetryNotifier.java +++ /dev/null @@ -1,5 +0,0 @@ -package ml.docilealligator.infinityforreddit; - -interface PaginationRetryNotifier { - void retry(); -} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationSynchronizer.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationSynchronizer.java deleted file mode 100644 index 7e53a29d..00000000 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PaginationSynchronizer.java +++ /dev/null @@ -1,65 +0,0 @@ -package ml.docilealligator.infinityforreddit; - -import java.util.ArrayList; - -class PaginationSynchronizer { - private boolean loadingState; - private boolean loadSuccess; - private PaginationNotifier paginationNotifier; - private PaginationRetryNotifier paginationRetryNotifier; - private ArrayList lastItemSynchronizers; - - PaginationSynchronizer() { - lastItemSynchronizers = new ArrayList<>(); - loadingState = false; - loadSuccess = true; - } - - void setLoadingState(boolean isLoading) { - this.loadingState = isLoading; - } - - public boolean isLoading() { - return loadingState; - } - - void loadSuccess(boolean state) { - loadSuccess = state; - if(loadSuccess) { - paginationNotifier.LoadMorePostSuccess(); - } else { - paginationNotifier.LoadMorePostFail(); - } - } - - void setLoadSuccess(boolean loadSuccess) { - this.loadSuccess = loadSuccess; - } - - boolean isLoadingMorePostsSuccess() { - return loadSuccess; - } - - void setPaginationNotifier(PaginationNotifier paginationNotifier) { - this.paginationNotifier = paginationNotifier; - } - - void setPaginationRetryNotifier(PaginationRetryNotifier paginationRetryNotifier) { - this.paginationRetryNotifier = paginationRetryNotifier; - } - - PaginationRetryNotifier getPaginationRetryNotifier() { - return paginationRetryNotifier; - } - - void addLastItemSynchronizer(LastItemSynchronizer lastItemSynchronizer) { - lastItemSynchronizers.add(lastItemSynchronizer); - } - - void notifyLastItemChanged(String lastItem) { - for(LastItemSynchronizer l : lastItemSynchronizers) { - l.lastItemChanged(lastItem); - } - } -} - diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubredditData.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubredditData.java index 5292a976..ab42d660 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubredditData.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubredditData.java @@ -14,7 +14,7 @@ class ParseSubredditData { void onParseSubredditDataFail(); } - static void parseComment(String response, ParseSubredditDataListener parseSubredditDataListener) { + static void parseSubredditData(String response, ParseSubredditDataListener parseSubredditDataListener) { new ParseSubredditDataAsyncTask(response, parseSubredditDataListener).execute(); } @@ -41,7 +41,7 @@ class ParseSubredditData { try { JSONObject data = jsonResponse.getJSONObject(JSONUtils.DATA_KEY); String id = data.getString(JSONUtils.NAME_KEY); - String subredditFullName = data.getString(JSONUtils.DISPLAY_NAME_PREFIXED_KEY); + String subredditFullName = data.getString(JSONUtils.DISPLAY_NAME); String description = data.getString(JSONUtils.PUBLIC_DESCRIPTION_KEY).trim(); String bannerImageUrl = data.getString(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY); if(bannerImageUrl.equals("") || bannerImageUrl.equals("null")) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubscribedThing.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubscribedThing.java index a69d0c22..6b9ef580 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubscribedThing.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ParseSubscribedThing.java @@ -96,7 +96,7 @@ class ParseSubscribedThing { //It's a user newSubscribedUserData.add(new SubscribedUserData(id, name.substring(2), iconUrl)); } else { - String subredditFullName = data.getString(JSONUtils.DISPLAY_NAME_PREFIXED_KEY); + String subredditFullName = data.getString(JSONUtils.DISPLAY_NAME); String description = data.getString(JSONUtils.PUBLIC_DESCRIPTION_KEY).trim(); int nSubscribers = data.getInt(JSONUtils.SUBSCRIBERS_KEY); newSubscribedSubredditData.add(new SubscribedSubredditData(id, name, iconUrl)); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java index 4fd07046..bc851a8f 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/PostRecyclerViewAdapter.java @@ -127,7 +127,8 @@ class PostRecyclerViewAdapter extends PagedListAdapter { + if(canStartActivity) { + canStartActivity = false; + Intent intent = new Intent(mContext, ViewSubredditDetailActivity.class); + intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, + post.getSubredditNamePrefixed().substring(2)); + mContext.startActivity(intent); } }); } else { @@ -374,32 +366,26 @@ class PostRecyclerViewAdapter extends PagedListAdapter { + Intent intent = new Intent(mContext, ViewImageActivity.class); + intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, imageUrl); + intent.putExtra(ViewImageActivity.TITLE_KEY, title); + intent.putExtra(ViewImageActivity.FILE_NAME_KEY, subredditNamePrefixed.substring(2) + + "-" + id.substring(3)); + mContext.startActivity(intent); }); break; case Post.LINK_TYPE: ((DataViewHolder) holder).typeChip.setVisibility(View.VISIBLE); ((DataViewHolder) holder).typeChip.setText("LINK"); - ((DataViewHolder) holder).imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); - // add share action to menu list - builder.addDefaultShareMenuItem(); - builder.setToolbarColor(mContext.getResources().getColor(R.color.colorPrimary)); - CustomTabsIntent customTabsIntent = builder.build(); - customTabsIntent.launchUrl(mContext, Uri.parse(post.getUrl())); - } + ((DataViewHolder) holder).imageView.setOnClickListener(view -> { + CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); + // add share action to menu list + builder.addDefaultShareMenuItem(); + builder.setToolbarColor(mContext.getResources().getColor(R.color.colorPrimary)); + CustomTabsIntent customTabsIntent = builder.build(); + customTabsIntent.launchUrl(mContext, Uri.parse(post.getUrl())); }); break; case Post.GIF_VIDEO_TYPE: @@ -407,21 +393,18 @@ class PostRecyclerViewAdapter extends PagedListAdapter { + Intent intent = new Intent(mContext, ViewVideoActivity.class); + intent.setData(gifVideoUri); + intent.putExtra(ViewVideoActivity.TITLE_KEY, title); + intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, post.isDashVideo()); + intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, post.isDownloadableGifOrVideo()); + if(post.isDownloadableGifOrVideo()) { + intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, post.getGifOrVideoDownloadUrl()); + intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, subredditNamePrefixed); + intent.putExtra(ViewVideoActivity.ID_KEY, id); } + mContext.startActivity(intent); }); break; case Post.VIDEO_TYPE: @@ -437,7 +420,7 @@ class PostRecyclerViewAdapter extends PagedListAdapter { + CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); + // add share action to menu list + builder.addDefaultShareMenuItem(); + builder.setToolbarColor(mContext.getResources().getColor(R.color.colorPrimary)); + CustomTabsIntent customTabsIntent = builder.build(); + customTabsIntent.launchUrl(mContext, Uri.parse(noPreviewLinkUrl)); }); break; case Post.TEXT_TYPE: @@ -465,133 +445,124 @@ class PostRecyclerViewAdapter extends PagedListAdapter { + final boolean isDownvotedBefore = ((DataViewHolder) holder).downvoteButton.getColorFilter() != null; - final ColorFilter downvoteButtonColorFilter = ((DataViewHolder) holder).downvoteButton.getColorFilter(); - ((DataViewHolder) holder).downvoteButton.clearColorFilter(); + final ColorFilter downvoteButtonColorFilter = ((DataViewHolder) holder).downvoteButton.getColorFilter(); + ((DataViewHolder) holder).downvoteButton.clearColorFilter(); - if (((DataViewHolder) holder).upvoteButton.getColorFilter() == null) { - ((DataViewHolder) holder).upvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); - if(isDownvotedBefore) { - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + 2)); - } else { - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + 1)); - } - - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { - @Override - public void onVoteThingSuccess(int position) { - post.setVoteType(1); - if(isDownvotedBefore) { - post.setScore(post.getScore() + 2); - } else { - post.setScore(post.getScore() + 1); - } - } - - @Override - public void onVoteThingFail(int position) { - Toast.makeText(mContext, "Cannot upvote this post", Toast.LENGTH_SHORT).show(); - ((DataViewHolder) holder).upvoteButton.clearColorFilter(); - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore())); - ((DataViewHolder) holder).downvoteButton.setColorFilter(downvoteButtonColorFilter); - } - }, id, RedditUtils.DIR_UPVOTE, holder.getAdapterPosition()); + if (((DataViewHolder) holder).upvoteButton.getColorFilter() == null) { + ((DataViewHolder) holder).upvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); + if(isDownvotedBefore) { + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + 2)); } else { - //Upvoted before - ((DataViewHolder) holder).upvoteButton.clearColorFilter(); - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() - 1)); + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + 1)); + } - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { - @Override - public void onVoteThingSuccess(int position) { - post.setVoteType(0); - post.setScore(post.getScore() - 1); - } - - @Override - public void onVoteThingFail(int position) { - Toast.makeText(mContext, "Cannot unvote this post", Toast.LENGTH_SHORT).show(); - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + 1)); - ((DataViewHolder) holder).upvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + @Override + public void onVoteThingSuccess(int position1) { + post.setVoteType(1); + if(isDownvotedBefore) { + post.setScore(post.getScore() + 2); + } else { post.setScore(post.getScore() + 1); } - }, id, RedditUtils.DIR_UNVOTE, holder.getAdapterPosition()); - } - } - }); - - ((DataViewHolder) holder).downvoteButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final boolean isUpvotedBefore = ((DataViewHolder) holder).upvoteButton.getColorFilter() != null; - - final ColorFilter upvoteButtonColorFilter = ((DataViewHolder) holder).upvoteButton.getColorFilter(); - ((DataViewHolder) holder).upvoteButton.clearColorFilter(); - if (((DataViewHolder) holder).downvoteButton.getColorFilter() == null) { - ((DataViewHolder) holder).downvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN); - if (isUpvotedBefore) { - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() - 2)); - } else { - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() - 1)); } - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { - @Override - public void onVoteThingSuccess(int position) { - post.setVoteType(-1); - if(isUpvotedBefore) { - post.setScore(post.getScore() - 2); - } else { - post.setScore(post.getScore() - 1); - } - } + @Override + public void onVoteThingFail(int position1) { + Toast.makeText(mContext, "Cannot upvote this post", Toast.LENGTH_SHORT).show(); + ((DataViewHolder) holder).upvoteButton.clearColorFilter(); + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore())); + ((DataViewHolder) holder).downvoteButton.setColorFilter(downvoteButtonColorFilter); + } + }, id, RedditUtils.DIR_UPVOTE, holder.getAdapterPosition()); + } else { + //Upvoted before + ((DataViewHolder) holder).upvoteButton.clearColorFilter(); + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() - 1)); - @Override - public void onVoteThingFail(int position) { - Toast.makeText(mContext, "Cannot downvote this post", Toast.LENGTH_SHORT).show(); - ((DataViewHolder) holder).downvoteButton.clearColorFilter(); - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore())); - ((DataViewHolder) holder).upvoteButton.setColorFilter(upvoteButtonColorFilter); - } - }, id, RedditUtils.DIR_DOWNVOTE, holder.getAdapterPosition()); - } else { - //Down voted before - ((DataViewHolder) holder).downvoteButton.clearColorFilter(); - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + 1)); + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + @Override + public void onVoteThingSuccess(int position1) { + post.setVoteType(0); + post.setScore(post.getScore() - 1); + } - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { - @Override - public void onVoteThingSuccess(int position) { - post.setVoteType(0); - post.setScore(post.getScore()); - } - - @Override - public void onVoteThingFail(int position) { - Toast.makeText(mContext, "Cannot unvote this post", Toast.LENGTH_SHORT).show(); - ((DataViewHolder) holder).downvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN); - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore())); - post.setScore(post.getScore()); - } - }, id, RedditUtils.DIR_UNVOTE, holder.getAdapterPosition()); - } + @Override + public void onVoteThingFail(int position1) { + Toast.makeText(mContext, "Cannot unvote this post", Toast.LENGTH_SHORT).show(); + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + 1)); + ((DataViewHolder) holder).upvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); + post.setScore(post.getScore() + 1); + } + }, id, RedditUtils.DIR_UNVOTE, holder.getAdapterPosition()); } }); - ((DataViewHolder) holder).shareButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(Intent.ACTION_SEND); - intent.setType("text/plain"); - String extraText = title + "\n" + permalink; - intent.putExtra(Intent.EXTRA_TEXT, extraText); - mContext.startActivity(Intent.createChooser(intent, "Share")); + ((DataViewHolder) holder).downvoteButton.setOnClickListener(view -> { + final boolean isUpvotedBefore = ((DataViewHolder) holder).upvoteButton.getColorFilter() != null; + + final ColorFilter upvoteButtonColorFilter = ((DataViewHolder) holder).upvoteButton.getColorFilter(); + ((DataViewHolder) holder).upvoteButton.clearColorFilter(); + if (((DataViewHolder) holder).downvoteButton.getColorFilter() == null) { + ((DataViewHolder) holder).downvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN); + if (isUpvotedBefore) { + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() - 2)); + } else { + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() - 1)); + } + + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + @Override + public void onVoteThingSuccess(int position12) { + post.setVoteType(-1); + if(isUpvotedBefore) { + post.setScore(post.getScore() - 2); + } else { + post.setScore(post.getScore() - 1); + } + } + + @Override + public void onVoteThingFail(int position12) { + Toast.makeText(mContext, "Cannot downvote this post", Toast.LENGTH_SHORT).show(); + ((DataViewHolder) holder).downvoteButton.clearColorFilter(); + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore())); + ((DataViewHolder) holder).upvoteButton.setColorFilter(upvoteButtonColorFilter); + } + }, id, RedditUtils.DIR_DOWNVOTE, holder.getAdapterPosition()); + } else { + //Down voted before + ((DataViewHolder) holder).downvoteButton.clearColorFilter(); + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + 1)); + + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + @Override + public void onVoteThingSuccess(int position12) { + post.setVoteType(0); + post.setScore(post.getScore()); + } + + @Override + public void onVoteThingFail(int position12) { + Toast.makeText(mContext, "Cannot unvote this post", Toast.LENGTH_SHORT).show(); + ((DataViewHolder) holder).downvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN); + ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore())); + post.setScore(post.getScore()); + } + }, id, RedditUtils.DIR_UNVOTE, holder.getAdapterPosition()); } }); + + ((DataViewHolder) holder).shareButton.setOnClickListener(view -> { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.setType("text/plain"); + String extraText = title + "\n" + permalink; + intent.putExtra(Intent.EXTRA_TEXT, extraText); + mContext.startActivity(Intent.createChooser(intent, "Share")); + }); } } } @@ -602,13 +573,10 @@ class PostRecyclerViewAdapter extends PagedListAdapter target, boolean isFirstResource) { ((DataViewHolder) holder).progressBar.setVisibility(View.GONE); ((DataViewHolder) holder).errorRelativeLayout.setVisibility(View.VISIBLE); - ((DataViewHolder)holder).errorRelativeLayout.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - ((DataViewHolder) holder).progressBar.setVisibility(View.VISIBLE); - ((DataViewHolder) holder).errorRelativeLayout.setVisibility(View.GONE); - loadImage(holder, post); - } + ((DataViewHolder)holder).errorRelativeLayout.setOnClickListener(view -> { + ((DataViewHolder) holder).progressBar.setVisibility(View.VISIBLE); + ((DataViewHolder) holder).errorRelativeLayout.setVisibility(View.GONE); + loadImage(holder, post); }); return false; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditAPI.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditAPI.java index 657f10d6..25b74317 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditAPI.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditAPI.java @@ -41,4 +41,8 @@ public interface RedditAPI { @GET("user/{username}/about.json?raw_json=1") Call getUserData(@Path("username") String username); + + @FormUrlEncoded + @POST("api/subscribe") + Call subredditSubscription(@HeaderMap Map headers, @FieldMap Map params); } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditUtils.java b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditUtils.java index ad081cc2..d598f684 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/RedditUtils.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/RedditUtils.java @@ -45,6 +45,9 @@ public class RedditUtils { static final String DIR_DOWNVOTE = "-1"; static final String RANK = "10"; + static final String ACTION_KEY = "action"; + static final String SR_NAME_KEY = "sr_name"; + static Map getHttpBasicAuthHeader() { Map params = new HashMap<>(); String credentials = String.format("%s:%s", RedditUtils.CLIENT_ID, ""); diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditSubscription.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditSubscription.java new file mode 100644 index 00000000..4a5f9ef5 --- /dev/null +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SubredditSubscription.java @@ -0,0 +1,127 @@ +package ml.docilealligator.infinityforreddit; + +import android.content.SharedPreferences; +import android.os.AsyncTask; +import android.support.annotation.NonNull; +import android.util.Log; + +import java.util.HashMap; +import java.util.Map; + +import SubredditDatabase.SubredditData; +import SubscribedSubredditDatabase.SubscribedSubredditDao; +import SubscribedSubredditDatabase.SubscribedSubredditData; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Retrofit; + +class SubredditSubscription { + interface SubredditSubscriptionListener { + void onSubredditSubscriptionSuccess(); + void onSubredditSubscriptionFail(); + } + + static void subscribeToSubreddit(Retrofit oauthRetrofit, Retrofit retrofit, + SharedPreferences authInfoSharedPreferences, String subredditName, + SubscribedSubredditDao subscribedSubredditDao, + SubredditSubscriptionListener subredditSubscriptionListener) { + subredditSubscription(oauthRetrofit, retrofit, authInfoSharedPreferences, subredditName, "sub", + subscribedSubredditDao, subredditSubscriptionListener); + } + + static void unsubscribeToSubreddit(Retrofit oauthRetrofit, SharedPreferences authInfoSharedPreferences, + String subredditName, SubscribedSubredditDao subscribedSubredditDao, + SubredditSubscriptionListener subredditSubscriptionListener) { + subredditSubscription(oauthRetrofit, null, authInfoSharedPreferences, subredditName, "unsub", + subscribedSubredditDao,subredditSubscriptionListener); + } + + private static void subredditSubscription(Retrofit oauthRetrofit, Retrofit retrofit, SharedPreferences authInfoSharedPreferences, + String subredditName, String action, SubscribedSubredditDao subscribedSubredditDao, + SubredditSubscriptionListener subredditSubscriptionListener) { + RedditAPI api = oauthRetrofit.create(RedditAPI.class); + + String accessToken = authInfoSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN_KEY, ""); + + Map params = new HashMap<>(); + params.put(RedditUtils.ACTION_KEY, action); + params.put(RedditUtils.SR_NAME_KEY, subredditName); + + Call subredditSubscriptionCall = api.subredditSubscription(RedditUtils.getOAuthHeader(accessToken), params); + subredditSubscriptionCall.enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull retrofit2.Response response) { + if(response.isSuccessful()) { + if(action.equals("sub")) { + FetchSubredditData.fetchSubredditData(retrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() { + @Override + public void onFetchSubredditDataSuccess(String response) { + ParseSubredditData.parseSubredditData(response, new ParseSubredditData.ParseSubredditDataListener() { + @Override + public void onParseSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { + new UpdateSubscriptionAsyncTask(subscribedSubredditDao, + subredditData, true).execute(); + } + + @Override + public void onParseSubredditDataFail() { + + } + }); + } + + @Override + public void onFetchSubredditDataFail() { + + } + }); + } else { + new UpdateSubscriptionAsyncTask(subscribedSubredditDao, subredditName, false).execute(); + } + subredditSubscriptionListener.onSubredditSubscriptionSuccess(); + } else { + Log.i("call failed", response.message()); + subredditSubscriptionListener.onSubredditSubscriptionFail(); + } + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + Log.i("call failed", t.getMessage()); + subredditSubscriptionListener.onSubredditSubscriptionFail(); + } + }); + } + + private static class UpdateSubscriptionAsyncTask extends AsyncTask { + + private SubscribedSubredditDao subscribedSubredditDao; + private String subredditName; + private SubscribedSubredditData subscribedSubredditData; + private boolean isSubscribing; + + UpdateSubscriptionAsyncTask(SubscribedSubredditDao subscribedSubredditDao, String subredditName, + boolean isSubscribing) { + this.subscribedSubredditDao = subscribedSubredditDao; + this.subredditName = subredditName; + this.isSubscribing = isSubscribing; + } + + UpdateSubscriptionAsyncTask(SubscribedSubredditDao subscribedSubredditDao, SubscribedSubredditData subscribedSubredditData, + boolean isSubscribing) { + this.subscribedSubredditDao = subscribedSubredditDao; + this.subscribedSubredditData = subscribedSubredditData; + this.isSubscribing = isSubscribing; + } + + @Override + protected Void doInBackground(Void... voids) { + if(isSubscribing) { + subscribedSubredditDao.insert(subscribedSubredditData); + } else { + subscribedSubredditDao.deleteSubscribedSubreddit(subredditName);; + } + return null; + } + } +} diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedSubredditRecyclerViewAdapter.java b/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedSubredditRecyclerViewAdapter.java index 9bc4f5e7..c737298d 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedSubredditRecyclerViewAdapter.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/SubscribedSubredditRecyclerViewAdapter.java @@ -50,17 +50,12 @@ class SubscribedSubredditRecyclerViewAdapter extends RecyclerView.Adapter= 0) { - mOnItemClickListener.onClick(); - Intent intent = new Intent(mContext, ViewSubredditDetailActivity.class); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, mSubscribedSubredditData.get(viewHolder.getAdapterPosition()).getName()); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY, mSubscribedSubredditData.get(viewHolder.getAdapterPosition()).getId()); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, true); - mContext.startActivity(intent); - } + viewHolder.itemView.setOnClickListener(view -> { + if(viewHolder.getAdapterPosition() >= 0) { + mOnItemClickListener.onClick(); + Intent intent = new Intent(mContext, ViewSubredditDetailActivity.class); + intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, mSubscribedSubredditData.get(viewHolder.getAdapterPosition()).getName()); + mContext.startActivity(intent); } }); if(!mSubscribedSubredditData.get(i).getIconUrl().equals("")) { diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewPostDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewPostDetailActivity.java index 4e813b22..de7b7992 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewPostDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewPostDetailActivity.java @@ -123,20 +123,17 @@ public class ViewPostDetailActivity extends AppCompatActivity { if(mPost.getSubredditIconUrl() == null) { mLoadSubredditIconAsyncTask = new LoadSubredditIconAsyncTask( SubredditRoomDatabase.getDatabase(this).subredditDao(), mPost.getSubredditNamePrefixed(), - new LoadSubredditIconAsyncTask.LoadSubredditIconAsyncTaskListener() { - @Override - public void loadIconSuccess(String iconImageUrl) { - if(!iconImageUrl.equals("")) { - Glide.with(ViewPostDetailActivity.this).load(iconImageUrl) - .into(mSubredditIconCircleImageView); - } else { - Glide.with(ViewPostDetailActivity.this).load(R.drawable.subreddit_default_icon) - .into(mSubredditIconCircleImageView); - } + iconImageUrl -> { + if(!iconImageUrl.equals("")) { + Glide.with(ViewPostDetailActivity.this).load(iconImageUrl) + .into(mSubredditIconCircleImageView); + } else { + Glide.with(ViewPostDetailActivity.this).load(R.drawable.subreddit_default_icon) + .into(mSubredditIconCircleImageView); + } - mPost.setSubredditIconUrl(iconImageUrl); - } - }); + mPost.setSubredditIconUrl(iconImageUrl); + }); mLoadSubredditIconAsyncTask.execute(); } else if(!mPost.getSubredditIconUrl().equals("")) { Glide.with(this).load(mPost.getSubredditIconUrl()).into(mSubredditIconCircleImageView); @@ -144,17 +141,11 @@ public class ViewPostDetailActivity extends AppCompatActivity { Glide.with(this).load(R.drawable.subreddit_default_icon).into(mSubredditIconCircleImageView); } - mSubredditIconCircleImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(ViewPostDetailActivity.this, ViewSubredditDetailActivity.class); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, - mPost.getSubredditNamePrefixed().substring(2)); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY, - mPost.getSubredditNamePrefixed()); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, false); - startActivity(intent); - } + mSubredditIconCircleImageView.setOnClickListener(view -> { + Intent intent = new Intent(ViewPostDetailActivity.this, ViewSubredditDetailActivity.class); + intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, + mPost.getSubredditNamePrefixed().substring(2)); + startActivity(intent); }); switch (mPost.getVoteType()) { @@ -184,17 +175,11 @@ public class ViewPostDetailActivity extends AppCompatActivity { mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); mSubredditTextView.setText(mPost.getSubredditNamePrefixed()); - mSubredditTextView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(ViewPostDetailActivity.this, ViewSubredditDetailActivity.class); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, - mPost.getSubredditNamePrefixed().substring(2)); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY, - mPost.getSubredditNamePrefixed()); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, false); - startActivity(intent); - } + mSubredditTextView.setOnClickListener(view -> { + Intent intent = new Intent(ViewPostDetailActivity.this, ViewSubredditDetailActivity.class); + intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, + mPost.getSubredditNamePrefixed().substring(2)); + startActivity(intent); }); mPostTimeTextView.setText(mPost.getPostTime()); @@ -212,87 +197,72 @@ public class ViewPostDetailActivity extends AppCompatActivity { } mScoreTextView.setText(Integer.toString(mPost.getScore())); - mShareButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(Intent.ACTION_SEND); - intent.setType("text/plain"); - String extraText = mPost.getTitle() + "\n" + mPost.getPermalink(); - intent.putExtra(Intent.EXTRA_TEXT, extraText); - startActivity(Intent.createChooser(intent, "Share")); - } + mShareButton.setOnClickListener(view -> { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.setType("text/plain"); + String extraText = mPost.getTitle() + "\n" + mPost.getPermalink(); + intent.putExtra(Intent.EXTRA_TEXT, extraText); + startActivity(Intent.createChooser(intent, "Share")); }); switch (mPost.getPostType()) { case Post.IMAGE_TYPE: mTypeChip.setText("IMAGE"); - mImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(ViewPostDetailActivity.this, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, mPost.getUrl()); - intent.putExtra(ViewImageActivity.TITLE_KEY, mPost.getTitle()); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, mPost.getSubredditNamePrefixed().substring(2) - + "-" + mPost.getId().substring(3)); - startActivity(intent); - } + mImageView.setOnClickListener(view -> { + Intent intent = new Intent(ViewPostDetailActivity.this, ViewImageActivity.class); + intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, mPost.getUrl()); + intent.putExtra(ViewImageActivity.TITLE_KEY, mPost.getTitle()); + intent.putExtra(ViewImageActivity.FILE_NAME_KEY, mPost.getSubredditNamePrefixed().substring(2) + + "-" + mPost.getId().substring(3)); + startActivity(intent); }); break; case Post.LINK_TYPE: mTypeChip.setText("LINK"); - mImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); - // add share action to menu list - builder.addDefaultShareMenuItem(); - builder.setToolbarColor(getResources().getColor(R.color.colorPrimary)); - CustomTabsIntent customTabsIntent = builder.build(); - customTabsIntent.launchUrl(ViewPostDetailActivity.this, Uri.parse(mPost.getUrl())); - } + mImageView.setOnClickListener(view -> { + CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); + // add share action to menu list + builder.addDefaultShareMenuItem(); + builder.setToolbarColor(getResources().getColor(R.color.colorPrimary)); + CustomTabsIntent customTabsIntent = builder.build(); + customTabsIntent.launchUrl(ViewPostDetailActivity.this, Uri.parse(mPost.getUrl())); }); break; case Post.GIF_VIDEO_TYPE: mTypeChip.setText("GIF"); final Uri gifVideoUri = Uri.parse(mPost.getVideoUrl()); - mImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(ViewPostDetailActivity.this, ViewVideoActivity.class); - intent.setData(gifVideoUri); - intent.putExtra(ViewVideoActivity.TITLE_KEY, mPost.getTitle()); - intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, mPost.isDashVideo()); - intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, mPost.isDownloadableGifOrVideo()); - if(mPost.isDownloadableGifOrVideo()) { - intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, mPost.getGifOrVideoDownloadUrl()); - intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, mPost.getSubredditNamePrefixed()); - intent.putExtra(ViewVideoActivity.ID_KEY, mPost.getId()); - } - startActivity(intent); + mImageView.setOnClickListener(view -> { + Intent intent = new Intent(ViewPostDetailActivity.this, ViewVideoActivity.class); + intent.setData(gifVideoUri); + intent.putExtra(ViewVideoActivity.TITLE_KEY, mPost.getTitle()); + intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, mPost.isDashVideo()); + intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, mPost.isDownloadableGifOrVideo()); + if(mPost.isDownloadableGifOrVideo()) { + intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, mPost.getGifOrVideoDownloadUrl()); + intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, mPost.getSubredditNamePrefixed()); + intent.putExtra(ViewVideoActivity.ID_KEY, mPost.getId()); } + startActivity(intent); }); break; case Post.VIDEO_TYPE: mTypeChip.setText("VIDEO"); final Uri videoUri = Uri.parse(mPost.getVideoUrl()); - mImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(ViewPostDetailActivity.this, ViewVideoActivity.class); - intent.setData(videoUri); - intent.putExtra(ViewVideoActivity.TITLE_KEY, mPost.getTitle()); - intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, mPost.isDashVideo()); - intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, mPost.isDownloadableGifOrVideo()); - if(mPost.isDownloadableGifOrVideo()) { - intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, mPost.getGifOrVideoDownloadUrl()); - intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, mPost.getSubredditNamePrefixed()); - intent.putExtra(ViewVideoActivity.ID_KEY, mPost.getId()); - } - startActivity(intent); + mImageView.setOnClickListener(view -> { + Intent intent = new Intent(ViewPostDetailActivity.this, ViewVideoActivity.class); + intent.setData(videoUri); + intent.putExtra(ViewVideoActivity.TITLE_KEY, mPost.getTitle()); + intent.putExtra(ViewVideoActivity.IS_DASH_VIDEO_KEY, mPost.isDashVideo()); + intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, mPost.isDownloadableGifOrVideo()); + if(mPost.isDownloadableGifOrVideo()) { + intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, mPost.getGifOrVideoDownloadUrl()); + intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, mPost.getSubredditNamePrefixed()); + intent.putExtra(ViewVideoActivity.ID_KEY, mPost.getId()); } + startActivity(intent); }); break; case Post.NO_PREVIEW_LINK_TYPE: @@ -302,16 +272,13 @@ public class ViewPostDetailActivity extends AppCompatActivity { mContentTextView.setHtml(mPost.getSelfText()); } mNoPreviewLinkImageView.setVisibility(View.VISIBLE); - mNoPreviewLinkImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); - // add share action to menu list - builder.addDefaultShareMenuItem(); - builder.setToolbarColor(getResources().getColor(R.color.colorPrimary)); - CustomTabsIntent customTabsIntent = builder.build(); - customTabsIntent.launchUrl(ViewPostDetailActivity.this, Uri.parse(mPost.getUrl())); - } + mNoPreviewLinkImageView.setOnClickListener(view -> { + CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); + // add share action to menu list + builder.addDefaultShareMenuItem(); + builder.setToolbarColor(getResources().getColor(R.color.colorPrimary)); + CustomTabsIntent customTabsIntent = builder.build(); + customTabsIntent.launchUrl(ViewPostDetailActivity.this, Uri.parse(mPost.getUrl())); }); break; case Post.TEXT_TYPE: @@ -324,123 +291,115 @@ public class ViewPostDetailActivity extends AppCompatActivity { } queryComment(); - mUpvoteButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - //observable.subscribe(observer); - final boolean isDownvotedBefore = mDownvoteButton.getColorFilter() != null; + mUpvoteButton.setOnClickListener(view -> { + final boolean isDownvotedBefore = mDownvoteButton.getColorFilter() != null; - final ColorFilter downVoteButtonColorFilter = mDownvoteButton.getColorFilter(); - mDownvoteButton.clearColorFilter(); + final ColorFilter downVoteButtonColorFilter = mDownvoteButton.getColorFilter(); + mDownvoteButton.clearColorFilter(); - if (mUpvoteButton.getColorFilter() == null) { - mUpvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); - if(isDownvotedBefore) { - mScoreTextView.setText(Integer.toString(mPost.getScore() + 2)); - } else { - mScoreTextView.setText(Integer.toString(mPost.getScore() + 1)); - } - - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { - @Override - public void onVoteThingSuccess() { - mPost.setVoteType(1); - if(isDownvotedBefore) { - mPost.setScore(mPost.getScore() + 2); - } else { - mPost.setScore(mPost.getScore() + 1); - } - } - - @Override - public void onVoteThingFail() { - Toast.makeText(ViewPostDetailActivity.this, "Cannot upvote this post", Toast.LENGTH_SHORT).show(); - mUpvoteButton.clearColorFilter(); - mScoreTextView.setText(Integer.toString(mPost.getScore())); - mDownvoteButton.setColorFilter(downVoteButtonColorFilter); - } - }, mPost.getFullName(), RedditUtils.DIR_UPVOTE); + if (mUpvoteButton.getColorFilter() == null) { + mUpvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); + if(isDownvotedBefore) { + mScoreTextView.setText(Integer.toString(mPost.getScore() + 2)); } else { - //Upvoted before - mUpvoteButton.clearColorFilter(); - mScoreTextView.setText(Integer.toString(mPost.getScore() - 1)); + mScoreTextView.setText(Integer.toString(mPost.getScore() + 1)); + } - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { - @Override - public void onVoteThingSuccess() { - mPost.setVoteType(0); - mPost.setScore(mPost.getScore() - 1); - } - - @Override - public void onVoteThingFail() { - Toast.makeText(ViewPostDetailActivity.this, "Cannot unvote this post", Toast.LENGTH_SHORT).show(); - mScoreTextView.setText(Integer.toString(mPost.getScore() + 1)); - mUpvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { + @Override + public void onVoteThingSuccess() { + mPost.setVoteType(1); + if(isDownvotedBefore) { + mPost.setScore(mPost.getScore() + 2); + } else { mPost.setScore(mPost.getScore() + 1); } - }, mPost.getFullName(), RedditUtils.DIR_UNVOTE); - } + } + + @Override + public void onVoteThingFail() { + Toast.makeText(ViewPostDetailActivity.this, "Cannot upvote this post", Toast.LENGTH_SHORT).show(); + mUpvoteButton.clearColorFilter(); + mScoreTextView.setText(Integer.toString(mPost.getScore())); + mDownvoteButton.setColorFilter(downVoteButtonColorFilter); + } + }, mPost.getFullName(), RedditUtils.DIR_UPVOTE); + } else { + //Upvoted before + mUpvoteButton.clearColorFilter(); + mScoreTextView.setText(Integer.toString(mPost.getScore() - 1)); + + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { + @Override + public void onVoteThingSuccess() { + mPost.setVoteType(0); + mPost.setScore(mPost.getScore() - 1); + } + + @Override + public void onVoteThingFail() { + Toast.makeText(ViewPostDetailActivity.this, "Cannot unvote this post", Toast.LENGTH_SHORT).show(); + mScoreTextView.setText(Integer.toString(mPost.getScore() + 1)); + mUpvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN); + mPost.setScore(mPost.getScore() + 1); + } + }, mPost.getFullName(), RedditUtils.DIR_UNVOTE); } }); - mDownvoteButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - //observable.subscribe(observer); - final boolean isUpvotedBefore = mUpvoteButton.getColorFilter() != null; + mDownvoteButton.setOnClickListener(view -> { + final boolean isUpvotedBefore = mUpvoteButton.getColorFilter() != null; - final ColorFilter upvoteButtonColorFilter = mUpvoteButton.getColorFilter(); - mUpvoteButton.clearColorFilter(); + final ColorFilter upvoteButtonColorFilter = mUpvoteButton.getColorFilter(); + mUpvoteButton.clearColorFilter(); - if (mDownvoteButton.getColorFilter() == null) { - mDownvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN); - if (isUpvotedBefore) { - mScoreTextView.setText(Integer.toString(mPost.getScore() - 2)); - } else { - mScoreTextView.setText(Integer.toString(mPost.getScore() - 1)); + if (mDownvoteButton.getColorFilter() == null) { + mDownvoteButton.setColorFilter(ContextCompat.getColor(ViewPostDetailActivity.this, R.color.minusButtonColor), android.graphics.PorterDuff.Mode.SRC_IN); + if (isUpvotedBefore) { + mScoreTextView.setText(Integer.toString(mPost.getScore() - 2)); + } else { + mScoreTextView.setText(Integer.toString(mPost.getScore() - 1)); + } + + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { + @Override + public void onVoteThingSuccess() { + mPost.setVoteType(-1); + if(isUpvotedBefore) { + mPost.setScore(mPost.getScore() - 2); + } else { + mPost.setScore(mPost.getScore() - 1); + } } - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { - @Override - public void onVoteThingSuccess() { - mPost.setVoteType(-1); - if(isUpvotedBefore) { - mPost.setScore(mPost.getScore() - 2); - } else { - mPost.setScore(mPost.getScore() - 1); - } - } + @Override + public void onVoteThingFail() { + Toast.makeText(ViewPostDetailActivity.this, "Cannot downvote this post", Toast.LENGTH_SHORT).show(); + mDownvoteButton.clearColorFilter(); + mScoreTextView.setText(Integer.toString(mPost.getScore())); + mUpvoteButton.setColorFilter(upvoteButtonColorFilter); + } + }, mPost.getFullName(), RedditUtils.DIR_DOWNVOTE); + } else { + //Down voted before + mDownvoteButton.clearColorFilter(); + mScoreTextView.setText(Integer.toString(mPost.getScore() + 1)); - @Override - public void onVoteThingFail() { - Toast.makeText(ViewPostDetailActivity.this, "Cannot downvote this post", Toast.LENGTH_SHORT).show(); - mDownvoteButton.clearColorFilter(); - mScoreTextView.setText(Integer.toString(mPost.getScore())); - mUpvoteButton.setColorFilter(upvoteButtonColorFilter); - } - }, mPost.getFullName(), RedditUtils.DIR_DOWNVOTE); - } else { - //Down voted before - mDownvoteButton.clearColorFilter(); - mScoreTextView.setText(Integer.toString(mPost.getScore() + 1)); + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { + @Override + public void onVoteThingSuccess() { + mPost.setVoteType(0); + mPost.setScore(mPost.getScore()); + } - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingWithoutPositionListener() { - @Override - public void onVoteThingSuccess() { - mPost.setVoteType(0); - mPost.setScore(mPost.getScore()); - } - - @Override - public void onVoteThingFail() { - 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); - mScoreTextView.setText(Integer.toString(mPost.getScore())); - mPost.setScore(mPost.getScore()); - } - }, mPost.getFullName(), RedditUtils.DIR_UNVOTE); - } + @Override + public void onVoteThingFail() { + 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); + mScoreTextView.setText(Integer.toString(mPost.getScore())); + mPost.setScore(mPost.getScore()); + } + }, mPost.getFullName(), RedditUtils.DIR_UNVOTE); } }); } @@ -500,13 +459,10 @@ public class ViewPostDetailActivity extends AppCompatActivity { public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { mLoadImageProgressBar.setVisibility(View.GONE); mLoadImageErrorTextView.setVisibility(View.VISIBLE); - mLoadImageErrorTextView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - mLoadImageProgressBar.setVisibility(View.VISIBLE); - mLoadImageErrorTextView.setVisibility(View.GONE); - loadImage(); - } + mLoadImageErrorTextView.setOnClickListener(view -> { + mLoadImageProgressBar.setVisibility(View.VISIBLE); + mLoadImageErrorTextView.setVisibility(View.GONE); + loadImage(); }); return false; } diff --git a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java index 38b1ba0d..cf9b0f9a 100644 --- a/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java +++ b/app/src/main/java/ml/docilealligator/infinityforreddit/ViewSubredditDetailActivity.java @@ -1,15 +1,18 @@ package ml.docilealligator.infinityforreddit; -import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; +import android.content.SharedPreferences; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; +import android.support.design.chip.Chip; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; +import android.support.design.widget.CoordinatorLayout; +import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; @@ -37,6 +40,9 @@ import SubredditDatabase.SubredditDao; import SubredditDatabase.SubredditData; import SubredditDatabase.SubredditRoomDatabase; import SubredditDatabase.SubredditViewModel; +import SubscribedSubredditDatabase.SubscribedSubredditDao; +import SubscribedSubredditDatabase.SubscribedSubredditData; +import SubscribedSubredditDatabase.SubscribedSubredditRoomDatabase; import butterknife.BindView; import butterknife.ButterKnife; import jp.wasabeef.glide.transformations.RoundedCornersTransformation; @@ -45,27 +51,38 @@ import retrofit2.Retrofit; public class ViewSubredditDetailActivity extends AppCompatActivity { static final String EXTRA_SUBREDDIT_NAME_KEY = "ESN"; - static final String EXTRA_SUBREDDIT_VALUE_KEY = "ESV"; - static final String EXTRA_QUERY_BY_ID_KEY = "EQBI"; private static final String FRAGMENT_OUT_STATE_KEY = "FOSK"; + @BindView(R.id.coordinator_layout_view_subreddit_detail_activity) CoordinatorLayout coordinatorLayout; @BindView(R.id.banner_image_view_view_subreddit_detail_activity) ImageView bannerImageView; @BindView(R.id.icon_gif_image_view_view_subreddit_detail_activity) GifImageView iconGifImageView; + @BindView(R.id.subscribe_subreddit_chip_view_subreddit_detail_activity) Chip subscribeSubredditChip; @BindView(R.id.subreddit_name_text_view_view_subreddit_detail_activity) TextView subredditNameTextView; @BindView(R.id.subscriber_count_text_view_view_subreddit_detail_activity) TextView nSubscribersTextView; @BindView(R.id.online_subscriber_count_text_view_view_subreddit_detail_activity) TextView nOnlineSubscribersTextView; @BindView(R.id.description_text_view_view_subreddit_detail_activity) TextView descriptionTextView; + private boolean subscriptionReady = false; + private RequestManager glide; private Fragment mFragment; + private SubscribedSubredditDao subscribedSubredditDao; private SubredditViewModel mSubredditViewModel; @Inject @Named("no_oauth") Retrofit mRetrofit; + @Inject + @Named("oauth") + Retrofit mOauthRetrofit; + + @Inject + @Named("auth_info") + SharedPreferences sharedPreferences; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -118,97 +135,140 @@ public class ViewSubredditDetailActivity extends AppCompatActivity { } }); + subscribedSubredditDao = SubscribedSubredditRoomDatabase.getDatabase(this).subscribedSubredditDao(); glide = Glide.with(ViewSubredditDetailActivity.this); - String value = getIntent().getExtras().getString(EXTRA_SUBREDDIT_VALUE_KEY); - boolean queryById = getIntent().getExtras().getBoolean(EXTRA_QUERY_BY_ID_KEY); - SubredditViewModel.Factory factory = new SubredditViewModel.Factory(getApplication(), value, queryById); + SubredditViewModel.Factory factory = new SubredditViewModel.Factory(getApplication(), subredditName); mSubredditViewModel = ViewModelProviders.of(this, factory).get(SubredditViewModel.class); - mSubredditViewModel.getSubredditLiveData().observe(this, new Observer() { - @Override - public void onChanged(@Nullable final SubredditData subredditData) { - if(subredditData != null) { - if(subredditData.getBannerUrl().equals("")) { - iconGifImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - //Do nothing as it has no image - } - }); - } else { - glide.load(subredditData.getBannerUrl()).into(bannerImageView); - bannerImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.TITLE_KEY, title); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, subredditData.getBannerUrl()); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, subredditName + "-banner"); - startActivity(intent); - } - }); - } + mSubredditViewModel.getSubredditLiveData().observe(this, subredditData -> { + if(subredditData != null) { + if(subredditData.getBannerUrl().equals("")) { + iconGifImageView.setOnClickListener(view -> { + //Do nothing as it has no image + }); + } else { + glide.load(subredditData.getBannerUrl()).into(bannerImageView); + bannerImageView.setOnClickListener(view -> { + Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewImageActivity.class); + intent.putExtra(ViewImageActivity.TITLE_KEY, title); + intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, subredditData.getBannerUrl()); + intent.putExtra(ViewImageActivity.FILE_NAME_KEY, subredditName + "-banner"); + startActivity(intent); + }); + } - if(subredditData.getIconUrl().equals("")) { - glide.load(getDrawable(R.drawable.subreddit_default_icon)) - .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(216, 0))) - .into(iconGifImageView); - iconGifImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - //Do nothing as it is a default icon - } - }); - } else { - glide.load(subredditData.getIconUrl()) - .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(216, 0))) - .error(glide.load(R.drawable.subreddit_default_icon)) - .listener(new RequestListener() { - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { - return false; + if(subredditData.getIconUrl().equals("")) { + glide.load(getDrawable(R.drawable.subreddit_default_icon)) + .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(216, 0))) + .into(iconGifImageView); + iconGifImageView.setOnClickListener(view -> { + //Do nothing as it is a default icon + }); + } else { + glide.load(subredditData.getIconUrl()) + .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(216, 0))) + .error(glide.load(R.drawable.subreddit_default_icon)) + .listener(new RequestListener() { + @Override + public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { + return false; + } + + @Override + public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { + if(resource instanceof Animatable) { + //This is a gif + ((Animatable) resource).start(); + iconGifImageView.startAnimation(); } + return false; + } + }) + .into(iconGifImageView); + iconGifImageView.setOnClickListener(view -> { + Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewImageActivity.class); + intent.putExtra(ViewImageActivity.TITLE_KEY, title); + intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, subredditData.getIconUrl()); + intent.putExtra(ViewImageActivity.FILE_NAME_KEY, subredditName + "-icon"); + startActivity(intent); + }); + } - @Override - public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) { - if(resource instanceof Animatable) { - //This is a gif - ((Animatable) resource).start(); - iconGifImageView.startAnimation(); - } - return false; - } - }) - .into(iconGifImageView); - iconGifImageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Intent intent = new Intent(ViewSubredditDetailActivity.this, ViewImageActivity.class); - intent.putExtra(ViewImageActivity.TITLE_KEY, title); - intent.putExtra(ViewImageActivity.IMAGE_URL_KEY, subredditData.getIconUrl()); - intent.putExtra(ViewImageActivity.FILE_NAME_KEY, subredditName + "-icon"); - startActivity(intent); - } - }); - } - - subredditNameTextView.setText(subredditData.getName()); - String nSubscribers = getString(R.string.subscribers_number_detail, subredditData.getNSubscribers()); - nSubscribersTextView.setText(nSubscribers); - if(subredditData.getDescription().equals("")) { - descriptionTextView.setVisibility(View.GONE); - } else { - descriptionTextView.setVisibility(View.VISIBLE); - descriptionTextView.setText(subredditData.getDescription()); - } + String subredditFullName = "r/" + subredditData.getName(); + subredditNameTextView.setText(subredditFullName); + String nSubscribers = getString(R.string.subscribers_number_detail, subredditData.getNSubscribers()); + nSubscribersTextView.setText(nSubscribers); + if(subredditData.getDescription().equals("")) { + descriptionTextView.setVisibility(View.GONE); + } else { + descriptionTextView.setVisibility(View.VISIBLE); + descriptionTextView.setText(subredditData.getDescription()); } } }); + subscribeSubredditChip.setOnClickListener(view -> { + if(subscriptionReady) { + subscriptionReady = false; + if(subscribeSubredditChip.getText().equals(getResources().getString(R.string.subscribe))) { + SubredditSubscription.subscribeToSubreddit(mOauthRetrofit, mRetrofit, sharedPreferences, + subredditName, subscribedSubredditDao, new SubredditSubscription.SubredditSubscriptionListener() { + @Override + public void onSubredditSubscriptionSuccess() { + subscribeSubredditChip.setText(R.string.unsubscribe); + subscribeSubredditChip.setChipBackgroundColor(getResources().getColorStateList(R.color.colorAccent)); + makeSnackbar(R.string.subscribed); + subscriptionReady = true; + } + + @Override + public void onSubredditSubscriptionFail() { + makeSnackbar(R.string.subscribe_failed); + subscriptionReady = true; + } + }); + } else { + SubredditSubscription.unsubscribeToSubreddit(mOauthRetrofit, sharedPreferences, + subredditName, subscribedSubredditDao, new SubredditSubscription.SubredditSubscriptionListener() { + @Override + public void onSubredditSubscriptionSuccess() { + subscribeSubredditChip.setText(R.string.subscribe); + subscribeSubredditChip.setChipBackgroundColor(getResources().getColorStateList(R.color.colorPrimaryDark)); + makeSnackbar(R.string.unsubscribed); + subscriptionReady = true; + } + + @Override + public void onSubredditSubscriptionFail() { + makeSnackbar(R.string.unsubscribe_failed); + subscriptionReady = true; + } + }); + } + } + }); + + new CheckIsSubscribedToSubredditAsyncTask(subscribedSubredditDao, subredditName, + new CheckIsSubscribedToSubredditAsyncTask.CheckIsSubscribedToSubredditListener() { + @Override + public void isSubscribed() { + subscribeSubredditChip.setText(R.string.unsubscribe); + subscribeSubredditChip.setChipBackgroundColor(getResources().getColorStateList(R.color.colorAccent)); + subscriptionReady = true; + } + + @Override + public void isNotSubscribed() { + subscribeSubredditChip.setText(R.string.subscribe); + subscribeSubredditChip.setChipBackgroundColor(getResources().getColorStateList(R.color.colorPrimaryDark)); + subscriptionReady = true; + } + }).execute(); + FetchSubredditData.fetchSubredditData(mRetrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() { @Override public void onFetchSubredditDataSuccess(String response) { - ParseSubredditData.parseComment(response, new ParseSubredditData.ParseSubredditDataListener() { + ParseSubredditData.parseSubredditData(response, new ParseSubredditData.ParseSubredditDataListener() { @Override public void onParseSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { new InsertSubredditDataAsyncTask(SubredditRoomDatabase.getDatabase(ViewSubredditDetailActivity.this), subredditData) @@ -271,6 +331,10 @@ public class ViewSubredditDetailActivity extends AppCompatActivity { } } + private void makeSnackbar(int resId) { + Snackbar.make(coordinatorLayout, resId, Snackbar.LENGTH_SHORT).show(); + } + private static class InsertSubredditDataAsyncTask extends AsyncTask { private SubredditDao mSubredditDao; @@ -287,4 +351,40 @@ public class ViewSubredditDetailActivity extends AppCompatActivity { return null; } } + + private static class CheckIsSubscribedToSubredditAsyncTask extends AsyncTask { + + private SubscribedSubredditDao subscribedSubredditDao; + private String subredditName; + private SubscribedSubredditData subscribedSubredditData; + private CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener; + + interface CheckIsSubscribedToSubredditListener { + void isSubscribed(); + void isNotSubscribed(); + } + + CheckIsSubscribedToSubredditAsyncTask(SubscribedSubredditDao subscribedSubredditDao, String subredditName, + CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener) { + this.subscribedSubredditDao = subscribedSubredditDao; + this.subredditName =subredditName; + this.checkIsSubscribedToSubredditListener = checkIsSubscribedToSubredditListener; + } + + @Override + protected Void doInBackground(Void... voids) { + subscribedSubredditData = subscribedSubredditDao.getSubscribedSubreddit(subredditName); + return null; + } + + @Override + protected void onPostExecute(Void aVoid) { + super.onPostExecute(aVoid); + if(subscribedSubredditData != null) { + checkIsSubscribedToSubredditListener.isSubscribed(); + } else { + checkIsSubscribedToSubredditListener.isNotSubscribed(); + } + } + } } diff --git a/app/src/main/res/layout/activity_view_subreddit_detail.xml b/app/src/main/res/layout/activity_view_subreddit_detail.xml index 528518e8..97aad464 100644 --- a/app/src/main/res/layout/activity_view_subreddit_detail.xml +++ b/app/src/main/res/layout/activity_view_subreddit_detail.xml @@ -47,6 +47,10 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" + android:paddingTop="36dp" + android:paddingBottom="16dp" + android:paddingStart="16dp" + android:paddingEnd="16dp" android:layout_below="@id/banner_image_view_view_subreddit_detail_activity" android:background="@android:color/white"> @@ -54,33 +58,45 @@ android:id="@+id/subreddit_name_text_view_view_subreddit_detail_activity" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginTop="36dp" - android:layout_marginStart="16dp" - android:layout_marginEnd="16dp" + android:layout_marginBottom="16dp" android:textSize="18sp" - android:textColor="@color/colorAccent"/> + android:textColor="@color/colorAccent" + android:layout_gravity="center_horizontal"/> + + + + + android:layout_marginTop="16dp"> + android:textColor="@android:color/black" + android:layout_marginBottom="16dp"/> @@ -91,9 +107,6 @@ android:id="@+id/description_text_view_view_subreddit_detail_activity" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginStart="16dp" - android:layout_marginEnd="16dp" - android:layout_marginBottom="16dp" android:textColor="@android:color/black" android:visibility="gone"/> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 325f4684..f9c75d07 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -118,4 +118,11 @@ "For example, position the FAB to one side of stream of a cards so the FAB won’t interfere " "when a user tries to pick up one of cards.\n\n" + + Subscribe + Unsubscribe + Subscribed" + Subscribe Failed + Unsubscribed" + Unsubscribe Failed