diff options
Diffstat (limited to '')
23 files changed, 692 insertions, 627 deletions
diff --git a/.idea/caches/build_file_checksums.ser b/.idea/caches/build_file_checksums.ser Binary files differindex 36e49c17..3ba2f49b 100644 --- a/.idea/caches/build_file_checksums.ser +++ b/.idea/caches/build_file_checksums.ser diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7b2f03cb..a36ebe04 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -17,7 +17,8 @@ android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" - android:theme="@style/AppTheme"> + android:theme="@style/AppTheme" + android:usesCleartextTraffic="true"> <activity android:name=".MainActivity" android:label="@string/app_name" diff --git a/app/src/main/java/SubredditDatabase/SubredditDao.java b/app/src/main/java/SubredditDatabase/SubredditDao.java index e7b564f7..ac291f9a 100644 --- a/app/src/main/java/SubredditDatabase/SubredditDao.java +++ b/app/src/main/java/SubredditDatabase/SubredditDao.java @@ -14,11 +14,8 @@ public interface SubredditDao { @Query("DELETE FROM subreddits") void deleteAllSubreddits(); - @Query("SELECT * from subreddits WHERE id = :id") - LiveData<SubredditData> getSubredditLiveDataById(String id); - @Query("SELECT * from subreddits WHERE name = :namePrefixed") - LiveData<SubredditData> getSubredditLiveDataByNamePrefixed(String namePrefixed); + LiveData<SubredditData> 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; -@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; +import SubscribedSubredditDatabase.SubscribedSubredditData; - @ColumnInfo(name = "banner_url") +@Entity(tableName = "subreddits") +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<SubredditData> 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<SubredditData> 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<SubredditData> 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 extends ViewModel> T create(Class<T> 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<List<SubscribedSubredditData>> 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<LastItemSynchronizer> 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<Post, RecyclerView.ViewHo Log.i("is null", Integer.toString(holder.getAdapterPosition())); } else { final String id = post.getFullName(); - final String subredditName = post.getSubredditNamePrefixed(); + final String subredditNamePrefixed = post.getSubredditNamePrefixed(); + String subredditName = subredditNamePrefixed.substring(2); String author = "u/" + post.getAuthor(); final String postTime = post.getPostTime(); final String title = post.getTitle(); @@ -217,28 +218,19 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo Intent intent = new Intent(mContext, ViewSubredditDetailActivity.class); intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, post.getSubredditNamePrefixed().substring(2)); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY, - post.getSubredditNamePrefixed()); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, false); mContext.startActivity(intent); } }); - ((DataViewHolder) holder).subredditNameTextView.setText(subredditName); - - ((DataViewHolder) holder).subredditNameTextView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if(canStartActivity) { - canStartActivity = false; - Intent intent = new Intent(mContext, ViewSubredditDetailActivity.class); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, - post.getSubredditNamePrefixed().substring(2)); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_VALUE_KEY, - post.getSubredditNamePrefixed()); - intent.putExtra(ViewSubredditDetailActivity.EXTRA_QUERY_BY_ID_KEY, false); - mContext.startActivity(intent); - } + ((DataViewHolder) holder).subredditNameTextView.setText(subredditNamePrefixed); + + ((DataViewHolder) holder).subredditNameTextView.setOnClickListener(view -> { + 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<Post, RecyclerView.ViewHo ((DataViewHolder) holder).typeChip.setText("IMAGE"); final String imageUrl = post.getUrl(); - ((DataViewHolder) holder).imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - 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, subredditName.substring(2) - + "-" + id.substring(3)); - mContext.startActivity(intent); - } + ((DataViewHolder) holder).imageView.setOnClickListener(view -> { + 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<Post, RecyclerView.ViewHo ((DataViewHolder) holder).typeChip.setText("GIF"); final Uri gifVideoUri = Uri.parse(post.getVideoUrl()); - ((DataViewHolder) holder).imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - 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, subredditName); - intent.putExtra(ViewVideoActivity.ID_KEY, id); - } - mContext.startActivity(intent); + ((DataViewHolder) holder).imageView.setOnClickListener(view -> { + 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<Post, RecyclerView.ViewHo intent.putExtra(ViewVideoActivity.IS_DOWNLOADABLE_KEY, post.isDownloadableGifOrVideo()); if(post.isDownloadableGifOrVideo()) { intent.putExtra(ViewVideoActivity.DOWNLOAD_URL_KEY, post.getGifOrVideoDownloadUrl()); - intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, subredditName); + intent.putExtra(ViewVideoActivity.SUBREDDIT_KEY, subredditNamePrefixed); intent.putExtra(ViewVideoActivity.ID_KEY, id); } mContext.startActivity(intent); @@ -448,16 +431,13 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo ((DataViewHolder) holder).typeChip.setText("LINK"); final String noPreviewLinkUrl = post.getUrl(); ((DataViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE); - ((DataViewHolder) holder).noPreviewLinkImageView.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(noPreviewLinkUrl)); - } + ((DataViewHolder) holder).noPreviewLinkImageView.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(noPreviewLinkUrl)); }); break; case Post.TEXT_TYPE: @@ -465,132 +445,123 @@ class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHo break; } - ((DataViewHolder) holder).upvoteButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final boolean isDownvotedBefore = ((DataViewHolder) holder).downvoteButton.getColorFilter() != null; + ((DataViewHolder) holder).upvoteButton.setOnClickListener(view -> { + 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)); - } + 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); - } + 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); } + } - @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()); - } else { - //Upvoted before - ((DataViewHolder) holder).upvoteButton.clearColorFilter(); - ((DataViewHolder) holder).scoreTextView.setText(Integer.toString(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)); - VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { - @Override - public void onVoteThingSuccess(int position) { - post.setVoteType(0); - post.setScore(post.getScore() - 1); - } + VoteThing.voteThing(mOauthRetrofit, mSharedPreferences, new VoteThing.VoteThingListener() { + @Override + public void onVoteThingSuccess(int position1) { + 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); - post.setScore(post.getScore() + 1); - } - }, 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).downvoteButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final boolean isUpvotedBefore = ((DataViewHolder) holder).upvoteButton.getColorFilter() != null; + ((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)); - } + 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); - } + 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 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)); + @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 position) { - post.setVoteType(0); - post.setScore(post.getScore()); - } + 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 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 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(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).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<Post, RecyclerView.ViewHo public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> 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<String> getUserData(@Path("username") String username); + + @FormUrlEncoded + @POST("api/subscribe") + Call<String> subredditSubscription(@HeaderMap Map<String, String> headers, @FieldMap Map<String, String> 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<String, String> getHttpBasicAuthHeader() { Map<String, String> 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<String, String> params = new HashMap<>(); + params.put(RedditUtils.ACTION_KEY, action); + params.put(RedditUtils.SR_NAME_KEY, subredditName); + + Call<String> subredditSubscriptionCall = api.subredditSubscription(RedditUtils.getOAuthHeader(accessToken), params); + subredditSubscriptionCall.enqueue(new Callback<String>() { + @Override + public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> 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<String> call, @NonNull Throwable t) { + Log.i("call failed", t.getMessage()); + subredditSubscriptionListener.onSubredditSubscriptionFail(); + } + }); + } + + private static class UpdateSubscriptionAsyncTask extends AsyncTask<Void, Void, Void> { + + 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<Recycl @Override public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, final int i) { - viewHolder.itemView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View 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()); - 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)); - } + 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); - } + 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); - } else { - //Upvoted before - mUpvoteButton.clearColorFilter(); - mScoreTextView.setText(Integer.toString(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); + } 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); - } + 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); - } + @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<Drawable> 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<SubredditData>() { - @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<Drawable>() { - @Override - public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> 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<Drawable>() { + @Override + public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { + return false; + } + + @Override + public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> 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<Drawable> 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); - } - }); - } + 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()); + } + } + }); - 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()); - } + 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<Void, Void, Void> { private SubredditDao mSubredditDao; @@ -287,4 +351,40 @@ public class ViewSubredditDetailActivity extends AppCompatActivity { return null; } } + + private static class CheckIsSubscribedToSubredditAsyncTask extends AsyncTask<Void, Void, Void> { + + 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.support.design.chip.Chip + android:id="@+id/subscribe_subreddit_chip_view_subreddit_detail_activity" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textColor="@android:color/white" + android:layout_gravity="center_horizontal"/> + + <!--<RelativeLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="48dp" + android:layout_marginStart="16dp" + android:layout_marginEnd="16dp"> + + + + </RelativeLayout>--> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" - android:layout_marginBottom="16dp"> + android:layout_marginTop="16dp"> <TextView android:id="@+id/subscriber_count_text_view_view_subreddit_detail_activity" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginTop="16dp" - android:layout_marginStart="16dp" - android:layout_marginEnd="16dp" - android:textColor="@android:color/black" /> + android:textColor="@android:color/black" + android:layout_marginBottom="16dp"/> <TextView android:id="@+id/online_subscriber_count_text_view_view_subreddit_detail_activity" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginTop="16dp" - android:layout_marginStart="16dp" - android:layout_marginEnd="16dp" android:layout_alignParentEnd="true" android:layout_toStartOf="@id/subscriber_count_text_view_view_subreddit_detail_activity" android:textColor="@android:color/black" /> @@ -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" </string> + + <string name="subscribe">Subscribe</string> + <string name="unsubscribe">Unsubscribe</string> + <string name="subscribed">Subscribed</string>" + <string name="subscribe_failed">Subscribe Failed</string> + <string name="unsubscribed">Unsubscribed</string>" + <string name="unsubscribe_failed">Unsubscribe Failed</string> </resources> |