Clean up code.

This commit is contained in:
Alex Ning 2019-09-29 22:11:34 +08:00
parent 456429725b
commit 76204ac044
127 changed files with 3781 additions and 3564 deletions

View File

@ -35,7 +35,7 @@ class AccessTokenAuthenticator implements Authenticator {
String accessToken = response.request().header(RedditUtils.AUTHORIZATION_KEY).substring(RedditUtils.AUTHORIZATION_BASE.length());
synchronized (this) {
Account account = mRedditDataRoomDatabase.accountDao().getCurrentAccount();
if(account == null) {
if (account == null) {
return null;
}
String accessTokenFromDatabase = account.getAccessToken();
@ -66,7 +66,7 @@ class AccessTokenAuthenticator implements Authenticator {
Call<String> accessTokenCall = api.getAccessToken(RedditUtils.getHttpBasicAuthHeader(), params);
try {
retrofit2.Response response = accessTokenCall.execute();
if(response.isSuccessful() && response.body() != null) {
if (response.isSuccessful() && response.body() != null) {
JSONObject jsonObject = new JSONObject((String) response.body());
String newAccessToken = jsonObject.getString(RedditUtils.ACCESS_TOKEN_KEY);
mRedditDataRoomDatabase.accountDao().changeAccessToken(account.getUsername(), newAccessToken);

View File

@ -29,20 +29,20 @@ import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.Fragment.UserThingSortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import ml.docilealligator.infinityforreddit.Fragment.UserThingSortTypeBottomSheetFragment;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
@ -59,26 +59,25 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
private static final String ACCOUNT_NAME_STATE = "ANS";
private static final String FRAGMENT_OUT_STATE = "FOS";
@BindView(R.id.collapsing_toolbar_layout_account_posts_activity) CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.appbar_layout_account_posts_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_account_posts_activity) Toolbar toolbar;
@BindView(R.id.collapsing_toolbar_layout_account_posts_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.appbar_layout_account_posts_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_account_posts_activity)
Toolbar toolbar;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean isInLazyMode = false;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
private String mUserWhere;
private Fragment mFragment;
private Menu mMenu;
private AppBarLayout.LayoutParams params;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -109,24 +108,24 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
View decorView = window.getDecorView();
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if (state == State.COLLAPSED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if (state == State.EXPANDED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -151,7 +150,7 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -160,13 +159,13 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
}
mUserWhere = getIntent().getExtras().getString(EXTRA_USER_WHERE);
if(mUserWhere.equals(PostDataSource.USER_WHERE_UPVOTED)) {
if (mUserWhere.equals(PostDataSource.USER_WHERE_UPVOTED)) {
toolbar.setTitle(R.string.upvoted);
} else if(mUserWhere.equals(PostDataSource.USER_WHERE_DOWNVOTED)) {
} else if (mUserWhere.equals(PostDataSource.USER_WHERE_DOWNVOTED)) {
toolbar.setTitle(R.string.downvoted);
} else if(mUserWhere.equals(PostDataSource.USER_WHERE_HIDDEN)) {
} else if (mUserWhere.equals(PostDataSource.USER_WHERE_HIDDEN)) {
toolbar.setTitle(R.string.hidden);
} else if(mUserWhere.equals(PostDataSource.USER_WHERE_GILDED)){
} else if (mUserWhere.equals(PostDataSource.USER_WHERE_GILDED)) {
toolbar.setTitle(R.string.gilded);
}
@ -175,12 +174,12 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
if(savedInstanceState != null) {
if (savedInstanceState != null) {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE);
isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndInitializeFragment();
} else {
mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE);
@ -193,7 +192,7 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
private void getCurrentAccountAndInitializeFragment() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -221,7 +220,7 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
getMenuInflater().inflate(R.menu.account_posts_activity, menu);
mMenu = menu;
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_account_posts_activity);
if(isInLazyMode) {
if (isInLazyMode) {
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
collapsingToolbarLayout.setLayoutParams(params);
@ -237,23 +236,23 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh_account_posts_activity:
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_lazy_mode_account_posts_activity).setTitle(R.string.action_start_lazy_mode);
}
if(mFragment != null) {
if (mFragment != null) {
((PostFragment) mFragment).refresh();
}
return true;
case R.id.action_lazy_mode_account_posts_activity:
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_account_posts_activity);
if(isInLazyMode) {
if (isInLazyMode) {
((FragmentCommunicator) mFragment).stopLazyMode();
isInLazyMode = false;
lazyModeItem.setTitle(R.string.action_start_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
collapsingToolbarLayout.setLayoutParams(params);
} else {
if(((FragmentCommunicator) mFragment).startLazyMode()) {
if (((FragmentCommunicator) mFragment).startLazyMode()) {
isInLazyMode = true;
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
@ -288,7 +287,7 @@ public class AccountPostsActivity extends AppCompatActivity implements UserThing
@Override
public void userThingSortTypeSelected(String sortType) {
if(mFragment != null) {
if (mFragment != null) {
((PostFragment) mFragment).changeSortType(sortType);
}
}

View File

@ -34,19 +34,19 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.Fragment.CommentsListingFragment;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Fragment.CommentsListingFragment;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import retrofit2.Retrofit;
@ -62,31 +62,31 @@ public class AccountSavedThingActivity extends AppCompatActivity {
private static final String ACCOUNT_NAME_STATE = "ANS";
private static final String IS_IN_LAZY_MODE_STATE = "IILMS";
@BindView(R.id.collapsing_toolbar_layout_account_saved_thing_activity) CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.appbar_layout_account_saved_thing_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_account_saved_thing_activity) Toolbar toolbar;
@BindView(R.id.tab_layout_tab_layout_account_saved_thing_activity_activity) TabLayout tabLayout;
@BindView(R.id.view_pager_account_saved_thing_activity) ViewPager viewPager;
@BindView(R.id.collapsing_toolbar_layout_account_saved_thing_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.appbar_layout_account_saved_thing_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_account_saved_thing_activity)
Toolbar toolbar;
@BindView(R.id.tab_layout_tab_layout_account_saved_thing_activity_activity)
TabLayout tabLayout;
@BindView(R.id.view_pager_account_saved_thing_activity)
ViewPager viewPager;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private SectionsPagerAdapter sectionsPagerAdapter;
private Menu mMenu;
private AppBarLayout.LayoutParams params;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
private boolean isInLazyMode = false;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -117,24 +117,24 @@ public class AccountSavedThingActivity extends AppCompatActivity {
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
View decorView = window.getDecorView();
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if (state == State.COLLAPSED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if (state == State.EXPANDED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -159,7 +159,7 @@ public class AccountSavedThingActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -172,12 +172,12 @@ public class AccountSavedThingActivity extends AppCompatActivity {
params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
if(savedInstanceState != null) {
if (savedInstanceState != null) {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE);
isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndInitializeViewPager();
} else {
initializeViewPager();
@ -189,7 +189,7 @@ public class AccountSavedThingActivity extends AppCompatActivity {
private void getCurrentAccountAndInitializeViewPager() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -213,8 +213,8 @@ public class AccountSavedThingActivity extends AppCompatActivity {
@Override
public void onPageSelected(int position) {
if(isInLazyMode) {
if(viewPager.getCurrentItem() == 0) {
if (isInLazyMode) {
if (viewPager.getCurrentItem() == 0) {
sectionsPagerAdapter.resumeLazyMode();
} else {
sectionsPagerAdapter.pauseLazyMode();
@ -254,14 +254,14 @@ public class AccountSavedThingActivity extends AppCompatActivity {
finish();
return true;
case R.id.action_refresh_account_saved_thing_activity:
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_lazy_mode_account_saved_thing_activity).setTitle(R.string.action_start_lazy_mode);
}
sectionsPagerAdapter.refresh();
return true;
case R.id.action_lazy_mode_account_saved_thing_activity:
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_account_saved_thing_activity);
if(isInLazyMode) {
if (isInLazyMode) {
isInLazyMode = false;
sectionsPagerAdapter.stopLazyMode();
lazyModeItem.setTitle(R.string.action_start_lazy_mode);
@ -269,7 +269,7 @@ public class AccountSavedThingActivity extends AppCompatActivity {
collapsingToolbarLayout.setLayoutParams(params);
} else {
isInLazyMode = true;
if(sectionsPagerAdapter.startLazyMode()) {
if (sectionsPagerAdapter.startLazyMode()) {
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
appBarLayout.setExpanded(false);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
@ -373,43 +373,43 @@ public class AccountSavedThingActivity extends AppCompatActivity {
public void refresh() {
if (viewPager.getCurrentItem() == 0) {
if(postFragment != null) {
if (postFragment != null) {
postFragment.refresh();
}
} else {
if(commentsListingFragment != null) {
if (commentsListingFragment != null) {
commentsListingFragment.refresh();
}
}
}
boolean startLazyMode() {
if(postFragment != null) {
if (postFragment != null) {
return ((FragmentCommunicator) postFragment).startLazyMode();
}
return false;
}
void stopLazyMode() {
if(postFragment != null) {
if (postFragment != null) {
((FragmentCommunicator) postFragment).stopLazyMode();
}
}
void resumeLazyMode() {
if(postFragment != null) {
if (postFragment != null) {
((FragmentCommunicator) postFragment).resumeLazyMode(false);
}
}
void pauseLazyMode() {
if(postFragment != null) {
if (postFragment != null) {
((FragmentCommunicator) postFragment).pauseLazyMode(false);
}
}
public void changeNSFW(boolean nsfw) {
if(postFragment != null) {
if (postFragment != null) {
postFragment.changeNSFW(nsfw);
}
}

View File

@ -39,16 +39,16 @@ import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration;
import io.noties.markwon.linkify.LinkifyPlugin;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.CommentData;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SendComment;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import retrofit2.Retrofit;
@ -70,11 +70,21 @@ public class CommentActivity extends AppCompatActivity {
private static final String NULL_ACCESS_TOKEN_STATE = "NATS";
private static final String ACCESS_TOKEN_STATE = "ATS";
@BindView(R.id.coordinator_layout_comment_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_comment_activity) Toolbar toolbar;
@BindView(R.id.comment_parent_markwon_view_comment_activity) TextView commentParentMarkwonView;
@BindView(R.id.comment_edit_text_comment_activity) EditText commentEditText;
@BindView(R.id.coordinator_layout_comment_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_comment_activity)
Toolbar toolbar;
@BindView(R.id.comment_parent_markwon_view_comment_activity)
TextView commentParentMarkwonView;
@BindView(R.id.comment_edit_text_comment_activity)
EditText commentEditText;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String parentFullname;
@ -82,16 +92,6 @@ public class CommentActivity extends AppCompatActivity {
private int parentPosition;
private boolean isReplying;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -113,9 +113,9 @@ public class CommentActivity extends AppCompatActivity {
EventBus.getDefault().register(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -131,7 +131,7 @@ public class CommentActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -139,12 +139,12 @@ public class CommentActivity extends AppCompatActivity {
}
if(savedInstanceState == null) {
if (savedInstanceState == null) {
getCurrentAccount();
} else {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccount();
}
}
@ -157,7 +157,7 @@ public class CommentActivity extends AppCompatActivity {
builder.linkResolver((view, link) -> {
Intent intent = new Intent(CommentActivity.this, LinkResolverActivity.class);
Uri uri = Uri.parse(link);
if(uri.getScheme() == null && uri.getHost() == null) {
if (uri.getScheme() == null && uri.getHost() == null) {
intent.setData(LinkResolverActivity.getRedditUriByPath(link));
} else {
intent.setData(uri);
@ -173,7 +173,7 @@ public class CommentActivity extends AppCompatActivity {
parentDepth = intent.getExtras().getInt(EXTRA_PARENT_DEPTH_KEY);
parentPosition = intent.getExtras().getInt(EXTRA_PARENT_POSITION_KEY);
isReplying = intent.getExtras().getBoolean(EXTRA_IS_REPLYING_KEY);
if(isReplying) {
if (isReplying) {
toolbar.setTitle(getString(R.string.comment_activity_label_is_replying));
}
@ -181,14 +181,14 @@ public class CommentActivity extends AppCompatActivity {
commentEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
private void getCurrentAccount() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -199,8 +199,8 @@ public class CommentActivity extends AppCompatActivity {
@Override
protected void onPause() {
super.onPause();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(commentEditText.getWindowToken(), 0);
}
}
@ -218,7 +218,7 @@ public class CommentActivity extends AppCompatActivity {
finish();
return true;
case R.id.action_send_comment_activity:
if(commentEditText.getText() == null || commentEditText.getText().toString().equals("")) {
if (commentEditText.getText() == null || commentEditText.getText().toString().equals("")) {
Snackbar.make(coordinatorLayout, R.string.comment_content_required, Snackbar.LENGTH_SHORT).show();
return true;
}
@ -238,7 +238,7 @@ public class CommentActivity extends AppCompatActivity {
Intent returnIntent = new Intent();
returnIntent.putExtra(EXTRA_COMMENT_DATA_KEY, commentData);
returnIntent.putExtra(EXTRA_PARENT_FULLNAME_KEY, parentFullname);
if(isReplying) {
if (isReplying) {
returnIntent.putExtra(EXTRA_PARENT_POSITION_KEY, parentPosition);
}
setResult(RESULT_OK, returnIntent);
@ -251,7 +251,7 @@ public class CommentActivity extends AppCompatActivity {
item.setEnabled(true);
item.getIcon().setAlpha(255);
if(errorMessage == null) {
if (errorMessage == null) {
Snackbar.make(coordinatorLayout, R.string.send_comment_failed, Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(coordinatorLayout, errorMessage, Snackbar.LENGTH_SHORT).show();

View File

@ -35,13 +35,13 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditAPI;
import ml.docilealligator.infinityforreddit.RedditUtils;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import retrofit2.Call;
import retrofit2.Callback;
@ -63,20 +63,20 @@ public class EditCommentActivity extends AppCompatActivity {
static final String EXTRA_EDITED_COMMENT_CONTENT = "EECC";
static final String EXTRA_EDITED_COMMENT_POSITION = "EECP";
@BindView(R.id.coordinator_layout_edit_comment_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_edit_comment_activity) Toolbar toolbar;
@BindView(R.id.post_text_content_edit_text_edit_comment_activity) EditText contentEditText;
private String mFullName;
private String mAccessToken;
private boolean isSubmitting = false;
@BindView(R.id.coordinator_layout_edit_comment_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_edit_comment_activity)
Toolbar toolbar;
@BindView(R.id.post_text_content_edit_text_edit_comment_activity)
EditText contentEditText;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
SharedPreferences mSharedPreferences;
private String mFullName;
private String mAccessToken;
private boolean isSubmitting = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -99,9 +99,9 @@ public class EditCommentActivity extends AppCompatActivity {
EventBus.getDefault().register(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -117,7 +117,7 @@ public class EditCommentActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -134,7 +134,7 @@ public class EditCommentActivity extends AppCompatActivity {
contentEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
@ -142,8 +142,8 @@ public class EditCommentActivity extends AppCompatActivity {
@Override
protected void onPause() {
super.onPause();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(contentEditText.getWindowToken(), 0);
}
}
@ -156,8 +156,8 @@ public class EditCommentActivity extends AppCompatActivity {
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == R.id.action_send_edit_comment_activity) {
if(!isSubmitting) {
if (item.getItemId() == R.id.action_send_edit_comment_activity) {
if (!isSubmitting) {
isSubmitting = true;
Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_SHORT).show();
@ -174,7 +174,7 @@ public class EditCommentActivity extends AppCompatActivity {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
isSubmitting = false;
if(response.isSuccessful()) {
if (response.isSuccessful()) {
Toast.makeText(EditCommentActivity.this, R.string.edit_success, Toast.LENGTH_SHORT).show();
Intent returnIntent = new Intent();
@ -197,7 +197,7 @@ public class EditCommentActivity extends AppCompatActivity {
}
return true;
} else if(item.getItemId() == android.R.id.home) {
} else if (item.getItemId() == android.R.id.home) {
finish();
return true;
}

View File

@ -36,13 +36,13 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditAPI;
import ml.docilealligator.infinityforreddit.RedditUtils;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import retrofit2.Call;
import retrofit2.Callback;
@ -61,21 +61,22 @@ public class EditPostActivity extends AppCompatActivity {
static final String EXTRA_FULLNAME = "EF";
static final String EXTRA_ACCESS_TOKEN = "EAT";
@BindView(R.id.coordinator_layout_edit_post_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_edit_post_activity) Toolbar toolbar;
@BindView(R.id.post_title_text_view_edit_post_activity) TextView titleTextView;
@BindView(R.id.post_text_content_edit_text_edit_post_activity) EditText contentEditText;
private String mFullName;
private String mAccessToken;
private boolean isSubmitting = false;
@BindView(R.id.coordinator_layout_edit_post_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_edit_post_activity)
Toolbar toolbar;
@BindView(R.id.post_title_text_view_edit_post_activity)
TextView titleTextView;
@BindView(R.id.post_text_content_edit_text_edit_post_activity)
EditText contentEditText;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
SharedPreferences mSharedPreferences;
private String mFullName;
private String mAccessToken;
private boolean isSubmitting = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -98,9 +99,9 @@ public class EditPostActivity extends AppCompatActivity {
EventBus.getDefault().register(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -116,7 +117,7 @@ public class EditPostActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -134,7 +135,7 @@ public class EditPostActivity extends AppCompatActivity {
contentEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
@ -142,8 +143,8 @@ public class EditPostActivity extends AppCompatActivity {
@Override
protected void onPause() {
super.onPause();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(contentEditText.getWindowToken(), 0);
}
}
@ -156,8 +157,8 @@ public class EditPostActivity extends AppCompatActivity {
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == R.id.action_send_edit_post_activity) {
if(!isSubmitting) {
if (item.getItemId() == R.id.action_send_edit_post_activity) {
if (!isSubmitting) {
isSubmitting = true;
Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_SHORT).show();
@ -187,7 +188,7 @@ public class EditPostActivity extends AppCompatActivity {
}
return true;
} else if(item.getItemId() == android.R.id.home) {
} else if (item.getItemId() == android.R.id.home) {
finish();
return true;
}

View File

@ -29,22 +29,22 @@ import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.Fragment.SearchPostSortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.Fragment.SortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.Fragment.UserThingSortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.Post;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.Fragment.SearchPostSortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Fragment.SortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import ml.docilealligator.infinityforreddit.Fragment.UserThingSortTypeBottomSheetFragment;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
@ -66,32 +66,30 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
private static final String ACCESS_TOKEN_STATE = "ATS";
private static final String FRAGMENT_OUT_STATE = "FOS";
@BindView(R.id.appbar_layout_filtered_posts_activity) AppBarLayout appBarLayout;
@BindView(R.id.collapsing_toolbar_layout_filtered_posts_activity) CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar_filtered_posts_activity) Toolbar toolbar;
@BindView(R.id.appbar_layout_filtered_posts_activity)
AppBarLayout appBarLayout;
@BindView(R.id.collapsing_toolbar_layout_filtered_posts_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar_filtered_posts_activity)
Toolbar toolbar;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean isInLazyMode = false;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String name;
private int postType;
private Fragment mFragment;
private Menu mMenu;
private AppBarLayout.LayoutParams params;
private SortTypeBottomSheetFragment bestSortTypeBottomSheetFragment;
private SortTypeBottomSheetFragment popularAndAllSortTypeBottomSheetFragment;
private SortTypeBottomSheetFragment subredditSortTypeBottomSheetFragment;
private UserThingSortTypeBottomSheetFragment userThingSortTypeBottomSheetFragment;
private SearchPostSortTypeBottomSheetFragment searchPostSortTypeBottomSheetFragment;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -122,24 +120,24 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
View decorView = window.getDecorView();
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if (state == State.COLLAPSED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if (state == State.EXPANDED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -164,7 +162,7 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -182,11 +180,11 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
int filter = getIntent().getIntExtra(EXTRA_FILTER, Post.TEXT_TYPE);
String sortType = getIntent().getStringExtra(EXTRA_SORT_TYPE);
if(savedInstanceState != null) {
if (savedInstanceState != null) {
isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE);
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndBindView(filter, sortType);
} else {
mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE);
@ -200,7 +198,7 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
private void getCurrentAccountAndBindView(int filter, String sortType) {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -227,7 +225,7 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
searchPostSortTypeBottomSheetFragment.setArguments(searchBundle);
break;
case PostDataSource.TYPE_SUBREDDIT:
if(name.equals("popular") || name.equals("all")) {
if (name.equals("popular") || name.equals("all")) {
getSupportActionBar().setTitle(name.substring(0, 1).toUpperCase() + name.substring(1));
popularAndAllSortTypeBottomSheetFragment = new SortTypeBottomSheetFragment();
@ -273,7 +271,7 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
toolbar.setSubtitle(R.string.gif);
}
if(initializeFragment) {
if (initializeFragment) {
mFragment = new PostFragment();
Bundle bundle = new Bundle();
bundle.putString(PostFragment.EXTRA_NAME, name);
@ -281,10 +279,10 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
bundle.putString(PostFragment.EXTRA_SORT_TYPE, sortType);
bundle.putInt(PostFragment.EXTRA_FILTER, filter);
bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
if(postType == PostDataSource.TYPE_USER) {
if (postType == PostDataSource.TYPE_USER) {
bundle.putString(PostFragment.EXTRA_USER_WHERE, getIntent().getStringExtra(EXTRA_USER_WHERE));
}
if(postType == PostDataSource.TYPE_SEARCH) {
if (postType == PostDataSource.TYPE_SEARCH) {
bundle.putString(PostFragment.EXTRA_QUERY, getIntent().getStringExtra(EXTRA_QUERY));
}
mFragment.setArguments(bundle);
@ -297,7 +295,7 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
getMenuInflater().inflate(R.menu.filtered_posts_activity, menu);
mMenu = menu;
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_filtered_thing_activity);
if(isInLazyMode) {
if (isInLazyMode) {
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
collapsingToolbarLayout.setLayoutParams(params);
@ -324,7 +322,7 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
searchPostSortTypeBottomSheetFragment.show(getSupportFragmentManager(), searchPostSortTypeBottomSheetFragment.getTag());
break;
case PostDataSource.TYPE_SUBREDDIT:
if(name.equals("popular") || name.equals("all")) {
if (name.equals("popular") || name.equals("all")) {
popularAndAllSortTypeBottomSheetFragment.show(getSupportFragmentManager(), popularAndAllSortTypeBottomSheetFragment.getTag());
} else {
subredditSortTypeBottomSheetFragment.show(getSupportFragmentManager(), subredditSortTypeBottomSheetFragment.getTag());
@ -335,23 +333,23 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
}
return true;
case R.id.action_refresh_filtered_thing_activity:
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_lazy_mode_filtered_thing_activity).setTitle(R.string.action_start_lazy_mode);
}
if(mFragment instanceof FragmentCommunicator) {
if (mFragment instanceof FragmentCommunicator) {
((FragmentCommunicator) mFragment).refresh();
}
return true;
case R.id.action_lazy_mode_filtered_thing_activity:
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_filtered_thing_activity);
if(isInLazyMode) {
if (isInLazyMode) {
((FragmentCommunicator) mFragment).stopLazyMode();
isInLazyMode = false;
lazyModeItem.setTitle(R.string.action_start_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
collapsingToolbarLayout.setLayoutParams(params);
} else {
if(((FragmentCommunicator) mFragment).startLazyMode()) {
if (((FragmentCommunicator) mFragment).startLazyMode()) {
isInLazyMode = true;
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
@ -382,17 +380,17 @@ public class FilteredThingActivity extends AppCompatActivity implements SortType
@Override
public void searchSortTypeSelected(String sortType) {
((PostFragment)mFragment).changeSortType(sortType);
((PostFragment) mFragment).changeSortType(sortType);
}
@Override
public void sortTypeSelected(String sortType) {
((PostFragment)mFragment).changeSortType(sortType);
((PostFragment) mFragment).changeSortType(sortType);
}
@Override
public void userThingSortTypeSelected(String sortType) {
((PostFragment)mFragment).changeSortType(sortType);
((PostFragment) mFragment).changeSortType(sortType);
}
@Subscribe

View File

@ -43,6 +43,10 @@ public class LinkResolverActivity extends AppCompatActivity {
@Inject
SharedPreferences mSharedPreferences;
public static Uri getRedditUriByPath(String path) {
return Uri.parse("https://www.reddit.com" + path);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -59,7 +63,7 @@ public class LinkResolverActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -68,25 +72,25 @@ public class LinkResolverActivity extends AppCompatActivity {
}
Uri uri = getIntent().getData();
if(uri == null) {
if (uri == null) {
Toast.makeText(this, R.string.no_link_available, Toast.LENGTH_SHORT).show();
finish();
} else {
String path = uri.getPath();
if(path == null) {
if (path == null) {
deepLinkError(uri);
} else {
if(path.endsWith("/")) {
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
String messageFullname = getIntent().getStringExtra(EXTRA_MESSAGE_FULLNAME);
String newAccountName = getIntent().getStringExtra(EXTRA_NEW_ACCOUNT_NAME);
if(path.matches(POST_PATTERN)) {
if (path.matches(POST_PATTERN)) {
List<String> segments = uri.getPathSegments();
int commentsIndex = segments.lastIndexOf("comments");
if(commentsIndex >=0 && commentsIndex < segments.size() - 1) {
if (commentsIndex >= 0 && commentsIndex < segments.size() - 1) {
Intent intent = new Intent(this, ViewPostDetailActivity.class);
intent.putExtra(ViewPostDetailActivity.EXTRA_POST_ID, segments.get(commentsIndex + 1));
intent.putExtra(ViewPostDetailActivity.EXTRA_MESSAGE_FULLNAME, messageFullname);
@ -95,10 +99,10 @@ public class LinkResolverActivity extends AppCompatActivity {
} else {
deepLinkError(uri);
}
} else if(path.matches(COMMENT_PATTERN)) {
} else if (path.matches(COMMENT_PATTERN)) {
List<String> segments = uri.getPathSegments();
int commentsIndex = segments.lastIndexOf("comments");
if(commentsIndex >=0 && commentsIndex < segments.size() - 1) {
if (commentsIndex >= 0 && commentsIndex < segments.size() - 1) {
Intent intent = new Intent(this, ViewPostDetailActivity.class);
intent.putExtra(ViewPostDetailActivity.EXTRA_POST_ID, segments.get(commentsIndex + 1));
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_ID, segments.get(segments.size() - 1));
@ -108,9 +112,9 @@ public class LinkResolverActivity extends AppCompatActivity {
} else {
deepLinkError(uri);
}
} else if(path.matches(SUBREDDIT_PATTERN)) {
} else if (path.matches(SUBREDDIT_PATTERN)) {
String subredditName = path.substring(3);
if(subredditName.equals("popular") || subredditName.equals("all")) {
if (subredditName.equals("popular") || subredditName.equals("all")) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.EXTRA_POST_TYPE, subredditName);
intent.putExtra(MainActivity.EXTRA_MESSSAGE_FULLNAME, messageFullname);
@ -123,13 +127,13 @@ public class LinkResolverActivity extends AppCompatActivity {
intent.putExtra(ViewSubredditDetailActivity.EXTRA_NEW_ACCOUNT_NAME, newAccountName);
startActivity(intent);
}
} else if(path.matches(USER_PATTERN_1)) {
} else if (path.matches(USER_PATTERN_1)) {
Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, path.substring(6));
intent.putExtra(ViewUserDetailActivity.EXTRA_MESSAGE_FULLNAME, messageFullname);
intent.putExtra(ViewUserDetailActivity.EXTRA_NEW_ACCOUNT_NAME, newAccountName);
startActivity(intent);
} else if(path.matches(USER_PATTERN_2)) {
} else if (path.matches(USER_PATTERN_2)) {
Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, path.substring(3));
intent.putExtra(ViewUserDetailActivity.EXTRA_MESSAGE_FULLNAME, messageFullname);
@ -147,14 +151,14 @@ public class LinkResolverActivity extends AppCompatActivity {
private void deepLinkError(Uri uri) {
PackageManager pm = getPackageManager();
ArrayList<ResolveInfo> resolveInfos = getCustomTabsPackages(pm);
if(!resolveInfos.isEmpty()) {
if (!resolveInfos.isEmpty()) {
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.intent.setPackage(resolveInfos.get(0).activityInfo.packageName);
if(uri.getScheme() == null) {
if (uri.getScheme() == null) {
uri = Uri.parse("http://" + uri.toString());
}
try {
@ -195,21 +199,17 @@ public class LinkResolverActivity extends AppCompatActivity {
String currentPackageName = getApplicationContext().getPackageName();
for(ResolveInfo info : activities) {
if(!info.activityInfo.packageName.equals(currentPackageName)) {
for (ResolveInfo info : activities) {
if (!info.activityInfo.packageName.equals(currentPackageName)) {
packageNames.add(info.activityInfo.packageName);
}
}
if(!packageNames.isEmpty()) {
if (!packageNames.isEmpty()) {
intent.setPackage(packageNames.get(0));
startActivity(intent);
} else {
Toast.makeText(this, R.string.no_browser_found, Toast.LENGTH_SHORT).show();
}
}
public static Uri getRedditUriByPath(String path) {
return Uri.parse("https://www.reddit.com" + path);
}
}

View File

@ -29,9 +29,9 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.AsyncTask.ParseAndInsertNewAccountAsyncTask;
import ml.docilealligator.infinityforreddit.FetchMyInfo;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.AsyncTask.ParseAndInsertNewAccountAsyncTask;
import ml.docilealligator.infinityforreddit.ParseAndSaveAccountInfo;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditAPI;
@ -50,23 +50,19 @@ import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
public class LoginActivity extends AppCompatActivity {
@BindView(R.id.toolbar_login_activity) Toolbar toolbar;
private String authCode;
@BindView(R.id.toolbar_login_activity)
Toolbar toolbar;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private String authCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -89,7 +85,7 @@ public class LoginActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -114,16 +110,17 @@ public class LoginActivity extends AppCompatActivity {
String url = uriBuilder.toString();
CookieManager.getInstance().removeAllCookies(aBoolean -> {});
CookieManager.getInstance().removeAllCookies(aBoolean -> {
});
webView.loadUrl(url);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("&code=") || url.contains("?code=")) {
if (url.contains("&code=") || url.contains("?code=")) {
Uri uri = Uri.parse(url);
String state = uri.getQueryParameter("state");
if(state.equals(RedditUtils.STATE)) {
if (state.equals(RedditUtils.STATE)) {
authCode = uri.getQueryParameter("code");
Map<String, String> params = new HashMap<>();
@ -136,10 +133,10 @@ public class LoginActivity extends AppCompatActivity {
accessTokenCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
try {
String accountResponse = response.body();
if(accountResponse == null) {
if (accountResponse == null) {
//Handle error
return;
}

View File

@ -57,39 +57,39 @@ import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.Account.Account;
import ml.docilealligator.infinityforreddit.Account.AccountViewModel;
import ml.docilealligator.infinityforreddit.Adapter.AccountRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.AsyncTask.InsertSubscribedThingsAsyncTask;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchAccountAsyncTask;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchToAnonymousAccountAsyncTask;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.ChangeFontSizeEvent;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FetchMyInfo;
import ml.docilealligator.infinityforreddit.FetchSubscribedThing;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.AsyncTask.InsertSubscribedThingsAsyncTask;
import ml.docilealligator.infinityforreddit.ParseAndSaveAccountInfo;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.Fragment.PostTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.Fragment.SortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.ParseAndSaveAccountInfo;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.PullNotificationWorker;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.ReadMessage;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Fragment.SortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.SubredditDatabase.SubredditData;
import ml.docilealligator.infinityforreddit.SubscribedSubredditDatabase.SubscribedSubredditData;
import ml.docilealligator.infinityforreddit.SubscribedUserDatabase.SubscribedUserData;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchToAnonymousAccountAsyncTask;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
@ -121,44 +121,71 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
private static final int LOGIN_ACTIVITY_REQUEST_CODE = 0;
@BindView(R.id.drawer_layout) DrawerLayout drawer;
@BindView(R.id.coordinator_layout_main_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_main_activity) AppBarLayout appBarLayout;
@BindView(R.id.view_pager_main_activity) ViewPager viewPager;
@BindView(R.id.collapsing_toolbar_layout_main_activity) CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.nested_scroll_view_main_activity) NestedScrollView nestedScrollView;
@BindView(R.id.all_drawer_items_linear_layout_main_activity) LinearLayout allDrawerItemsLinearLayout;
@BindView(R.id.account_label_main_activity) TextView accountLabelTextView;
@BindView(R.id.profile_linear_layout_main_activity) LinearLayout profileLinearLayout;
@BindView(R.id.subscriptions_linear_layout_main_activity) LinearLayout subscriptionLinearLayout;
@BindView(R.id.inbox_linear_layout_main_activity) LinearLayout inboxLinearLayout;
@BindView(R.id.post_label_main_activity) TextView postLabelTextView;
@BindView(R.id.upvoted_linear_layout_main_activity) LinearLayout upvotedLinearLayout;
@BindView(R.id.downvoted_linear_layout_main_activity) LinearLayout downvotedLinearLayout;
@BindView(R.id.hidden_linear_layout_main_activity) LinearLayout hiddenLinearLayout;
@BindView(R.id.saved_linear_layout_main_activity) LinearLayout savedLinearLayout;
@BindView(R.id.gilded_linear_layout_main_activity) LinearLayout gildedLinearLayout;
@BindView(R.id.divider_main_activity) View divider;
@BindView(R.id.settings_linear_layout_main_activity) LinearLayout settingsLinearLayout;
@BindView(R.id.account_recycler_view_main_activity) RecyclerView accountRecyclerView;
@BindView(R.id.tab_layout_main_activity) TabLayout tabLayout;
@BindView(R.id.fab_main_activity) FloatingActionButton fab;
@BindView(R.id.drawer_layout)
DrawerLayout drawer;
@BindView(R.id.coordinator_layout_main_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_main_activity)
AppBarLayout appBarLayout;
@BindView(R.id.view_pager_main_activity)
ViewPager viewPager;
@BindView(R.id.collapsing_toolbar_layout_main_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.nested_scroll_view_main_activity)
NestedScrollView nestedScrollView;
@BindView(R.id.all_drawer_items_linear_layout_main_activity)
LinearLayout allDrawerItemsLinearLayout;
@BindView(R.id.account_label_main_activity)
TextView accountLabelTextView;
@BindView(R.id.profile_linear_layout_main_activity)
LinearLayout profileLinearLayout;
@BindView(R.id.subscriptions_linear_layout_main_activity)
LinearLayout subscriptionLinearLayout;
@BindView(R.id.inbox_linear_layout_main_activity)
LinearLayout inboxLinearLayout;
@BindView(R.id.post_label_main_activity)
TextView postLabelTextView;
@BindView(R.id.upvoted_linear_layout_main_activity)
LinearLayout upvotedLinearLayout;
@BindView(R.id.downvoted_linear_layout_main_activity)
LinearLayout downvotedLinearLayout;
@BindView(R.id.hidden_linear_layout_main_activity)
LinearLayout hiddenLinearLayout;
@BindView(R.id.saved_linear_layout_main_activity)
LinearLayout savedLinearLayout;
@BindView(R.id.gilded_linear_layout_main_activity)
LinearLayout gildedLinearLayout;
@BindView(R.id.divider_main_activity)
View divider;
@BindView(R.id.settings_linear_layout_main_activity)
LinearLayout settingsLinearLayout;
@BindView(R.id.account_recycler_view_main_activity)
RecyclerView accountRecyclerView;
@BindView(R.id.tab_layout_main_activity)
TabLayout tabLayout;
@BindView(R.id.fab_main_activity)
FloatingActionButton fab;
AccountViewModel accountViewModel;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private SectionsPagerAdapter sectionsPagerAdapter;
private TextView mAccountNameTextView;
private TextView mKarmaTextView;
private GifImageView mProfileImageView;
private ImageView mBannerImageView;
private ImageView mDropIconImageView;
private RequestManager glide;
private AppBarLayout.LayoutParams params;
private PostTypeBottomSheetFragment postTypeBottomSheetFragment;
private SortTypeBottomSheetFragment bestSortTypeBottomSheetFragment;
private SortTypeBottomSheetFragment popularAndAllSortTypeBottomSheetFragment;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
@ -170,23 +197,9 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
private boolean mDrawerOnAccountSwitch = false;
private String mMessageFullname;
private String mNewAccountName;
private Menu mMenu;
private boolean isInLazyMode = false;
AccountViewModel accountViewModel;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme_NoActionBarWithTransparentStatusBar);
@ -215,12 +228,12 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Resources resources = getResources();
if(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
@ -229,12 +242,12 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if(state == State.COLLAPSED) {
if(finalLightNavBar) {
if (state == State.COLLAPSED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if(state == State.EXPANDED) {
if(finalLightNavBar) {
} else if (state == State.EXPANDED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -270,7 +283,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -300,7 +313,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
if(savedInstanceState != null) {
if (savedInstanceState != null) {
mFetchUserInfoSuccess = savedInstanceState.getBoolean(FETCH_USER_INFO_STATE);
mFetchSubscriptionsSuccess = savedInstanceState.getBoolean(FETCH_SUBSCRIPTIONS_STATE);
mDrawerOnAccountSwitch = savedInstanceState.getBoolean(DRAWER_ON_ACCOUNT_SWITCH_STATE);
@ -314,7 +327,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
mMessageFullname = savedInstanceState.getString(MESSAGE_FULLNAME_STATE);
mNewAccountName = savedInstanceState.getString(NEW_ACCOUNT_NAME_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndBindView();
} else {
bindView();
@ -326,7 +339,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
fab.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(MainActivity.this, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
@ -342,17 +355,17 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
WorkManager workManager = WorkManager.getInstance(this);
if(mNewAccountName != null) {
if(account == null || !account.getUsername().equals(mNewAccountName)) {
if (mNewAccountName != null) {
if (account == null || !account.getUsername().equals(mNewAccountName)) {
new SwitchAccountAsyncTask(mRedditDataRoomDatabase, mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
mNewAccountName = null;
if(newAccount == null) {
if (newAccount == null) {
mNullAccessToken = true;
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_subscriptions_main_activity).setVisible(false);
}
} else {
@ -362,12 +375,12 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
mBannerImageUrl = newAccount.getBannerImageUrl();
mKarma = newAccount.getKarma();
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_subscriptions_main_activity).setVisible(true);
}
}
if(enableNotification) {
if (enableNotification) {
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
@ -393,11 +406,11 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
mBannerImageUrl = account.getBannerImageUrl();
mKarma = account.getKarma();
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_subscriptions_main_activity).setVisible(true);
}
if(enableNotification) {
if (enableNotification) {
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
@ -417,10 +430,10 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
bindView();
}
} else {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_subscriptions_main_activity).setVisible(false);
}
} else {
@ -430,12 +443,12 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
mBannerImageUrl = account.getBannerImageUrl();
mKarma = account.getKarma();
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_subscriptions_main_activity).setVisible(true);
}
}
if(enableNotification) {
if (enableNotification) {
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
@ -458,7 +471,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
private void bindView() {
if(isDestroyed()) {
if (isDestroyed()) {
return;
}
@ -469,13 +482,14 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
fab.show();
if(isInLazyMode) {
if(position == sectionsPagerAdapter.getCurrentLazyModeFragmentPosition()) {
if (isInLazyMode) {
if (position == sectionsPagerAdapter.getCurrentLazyModeFragmentPosition()) {
sectionsPagerAdapter.resumeLazyMode();
} else {
sectionsPagerAdapter.pauseLazyMode();
@ -484,7 +498,8 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
@Override
public void onPageScrollStateChanged(int state) {}
public void onPageScrollStateChanged(int state) {
}
});
loadSubscriptions();
@ -493,41 +508,41 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
AccountRecyclerViewAdapter adapter = new AccountRecyclerViewAdapter(this, glide, mAccountName,
new AccountRecyclerViewAdapter.ItemSelectedListener() {
@Override
public void accountSelected(Account account) {
new SwitchAccountAsyncTask(mRedditDataRoomDatabase, account.getUsername(), newAccount -> {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}).execute();
}
@Override
public void addAccountSelected() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivityForResult(intent, LOGIN_ACTIVITY_REQUEST_CODE);
}
@Override
public void anonymousSelected() {
new SwitchToAnonymousAccountAsyncTask(mRedditDataRoomDatabase, false,
() -> {
@Override
public void accountSelected(Account account) {
new SwitchAccountAsyncTask(mRedditDataRoomDatabase, account.getUsername(), newAccount -> {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}).execute();
}
}
@Override
public void logoutSelected() {
new SwitchToAnonymousAccountAsyncTask(mRedditDataRoomDatabase, true,
() -> {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}).execute();
}
});
@Override
public void addAccountSelected() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivityForResult(intent, LOGIN_ACTIVITY_REQUEST_CODE);
}
@Override
public void anonymousSelected() {
new SwitchToAnonymousAccountAsyncTask(mRedditDataRoomDatabase, false,
() -> {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}).execute();
}
@Override
public void logoutSelected() {
new SwitchToAnonymousAccountAsyncTask(mRedditDataRoomDatabase, true,
() -> {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}).execute();
}
});
accountRecyclerView.setLayoutManager(new LinearLayoutManager(this));
accountRecyclerView.setNestedScrollingEnabled(false);
@ -537,9 +552,9 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
new AccountViewModel.Factory(getApplication(), mRedditDataRoomDatabase, mAccountName)).get(AccountViewModel.class);
accountViewModel.getAccountsExceptCurrentAccountLiveData().observe(this, adapter::changeAccountsDataset);
if(getIntent().hasExtra(EXTRA_POST_TYPE)) {
if (getIntent().hasExtra(EXTRA_POST_TYPE)) {
String type = getIntent().getStringExtra(EXTRA_POST_TYPE);
if(type != null && type.equals("popular")) {
if (type != null && type.equals("popular")) {
viewPager.setCurrentItem(1);
} else {
viewPager.setCurrentItem(2);
@ -553,7 +568,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
mBannerImageView = header.findViewById(R.id.banner_image_view_nav_header_main);
mDropIconImageView = header.findViewById(R.id.account_switcher_image_view_nav_header_main);
if(mDrawerOnAccountSwitch) {
if (mDrawerOnAccountSwitch) {
mDropIconImageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_baseline_arrow_drop_up_24px));
accountRecyclerView.setVisibility(View.VISIBLE);
allDrawerItemsLinearLayout.setVisibility(View.GONE);
@ -564,7 +579,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
header.setOnClickListener(view -> {
if(mDrawerOnAccountSwitch) {
if (mDrawerOnAccountSwitch) {
mDrawerOnAccountSwitch = false;
mDropIconImageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_baseline_arrow_drop_down_24px));
accountRecyclerView.setVisibility(View.GONE);
@ -579,10 +594,10 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
loadUserData();
if(mAccessToken != null) {
if (mAccessToken != null) {
mKarmaTextView.setText(getString(R.string.karma_info, mKarma));
mAccountNameTextView.setText(mAccountName);
if(mMessageFullname != null) {
if (mMessageFullname != null) {
ReadMessage.readMessage(mOauthRetrofit, mAccessToken, mMessageFullname, new ReadMessage.ReadMessageListener() {
@Override
public void readSuccess() {
@ -765,7 +780,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == LOGIN_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (requestCode == LOGIN_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
@ -781,13 +796,13 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_main_activity);
MenuItem subscriptionsItem = mMenu.findItem(R.id.action_subscriptions_main_activity);
if(mAccessToken != null) {
if (mAccessToken != null) {
subscriptionsItem.setVisible(true);
} else {
subscriptionsItem.setVisible(false);
}
if(isInLazyMode) {
if (isInLazyMode) {
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
collapsingToolbarLayout.setLayoutParams(params);
@ -808,7 +823,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
startActivity(subscriptionsIntent);
return true;
case R.id.action_sort_main_activity:
if(viewPager.getCurrentItem() == 1 ||viewPager.getCurrentItem() == 2) {
if (viewPager.getCurrentItem() == 1 || viewPager.getCurrentItem() == 2) {
popularAndAllSortTypeBottomSheetFragment.show(getSupportFragmentManager(), popularAndAllSortTypeBottomSheetFragment.getTag());
} else {
bestSortTypeBottomSheetFragment.show(getSupportFragmentManager(), bestSortTypeBottomSheetFragment.getTag());
@ -820,7 +835,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
startActivity(intent);
return true;
case R.id.action_refresh_main_activity:
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_lazy_mode_main_activity).setTitle(R.string.action_start_lazy_mode);
}
sectionsPagerAdapter.refresh();
@ -829,14 +844,14 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
return true;
case R.id.action_lazy_mode_main_activity:
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_main_activity);
if(isInLazyMode) {
if (isInLazyMode) {
sectionsPagerAdapter.stopLazyMode();
isInLazyMode = false;
lazyModeItem.setTitle(R.string.action_start_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
collapsingToolbarLayout.setLayoutParams(params);
} else {
if(sectionsPagerAdapter.startLazyMode()) {
if (sectionsPagerAdapter.startLazyMode()) {
isInLazyMode = true;
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
@ -918,7 +933,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
@Subscribe
public void onAccountSwitchEvent(SwitchAccountEvent event) {
if(!getClass().getName().equals(event.excludeActivityClassName)) {
if (!getClass().getName().equals(event.excludeActivityClassName)) {
finish();
}
}
@ -945,8 +960,8 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
@NonNull
@Override
public Fragment getItem(int position) {
if(mAccessToken == null) {
if(position == 0) {
if (mAccessToken == null) {
if (position == 0) {
PostFragment fragment = new PostFragment();
Bundle bundle = new Bundle();
bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_SUBREDDIT);
@ -978,7 +993,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
fragment.setArguments(bundle);
return fragment;
} else if(position == 1) {
} else if (position == 1) {
PostFragment fragment = new PostFragment();
Bundle bundle = new Bundle();
bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostDataSource.TYPE_SUBREDDIT);
@ -1002,9 +1017,8 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
@Override
public int getCount()
{
if(mAccessToken == null) {
public int getCount() {
if (mAccessToken == null) {
return 2;
}
return 3;
@ -1012,7 +1026,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
@Override
public CharSequence getPageTitle(int position) {
if(mAccessToken == null) {
if (mAccessToken == null) {
switch (position) {
case 0:
return "Popular";
@ -1036,7 +1050,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
if(mAccessToken == null) {
if (mAccessToken == null) {
switch (position) {
case 0:
popularPostFragment = (PostFragment) fragment;
@ -1060,7 +1074,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
boolean startLazyMode() {
if(mAccessToken == null) {
if (mAccessToken == null) {
switch (viewPager.getCurrentItem()) {
case 0:
return ((FragmentCommunicator) popularPostFragment).startLazyMode();
@ -1082,7 +1096,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
void stopLazyMode() {
if(mAccessToken == null) {
if (mAccessToken == null) {
switch (getCurrentLazyModeFragmentPosition()) {
case 0:
((FragmentCommunicator) popularPostFragment).stopLazyMode();
@ -1107,7 +1121,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
void resumeLazyMode() {
if(mAccessToken == null) {
if (mAccessToken == null) {
switch (getCurrentLazyModeFragmentPosition()) {
case 0:
((FragmentCommunicator) popularPostFragment).resumeLazyMode(false);
@ -1132,7 +1146,7 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
void pauseLazyMode() {
if(mAccessToken == null) {
if (mAccessToken == null) {
switch (getCurrentLazyModeFragmentPosition()) {
case 0:
((FragmentCommunicator) popularPostFragment).pauseLazyMode(false);
@ -1155,24 +1169,24 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
int getCurrentLazyModeFragmentPosition() {
if(mAccessToken == null) {
if(!isInLazyMode) {
if (mAccessToken == null) {
if (!isInLazyMode) {
return -1;
} else if(popularPostFragment != null && ((FragmentCommunicator) popularPostFragment).isInLazyMode()) {
} else if (popularPostFragment != null && ((FragmentCommunicator) popularPostFragment).isInLazyMode()) {
return 0;
} else if(allPostFragment != null && ((FragmentCommunicator) allPostFragment).isInLazyMode()) {
} else if (allPostFragment != null && ((FragmentCommunicator) allPostFragment).isInLazyMode()) {
return 1;
} else {
return -1;
}
} else {
if(!isInLazyMode) {
if (!isInLazyMode) {
return -1;
} else if(frontPagePostFragment != null && ((FragmentCommunicator) frontPagePostFragment).isInLazyMode()) {
} else if (frontPagePostFragment != null && ((FragmentCommunicator) frontPagePostFragment).isInLazyMode()) {
return 0;
} else if(popularPostFragment != null && ((FragmentCommunicator) popularPostFragment).isInLazyMode()) {
} else if (popularPostFragment != null && ((FragmentCommunicator) popularPostFragment).isInLazyMode()) {
return 1;
} else if(allPostFragment != null && ((FragmentCommunicator) allPostFragment).isInLazyMode()) {
} else if (allPostFragment != null && ((FragmentCommunicator) allPostFragment).isInLazyMode()) {
return 2;
} else {
return -1;
@ -1181,8 +1195,8 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
void changeSortType(String sortType) {
if(mAccessToken == null) {
if(viewPager.getCurrentItem() == 0) {
if (mAccessToken == null) {
if (viewPager.getCurrentItem() == 0) {
popularPostFragment.changeSortType(sortType);
} else {
allPostFragment.changeSortType(sortType);
@ -1202,30 +1216,30 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
public void refresh() {
if(mAccessToken == null) {
if(viewPager.getCurrentItem() == 0) {
if(popularPostFragment != null) {
if (mAccessToken == null) {
if (viewPager.getCurrentItem() == 0) {
if (popularPostFragment != null) {
((FragmentCommunicator) popularPostFragment).refresh();
}
} else {
if(allPostFragment != null) {
if (allPostFragment != null) {
((FragmentCommunicator) allPostFragment).refresh();
}
}
} else {
switch (viewPager.getCurrentItem()) {
case 0:
if(frontPagePostFragment != null) {
if (frontPagePostFragment != null) {
((FragmentCommunicator) frontPagePostFragment).refresh();
}
break;
case 1:
if(popularPostFragment != null) {
if (popularPostFragment != null) {
((FragmentCommunicator) popularPostFragment).refresh();
}
break;
case 2:
if(allPostFragment != null) {
if (allPostFragment != null) {
((FragmentCommunicator) allPostFragment).refresh();
}
}
@ -1233,13 +1247,13 @@ public class MainActivity extends AppCompatActivity implements SortTypeBottomShe
}
void changeNSFW(boolean nsfw) {
if(frontPagePostFragment != null) {
if (frontPagePostFragment != null) {
frontPagePostFragment.changeNSFW(nsfw);
}
if(popularPostFragment != null) {
if (popularPostFragment != null) {
popularPostFragment.changeNSFW(nsfw);
}
if(allPostFragment != null) {
if (allPostFragment != null) {
allPostFragment.changeNSFW(nsfw);
}
}

View File

@ -91,21 +91,47 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
private static final int PICK_IMAGE_REQUEST_CODE = 1;
private static final int CAPTURE_IMAGE_REQUEST_CODE = 2;
@BindView(R.id.coordinator_layout_post_image_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_post_image_activity) Toolbar toolbar;
@BindView(R.id.subreddit_icon_gif_image_view_post_image_activity) GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_post_image_activity) TextView subredditNameTextView;
@BindView(R.id.rules_button_post_image_activity) Button rulesButton;
@BindView(R.id.flair_custom_text_view_post_image_activity) CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_image_activity) CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_image_activity) CustomTextView nsfwTextView;
@BindView(R.id.post_title_edit_text_post_image_activity) EditText titleEditText;
@BindView(R.id.select_image_constraint_layout_post_image_activity) ConstraintLayout constraintLayout;
@BindView(R.id.capture_fab_post_image_activity) FloatingActionButton captureFab;
@BindView(R.id.select_from_library_fab_post_image_activity) FloatingActionButton selectFromLibraryFab;
@BindView(R.id.select_again_text_view_post_image_activity) TextView selectAgainTextView;
@BindView(R.id.image_view_post_image_activity) ImageView imageView;
@BindView(R.id.coordinator_layout_post_image_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_post_image_activity)
Toolbar toolbar;
@BindView(R.id.subreddit_icon_gif_image_view_post_image_activity)
GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_post_image_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_post_image_activity)
Button rulesButton;
@BindView(R.id.flair_custom_text_view_post_image_activity)
CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_image_activity)
CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_image_activity)
CustomTextView nsfwTextView;
@BindView(R.id.post_title_edit_text_post_image_activity)
EditText titleEditText;
@BindView(R.id.select_image_constraint_layout_post_image_activity)
ConstraintLayout constraintLayout;
@BindView(R.id.capture_fab_post_image_activity)
FloatingActionButton captureFab;
@BindView(R.id.select_from_library_fab_post_image_activity)
FloatingActionButton selectFromLibraryFab;
@BindView(R.id.select_again_text_view_post_image_activity)
TextView selectAgainTextView;
@BindView(R.id.image_view_post_image_activity)
ImageView imageView;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("upload_media")
Retrofit mUploadMediaRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
@ -116,34 +142,14 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
private boolean loadSubredditIconSuccessful = true;
private boolean isPosting;
private Uri imageUri;
private Flair flair;
private boolean isSpoiler = false;
private boolean isNSFW = false;
private Menu mMemu;
private RequestManager mGlide;
private FlairBottomSheetFragment flairSelectionBottomSheetFragment;
private Snackbar mPostingSnackbar;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("upload_media")
Retrofit mUploadMediaRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -165,9 +171,9 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
EventBus.getDefault().register(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -183,7 +189,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -198,12 +204,12 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
mPostingSnackbar = Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_INDEFINITE);
if(savedInstanceState != null) {
if (savedInstanceState != null) {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccount();
}
@ -217,33 +223,33 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
isSpoiler = savedInstanceState.getBoolean(IS_SPOILER_STATE);
isNSFW = savedInstanceState.getBoolean(IS_NSFW_STATE);
if(savedInstanceState.getString(IMAGE_URI_STATE) != null) {
if (savedInstanceState.getString(IMAGE_URI_STATE) != null) {
imageUri = Uri.parse(savedInstanceState.getString(IMAGE_URI_STATE));
loadImage();
}
if(subredditName != null) {
if (subredditName != null) {
subredditNameTextView.setTextColor(getResources().getColor(R.color.primaryTextColor));
subredditNameTextView.setText(subredditName);
flairTextView.setVisibility(View.VISIBLE);
if(!loadSubredditIconSuccessful) {
if (!loadSubredditIconSuccessful) {
loadSubredditIcon();
}
}
displaySubredditIcon();
if(isPosting) {
if (isPosting) {
mPostingSnackbar.show();
}
if(flair != null) {
if (flair != null) {
flairTextView.setText(flair.getText());
flairTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
}
if(isSpoiler) {
if (isSpoiler) {
spoilerTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
}
if(isNSFW) {
if (isNSFW) {
nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
} else {
@ -251,7 +257,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
isPosting = false;
if(getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
if (getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
loadSubredditIconSuccessful = false;
subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
subredditSelected = true;
@ -265,7 +271,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
}
imageUri = getIntent().getData();
if(imageUri != null) {
if (imageUri != null) {
loadImage();
}
}
@ -281,11 +287,11 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
});
rulesButton.setOnClickListener(view -> {
if(subredditName == null) {
if (subredditName == null) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(this, RulesActivity.class);
if(subredditIsUser) {
if (subredditIsUser) {
intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, "u_" + subredditName);
} else {
intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, subredditName);
@ -295,7 +301,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
});
flairTextView.setOnClickListener(view -> {
if(flair == null) {
if (flair == null) {
flairSelectionBottomSheetFragment = new FlairBottomSheetFragment();
Bundle bundle = new Bundle();
bundle.putString(FlairBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
@ -310,7 +316,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
});
spoilerTextView.setOnClickListener(view -> {
if(!isSpoiler) {
if (!isSpoiler) {
spoilerTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
isSpoiler = true;
} else {
@ -320,7 +326,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
});
nsfwTextView.setOnClickListener(view -> {
if(!isNSFW) {
if (!isNSFW) {
nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
isNSFW = true;
} else {
@ -331,7 +337,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
captureFab.setOnClickListener(view -> {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(pictureIntent.resolveActivity(getPackageManager()) != null) {
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
try {
imageUri = FileProvider.getUriForFile(this, "ml.docilealligator.infinityforreddit.provider",
File.createTempFile("temp_img", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
@ -349,7 +355,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
});
selectAgainTextView.setOnClickListener(view -> {
@ -363,7 +369,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
private void getCurrentAccount() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -380,7 +386,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
}
private void displaySubredditIcon() {
if(iconUrl != null && !iconUrl.equals("")) {
if (iconUrl != null && !iconUrl.equals("")) {
mGlide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@ -415,7 +421,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.post_image_activity, menu);
mMemu = menu;
if(isPosting) {
if (isPosting) {
mMemu.findItem(R.id.action_send_post_image_activity).setEnabled(false);
mMemu.findItem(R.id.action_send_post_image_activity).getIcon().setAlpha(130);
}
@ -426,11 +432,11 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(isPosting) {
if (isPosting) {
promptAlertDialog(R.string.exit_when_submit_post, R.string.exit_when_submit_post_detail);
return true;
} else {
if(!titleEditText.getText().toString().equals("") || imageUri != null) {
if (!titleEditText.getText().toString().equals("") || imageUri != null) {
promptAlertDialog(R.string.discard_post, R.string.discard_post_detail);
return true;
}
@ -438,17 +444,17 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
finish();
return true;
case R.id.action_send_post_image_activity:
if(!subredditSelected) {
if (!subredditSelected) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
return true;
}
if(titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
return true;
}
if(imageUri == null) {
if (imageUri == null) {
Snackbar.make(coordinatorLayout, R.string.select_an_image, Snackbar.LENGTH_SHORT).show();
return true;
}
@ -461,7 +467,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
mPostingSnackbar.show();
String subredditName;
if(subredditIsUser) {
if (subredditIsUser) {
subredditName = "u_" + subredditNameTextView.getText().toString();
} else {
subredditName = subredditNameTextView.getText().toString();
@ -478,7 +484,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_IMAGE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
@ -492,10 +498,10 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
@Override
public void onBackPressed() {
if(isPosting) {
if (isPosting) {
promptAlertDialog(R.string.exit_when_submit_post, R.string.exit_when_submit_post_detail);
} else {
if(!titleEditText.getText().toString().equals("") || imageUri != null) {
if (!titleEditText.getText().toString().equals("") || imageUri != null) {
promptAlertDialog(R.string.discard_post, R.string.discard_post_detail);
} else {
finish();
@ -510,7 +516,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
outState.putString(SUBREDDIT_ICON_STATE, iconUrl);
outState.putBoolean(SUBREDDIT_SELECTED_STATE, subredditSelected);
outState.putBoolean(SUBREDDIT_IS_USER_STATE, subredditIsUser);
if(imageUri != null) {
if (imageUri != null) {
outState.putString(IMAGE_URI_STATE, imageUri.toString());
}
outState.putBoolean(LOAD_SUBREDDIT_ICON_STATE, loadSubredditIconSuccessful);
@ -526,8 +532,8 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
subredditName = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_NAME);
iconUrl = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL);
subredditSelected = true;
@ -542,9 +548,9 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
flairTextView.setText(getString(R.string.flair));
flair = null;
}
} else if(requestCode == PICK_IMAGE_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if(data == null) {
} else if (requestCode == PICK_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if (data == null) {
Snackbar.make(coordinatorLayout, R.string.error_getting_image, Snackbar.LENGTH_SHORT).show();
return;
}
@ -552,8 +558,8 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
imageUri = data.getData();
loadImage();
}
} else if(requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
} else if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
loadImage();
}
}
@ -581,7 +587,7 @@ public class PostImageActivity extends AppCompatActivity implements FlairBottomS
public void onSubmitImagePostEvent(SubmitImagePostEvent submitImagePostEvent) {
isPosting = false;
mPostingSnackbar.dismiss();
if(submitImagePostEvent.postSuccess) {
if (submitImagePostEvent.postSuccess) {
Intent intent = new Intent(PostImageActivity.this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
startActivity(intent);

View File

@ -79,17 +79,36 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0;
@BindView(R.id.coordinator_layout_post_link_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_post_link_activity) Toolbar toolbar;
@BindView(R.id.subreddit_icon_gif_image_view_post_link_activity) GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_post_link_activity) TextView subredditNameTextView;
@BindView(R.id.rules_button_post_link_activity) Button rulesButton;
@BindView(R.id.flair_custom_text_view_post_link_activity) CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_link_activity) CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_link_activity) CustomTextView nsfwTextView;
@BindView(R.id.post_title_edit_text_post_link_activity) EditText titleEditText;
@BindView(R.id.post_link_edit_text_post_link_activity) EditText contentEditText;
@BindView(R.id.coordinator_layout_post_link_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_post_link_activity)
Toolbar toolbar;
@BindView(R.id.subreddit_icon_gif_image_view_post_link_activity)
GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_post_link_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_post_link_activity)
Button rulesButton;
@BindView(R.id.flair_custom_text_view_post_link_activity)
CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_link_activity)
CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_link_activity)
CustomTextView nsfwTextView;
@BindView(R.id.post_title_edit_text_post_link_activity)
EditText titleEditText;
@BindView(R.id.post_link_edit_text_post_link_activity)
EditText contentEditText;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String iconUrl;
@ -98,30 +117,14 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
private boolean subredditIsUser;
private boolean loadSubredditIconSuccessful = true;
private boolean isPosting;
private Flair flair;
private boolean isSpoiler = false;
private boolean isNSFW = false;
private Menu mMemu;
private RequestManager mGlide;
private FlairBottomSheetFragment flairSelectionBottomSheetFragment;
private Snackbar mPostingSnackbar;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -143,9 +146,9 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
EventBus.getDefault().register(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -161,7 +164,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -176,11 +179,11 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
mPostingSnackbar = Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_INDEFINITE);
if(savedInstanceState != null) {
if (savedInstanceState != null) {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccount();
}
@ -194,28 +197,28 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
isSpoiler = savedInstanceState.getBoolean(IS_SPOILER_STATE);
isNSFW = savedInstanceState.getBoolean(IS_NSFW_STATE);
if(subredditName != null) {
if (subredditName != null) {
subredditNameTextView.setTextColor(getResources().getColor(R.color.primaryTextColor));
subredditNameTextView.setText(subredditName);
flairTextView.setVisibility(View.VISIBLE);
if(!loadSubredditIconSuccessful) {
if (!loadSubredditIconSuccessful) {
loadSubredditIcon();
}
}
displaySubredditIcon();
if(isPosting) {
if (isPosting) {
mPostingSnackbar.show();
}
if(flair != null) {
if (flair != null) {
flairTextView.setText(flair.getText());
flairTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
}
if(isSpoiler) {
if (isSpoiler) {
spoilerTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
}
if(isNSFW) {
if (isNSFW) {
nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
} else {
@ -223,7 +226,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
isPosting = false;
if(getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
if (getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
loadSubredditIconSuccessful = false;
subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
subredditSelected = true;
@ -238,7 +241,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
}
String link = getIntent().getStringExtra(EXTRA_LINK);
if(link != null) {
if (link != null) {
contentEditText.setText(link);
}
}
@ -254,11 +257,11 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
});
rulesButton.setOnClickListener(view -> {
if(subredditName == null) {
if (subredditName == null) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(this, RulesActivity.class);
if(subredditIsUser) {
if (subredditIsUser) {
intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, "u_" + subredditName);
} else {
intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, subredditName);
@ -268,7 +271,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
});
flairTextView.setOnClickListener(view -> {
if(flair == null) {
if (flair == null) {
flairSelectionBottomSheetFragment = new FlairBottomSheetFragment();
Bundle bundle = new Bundle();
bundle.putString(FlairBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
@ -283,7 +286,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
});
spoilerTextView.setOnClickListener(view -> {
if(!isSpoiler) {
if (!isSpoiler) {
spoilerTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
isSpoiler = true;
} else {
@ -293,7 +296,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
});
nsfwTextView.setOnClickListener(view -> {
if(!isNSFW) {
if (!isNSFW) {
nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
isNSFW = true;
} else {
@ -305,7 +308,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
private void getCurrentAccount() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -314,7 +317,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
}
private void displaySubredditIcon() {
if(iconUrl != null && !iconUrl.equals("")) {
if (iconUrl != null && !iconUrl.equals("")) {
mGlide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@ -348,7 +351,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.post_link_activity, menu);
mMemu = menu;
if(isPosting) {
if (isPosting) {
mMemu.findItem(R.id.action_send_post_link_activity).setEnabled(false);
mMemu.findItem(R.id.action_send_post_link_activity).getIcon().setAlpha(130);
}
@ -359,11 +362,11 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(isPosting) {
if (isPosting) {
promptAlertDialog(R.string.exit_when_submit_post, R.string.exit_when_submit_post_detail);
return true;
} else {
if(!titleEditText.getText().toString().equals("") || !contentEditText.getText().toString().equals("")) {
if (!titleEditText.getText().toString().equals("") || !contentEditText.getText().toString().equals("")) {
promptAlertDialog(R.string.discard_post, R.string.discard_post_detail);
return true;
}
@ -371,17 +374,17 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
finish();
return true;
case R.id.action_send_post_link_activity:
if(!subredditSelected) {
if (!subredditSelected) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
return true;
}
if(titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
return true;
}
if(contentEditText.getText() == null || contentEditText.getText().toString().equals("")) {
if (contentEditText.getText() == null || contentEditText.getText().toString().equals("")) {
Snackbar.make(coordinatorLayout, R.string.link_required, Snackbar.LENGTH_SHORT).show();
return true;
}
@ -394,7 +397,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
mPostingSnackbar.show();
String subredditName;
if(subredditIsUser) {
if (subredditIsUser) {
subredditName = "u_" + subredditNameTextView.getText().toString();
} else {
subredditName = subredditNameTextView.getText().toString();
@ -420,10 +423,10 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
@Override
public void onBackPressed() {
if(isPosting) {
if (isPosting) {
promptAlertDialog(R.string.exit_when_submit_post, R.string.exit_when_submit_post_detail);
} else {
if(!titleEditText.getText().toString().equals("") || !contentEditText.getText().toString().equals("")) {
if (!titleEditText.getText().toString().equals("") || !contentEditText.getText().toString().equals("")) {
promptAlertDialog(R.string.discard_post, R.string.discard_post_detail);
} else {
finish();
@ -450,8 +453,8 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
subredditName = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_NAME);
iconUrl = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL);
subredditSelected = true;
@ -491,7 +494,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
public void onSubmitLinkPostEvent(SubmitTextOrLinkPostEvent submitTextOrLinkPostEvent) {
isPosting = false;
mPostingSnackbar.dismiss();
if(submitTextOrLinkPostEvent.postSuccess) {
if (submitTextOrLinkPostEvent.postSuccess) {
Intent intent = new Intent(PostLinkActivity.this, ViewPostDetailActivity.class);
intent.putExtra(ViewPostDetailActivity.EXTRA_POST_DATA, submitTextOrLinkPostEvent.post);
startActivity(intent);
@ -499,7 +502,7 @@ public class PostLinkActivity extends AppCompatActivity implements FlairBottomSh
} else {
mMemu.findItem(R.id.action_send_post_link_activity).setEnabled(true);
mMemu.findItem(R.id.action_send_post_link_activity).getIcon().setAlpha(255);
if(submitTextOrLinkPostEvent.errorMessage == null) {
if (submitTextOrLinkPostEvent.errorMessage == null) {
Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(coordinatorLayout, submitTextOrLinkPostEvent.errorMessage.substring(0, 1).toUpperCase()

View File

@ -79,17 +79,36 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0;
@BindView(R.id.coordinator_layout_post_text_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_post_text_activity) Toolbar toolbar;
@BindView(R.id.subreddit_icon_gif_image_view_search_activity) GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_search_activity) TextView subredditNameTextView;
@BindView(R.id.rules_button_post_text_activity) Button rulesButton;
@BindView(R.id.flair_custom_text_view_post_text_activity) CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_text_activity) CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_text_activity) CustomTextView nsfwTextView;
@BindView(R.id.post_title_edit_text_post_text_activity) EditText titleEditText;
@BindView(R.id.post_text_content_edit_text_post_text_activity) EditText contentEditText;
@BindView(R.id.coordinator_layout_post_text_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_post_text_activity)
Toolbar toolbar;
@BindView(R.id.subreddit_icon_gif_image_view_search_activity)
GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_search_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_post_text_activity)
Button rulesButton;
@BindView(R.id.flair_custom_text_view_post_text_activity)
CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_text_activity)
CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_text_activity)
CustomTextView nsfwTextView;
@BindView(R.id.post_title_edit_text_post_text_activity)
EditText titleEditText;
@BindView(R.id.post_text_content_edit_text_post_text_activity)
EditText contentEditText;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String iconUrl;
@ -98,30 +117,14 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
private boolean subredditIsUser;
private boolean loadSubredditIconSuccessful = true;
private boolean isPosting;
private Flair flair;
private boolean isSpoiler = false;
private boolean isNSFW = false;
private Menu mMemu;
private RequestManager mGlide;
private FlairBottomSheetFragment flairSelectionBottomSheetFragment;
private Snackbar mPostingSnackbar;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -143,9 +146,9 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
EventBus.getDefault().register(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -161,7 +164,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -176,11 +179,11 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
mPostingSnackbar = Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_INDEFINITE);
if(savedInstanceState != null) {
if (savedInstanceState != null) {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccount();
}
@ -194,28 +197,28 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
isSpoiler = savedInstanceState.getBoolean(IS_SPOILER_STATE);
isNSFW = savedInstanceState.getBoolean(IS_NSFW_STATE);
if(subredditName != null) {
if (subredditName != null) {
subredditNameTextView.setTextColor(getResources().getColor(R.color.primaryTextColor));
subredditNameTextView.setText(subredditName);
flairTextView.setVisibility(View.VISIBLE);
if(!loadSubredditIconSuccessful) {
if (!loadSubredditIconSuccessful) {
loadSubredditIcon();
}
}
displaySubredditIcon();
if(isPosting) {
if (isPosting) {
mPostingSnackbar.show();
}
if(flair != null) {
if (flair != null) {
flairTextView.setText(flair.getText());
flairTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
}
if(isSpoiler) {
if (isSpoiler) {
spoilerTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
}
if(isNSFW) {
if (isNSFW) {
nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
} else {
@ -223,7 +226,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
isPosting = false;
if(getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
if (getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
loadSubredditIconSuccessful = false;
subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
subredditSelected = true;
@ -238,7 +241,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
}
String text = getIntent().getStringExtra(EXTRA_CONTENT);
if(text != null) {
if (text != null) {
contentEditText.setText(text);
}
}
@ -254,11 +257,11 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
});
rulesButton.setOnClickListener(view -> {
if(subredditName == null) {
if (subredditName == null) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(this, RulesActivity.class);
if(subredditIsUser) {
if (subredditIsUser) {
intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, "u_" + subredditName);
} else {
intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, subredditName);
@ -268,11 +271,11 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
});
flairTextView.setOnClickListener(view -> {
if(flair == null) {
if (flair == null) {
flairSelectionBottomSheetFragment = new FlairBottomSheetFragment();
Bundle bundle = new Bundle();
bundle.putString(FlairBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
if(subredditIsUser) {
if (subredditIsUser) {
bundle.putString(FlairBottomSheetFragment.EXTRA_SUBREDDIT_NAME, "u_" + subredditName);
} else {
bundle.putString(FlairBottomSheetFragment.EXTRA_SUBREDDIT_NAME, subredditName);
@ -287,7 +290,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
});
spoilerTextView.setOnClickListener(view -> {
if(!isSpoiler) {
if (!isSpoiler) {
spoilerTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
isSpoiler = true;
} else {
@ -297,7 +300,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
});
nsfwTextView.setOnClickListener(view -> {
if(!isNSFW) {
if (!isNSFW) {
nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
isNSFW = true;
} else {
@ -309,7 +312,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
private void getCurrentAccount() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -318,7 +321,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
}
private void displaySubredditIcon() {
if(iconUrl != null && !iconUrl.equals("")) {
if (iconUrl != null && !iconUrl.equals("")) {
mGlide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@ -353,7 +356,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.post_text_activity, menu);
mMemu = menu;
if(isPosting) {
if (isPosting) {
mMemu.findItem(R.id.action_send_post_text_activity).setEnabled(false);
mMemu.findItem(R.id.action_send_post_text_activity).getIcon().setAlpha(130);
}
@ -364,11 +367,11 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(isPosting) {
if (isPosting) {
promptAlertDialog(R.string.exit_when_submit_post, R.string.exit_when_submit_post_detail);
return true;
} else {
if(!titleEditText.getText().toString().equals("") || !contentEditText.getText().toString().equals("")) {
if (!titleEditText.getText().toString().equals("") || !contentEditText.getText().toString().equals("")) {
promptAlertDialog(R.string.discard_post, R.string.discard_post_detail);
return true;
}
@ -376,12 +379,12 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
finish();
return true;
case R.id.action_send_post_text_activity:
if(!subredditSelected) {
if (!subredditSelected) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
return true;
}
if(titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
return true;
}
@ -394,7 +397,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
mPostingSnackbar.show();
String subredditName;
if(subredditIsUser) {
if (subredditIsUser) {
subredditName = "u_" + subredditNameTextView.getText().toString();
} else {
subredditName = subredditNameTextView.getText().toString();
@ -420,10 +423,10 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
@Override
public void onBackPressed() {
if(isPosting) {
if (isPosting) {
promptAlertDialog(R.string.exit_when_submit_post, R.string.exit_when_submit_post_detail);
} else {
if(!titleEditText.getText().toString().equals("") || !contentEditText.getText().toString().equals("")) {
if (!titleEditText.getText().toString().equals("") || !contentEditText.getText().toString().equals("")) {
promptAlertDialog(R.string.discard_post, R.string.discard_post_detail);
} else {
finish();
@ -450,8 +453,8 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
subredditName = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_NAME);
iconUrl = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL);
subredditSelected = true;
@ -491,7 +494,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
public void onSubmitTextPostEvent(SubmitTextOrLinkPostEvent submitTextOrLinkPostEvent) {
isPosting = false;
mPostingSnackbar.dismiss();
if(submitTextOrLinkPostEvent.postSuccess) {
if (submitTextOrLinkPostEvent.postSuccess) {
Intent intent = new Intent(PostTextActivity.this, ViewPostDetailActivity.class);
intent.putExtra(ViewPostDetailActivity.EXTRA_POST_DATA, submitTextOrLinkPostEvent.post);
startActivity(intent);
@ -499,7 +502,7 @@ public class PostTextActivity extends AppCompatActivity implements FlairBottomSh
} else {
mMemu.findItem(R.id.action_send_post_text_activity).setEnabled(true);
mMemu.findItem(R.id.action_send_post_text_activity).getIcon().setAlpha(255);
if(submitTextOrLinkPostEvent.errorMessage == null) {
if (submitTextOrLinkPostEvent.errorMessage == null) {
Snackbar.make(coordinatorLayout, R.string.post_failed, Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(coordinatorLayout, submitTextOrLinkPostEvent.errorMessage.substring(0, 1).toUpperCase()

View File

@ -49,19 +49,19 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Flair;
import ml.docilealligator.infinityforreddit.Fragment.FlairBottomSheetFragment;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.AsyncTask.LoadSubredditIconAsyncTask;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SubmitVideoPostEvent;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.Flair;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Fragment.FlairBottomSheetFragment;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.SubmitPostService;
import ml.docilealligator.infinityforreddit.Event.SubmitVideoPostEvent;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
@ -93,21 +93,50 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
private static final int PICK_VIDEO_REQUEST_CODE = 1;
private static final int CAPTURE_VIDEO_REQUEST_CODE = 2;
@BindView(R.id.coordinator_layout_post_video_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_post_video_activity) Toolbar toolbar;
@BindView(R.id.subreddit_icon_gif_image_view_post_video_activity) GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_post_video_activity) TextView subredditNameTextView;
@BindView(R.id.rules_button_post_video_activity) Button rulesButton;
@BindView(R.id.flair_custom_text_view_post_video_activity) CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_video_activity) CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_video_activity) CustomTextView nsfwTextView;
@BindView(R.id.post_title_edit_text_post_video_activity) EditText titleEditText;
@BindView(R.id.select_video_constraint_layout_post_video_activity) ConstraintLayout constraintLayout;
@BindView(R.id.capture_fab_post_video_activity) FloatingActionButton captureFab;
@BindView(R.id.select_from_library_fab_post_video_activity) FloatingActionButton selectFromLibraryFab;
@BindView(R.id.select_again_text_view_post_video_activity) TextView selectAgainTextView;
@BindView(R.id.player_view_post_video_activity) PlayerView videoPlayerView;
@BindView(R.id.coordinator_layout_post_video_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.toolbar_post_video_activity)
Toolbar toolbar;
@BindView(R.id.subreddit_icon_gif_image_view_post_video_activity)
GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_post_video_activity)
TextView subredditNameTextView;
@BindView(R.id.rules_button_post_video_activity)
Button rulesButton;
@BindView(R.id.flair_custom_text_view_post_video_activity)
CustomTextView flairTextView;
@BindView(R.id.spoiler_custom_text_view_post_video_activity)
CustomTextView spoilerTextView;
@BindView(R.id.nsfw_custom_text_view_post_video_activity)
CustomTextView nsfwTextView;
@BindView(R.id.post_title_edit_text_post_video_activity)
EditText titleEditText;
@BindView(R.id.select_video_constraint_layout_post_video_activity)
ConstraintLayout constraintLayout;
@BindView(R.id.capture_fab_post_video_activity)
FloatingActionButton captureFab;
@BindView(R.id.select_from_library_fab_post_video_activity)
FloatingActionButton selectFromLibraryFab;
@BindView(R.id.select_again_text_view_post_video_activity)
TextView selectAgainTextView;
@BindView(R.id.player_view_post_video_activity)
PlayerView videoPlayerView;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("upload_media")
Retrofit mUploadMediaRetrofit;
@Inject
@Named("upload_video")
Retrofit mUploadVideoRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
@ -119,41 +148,16 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
private boolean loadSubredditIconSuccessful = true;
private boolean isPosting;
private boolean wasPlaying;
private Flair flair;
private boolean isSpoiler = false;
private boolean isNSFW = false;
private Menu mMemu;
private RequestManager mGlide;
private FlairBottomSheetFragment mFlairSelectionBottomSheetFragment;
private Snackbar mPostingSnackbar;
private DataSource.Factory dataSourceFactory;
private SimpleExoPlayer player;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("upload_media")
Retrofit mUploadMediaRetrofit;
@Inject
@Named("upload_video")
Retrofit mUploadVideoRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -175,9 +179,9 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
EventBus.getDefault().register(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -193,7 +197,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -214,7 +218,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
mPostingSnackbar = Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_INDEFINITE);
if(savedInstanceState != null) {
if (savedInstanceState != null) {
subredditName = savedInstanceState.getString(SUBREDDIT_NAME_STATE);
iconUrl = savedInstanceState.getString(SUBREDDIT_ICON_STATE);
subredditSelected = savedInstanceState.getBoolean(SUBREDDIT_SELECTED_STATE);
@ -228,37 +232,37 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccount();
}
if(savedInstanceState.getString(VIDEO_URI_STATE) != null) {
if (savedInstanceState.getString(VIDEO_URI_STATE) != null) {
videoUri = Uri.parse(savedInstanceState.getString(VIDEO_URI_STATE));
loadVideo();
}
if(subredditName != null) {
if (subredditName != null) {
subredditNameTextView.setTextColor(getResources().getColor(R.color.primaryTextColor));
subredditNameTextView.setText(subredditName);
flairTextView.setVisibility(View.VISIBLE);
if(!loadSubredditIconSuccessful) {
if (!loadSubredditIconSuccessful) {
loadSubredditIcon();
}
}
displaySubredditIcon();
if(isPosting) {
if (isPosting) {
mPostingSnackbar.show();
}
if(flair != null) {
if (flair != null) {
flairTextView.setText(flair.getText());
flairTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
}
if(isSpoiler) {
if (isSpoiler) {
spoilerTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
}
if(isNSFW) {
if (isNSFW) {
nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
} else {
@ -266,7 +270,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
isPosting = false;
if(getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
if (getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
loadSubredditIconSuccessful = false;
subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
subredditSelected = true;
@ -280,7 +284,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
}
videoUri = getIntent().getData();
if(videoUri != null) {
if (videoUri != null) {
loadVideo();
}
}
@ -296,11 +300,11 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
});
rulesButton.setOnClickListener(view -> {
if(subredditName == null) {
if (subredditName == null) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(this, RulesActivity.class);
if(subredditIsUser) {
if (subredditIsUser) {
intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, "u_" + subredditName);
} else {
intent.putExtra(RulesActivity.EXTRA_SUBREDDIT_NAME, subredditName);
@ -310,7 +314,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
});
flairTextView.setOnClickListener(view -> {
if(flair == null) {
if (flair == null) {
mFlairSelectionBottomSheetFragment = new FlairBottomSheetFragment();
Bundle bundle = new Bundle();
bundle.putString(FlairBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
@ -325,7 +329,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
});
spoilerTextView.setOnClickListener(view -> {
if(!isSpoiler) {
if (!isSpoiler) {
spoilerTextView.setBackgroundColor(getResources().getColor(R.color.backgroundColorPrimaryDark));
isSpoiler = true;
} else {
@ -335,7 +339,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
});
nsfwTextView.setOnClickListener(view -> {
if(!isNSFW) {
if (!isNSFW) {
nsfwTextView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
isNSFW = true;
} else {
@ -355,7 +359,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,getResources().getString(R.string.select_from_gallery)), PICK_VIDEO_REQUEST_CODE);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_from_gallery)), PICK_VIDEO_REQUEST_CODE);
});
selectAgainTextView.setOnClickListener(view -> {
@ -370,7 +374,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
private void getCurrentAccount() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -389,7 +393,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
}
private void displaySubredditIcon() {
if(iconUrl != null && !iconUrl.equals("")) {
if (iconUrl != null && !iconUrl.equals("")) {
mGlide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@ -423,7 +427,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.post_video_activity, menu);
mMemu = menu;
if(isPosting) {
if (isPosting) {
mMemu.findItem(R.id.action_send_post_video_activity).setEnabled(false);
mMemu.findItem(R.id.action_send_post_video_activity).getIcon().setAlpha(130);
}
@ -434,11 +438,11 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(isPosting) {
if (isPosting) {
promptAlertDialog(R.string.exit_when_submit_post, R.string.exit_when_submit_post_detail);
return true;
} else {
if(!titleEditText.getText().toString().equals("") || videoUri != null) {
if (!titleEditText.getText().toString().equals("") || videoUri != null) {
promptAlertDialog(R.string.discard_post, R.string.discard_post_detail);
return true;
}
@ -446,17 +450,17 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
finish();
return true;
case R.id.action_send_post_video_activity:
if(!subredditSelected) {
if (!subredditSelected) {
Snackbar.make(coordinatorLayout, R.string.select_a_subreddit, Snackbar.LENGTH_SHORT).show();
return true;
}
if(titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
if (titleEditText.getText() == null || titleEditText.getText().toString().equals("")) {
Snackbar.make(coordinatorLayout, R.string.title_required, Snackbar.LENGTH_SHORT).show();
return true;
}
if(videoUri == null) {
if (videoUri == null) {
Snackbar.make(coordinatorLayout, R.string.select_an_image, Snackbar.LENGTH_SHORT).show();
return true;
}
@ -469,7 +473,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
mPostingSnackbar.show();
String subredditName;
if(subredditIsUser) {
if (subredditIsUser) {
subredditName = "u_" + subredditNameTextView.getText().toString();
} else {
subredditName = subredditNameTextView.getText().toString();
@ -486,7 +490,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
intent.putExtra(SubmitPostService.EXTRA_POST_TYPE, SubmitPostService.EXTRA_POST_TYPE_VIDEO);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
@ -500,10 +504,10 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
@Override
public void onBackPressed() {
if(isPosting) {
if (isPosting) {
promptAlertDialog(R.string.exit_when_submit_post, R.string.exit_when_submit_post_detail);
} else {
if(!titleEditText.getText().toString().equals("") || videoUri != null) {
if (!titleEditText.getText().toString().equals("") || videoUri != null) {
promptAlertDialog(R.string.discard_post, R.string.discard_post_detail);
} else {
finish();
@ -514,7 +518,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
@Override
protected void onStart() {
super.onStart();
if(wasPlaying) {
if (wasPlaying) {
player.setPlayWhenReady(true);
}
}
@ -532,7 +536,7 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
outState.putString(SUBREDDIT_ICON_STATE, iconUrl);
outState.putBoolean(SUBREDDIT_SELECTED_STATE, subredditSelected);
outState.putBoolean(SUBREDDIT_IS_USER_STATE, subredditIsUser);
if(videoUri != null) {
if (videoUri != null) {
outState.putString(VIDEO_URI_STATE, videoUri.toString());
}
outState.putBoolean(LOAD_SUBREDDIT_ICON_STATE, loadSubredditIconSuccessful);
@ -548,9 +552,9 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if(data != null) {
if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if (data != null) {
subredditName = data.getStringExtra(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_NAME);
iconUrl = data.getStringExtra(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL);
subredditSelected = true;
@ -566,9 +570,9 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
flair = null;
}
}
} else if(requestCode == PICK_VIDEO_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if(data == null) {
} else if (requestCode == PICK_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
if (data == null) {
Snackbar.make(coordinatorLayout, R.string.error_getting_video, Snackbar.LENGTH_SHORT).show();
return;
}
@ -577,8 +581,8 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
loadVideo();
}
} else if (requestCode == CAPTURE_VIDEO_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if(data != null && data.getData() != null) {
if (resultCode == RESULT_OK) {
if (data != null && data.getData() != null) {
videoUri = data.getData();
loadVideo();
} else {
@ -614,13 +618,13 @@ public class PostVideoActivity extends AppCompatActivity implements FlairBottomS
mMemu.findItem(R.id.action_send_post_video_activity).setEnabled(true);
mMemu.findItem(R.id.action_send_post_video_activity).getIcon().setAlpha(255);
if(submitVideoPostEvent.postSuccess) {
if (submitVideoPostEvent.postSuccess) {
Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY,
mAccountName);
startActivity(intent);
finish();
} else if(submitVideoPostEvent.errorProcessingVideo) {
} else if (submitVideoPostEvent.errorProcessingVideo) {
Snackbar.make(coordinatorLayout, R.string.error_processing_video, Snackbar.LENGTH_SHORT).show();
} else {
if (submitVideoPostEvent.errorMessage == null || submitVideoPostEvent.errorMessage.equals("")) {

View File

@ -63,22 +63,23 @@ public class RulesActivity extends AppCompatActivity {
static final String EXTRA_SUBREDDIT_NAME = "ESN";
@BindView(R.id.appbar_layout_rules_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_rules_activity) Toolbar toolbar;
@BindView(R.id.progress_bar_rules_activity) ProgressBar progressBar;
@BindView(R.id.recycler_view_rules_activity) RecyclerView recyclerView;
@BindView(R.id.error_text_view_rules_activity) TextView errorTextView;
private String mSubredditName;
private RulesRecyclerViewAdapter mAdapter;
@BindView(R.id.appbar_layout_rules_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_rules_activity)
Toolbar toolbar;
@BindView(R.id.progress_bar_rules_activity)
ProgressBar progressBar;
@BindView(R.id.recycler_view_rules_activity)
RecyclerView recyclerView;
@BindView(R.id.error_text_view_rules_activity)
TextView errorTextView;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
SharedPreferences mSharedPreferences;
private String mSubredditName;
private RulesRecyclerViewAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -104,29 +105,29 @@ public class RulesActivity extends AppCompatActivity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Resources resources = getResources();
if(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
View decorView = window.getDecorView();
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if(state == State.COLLAPSED) {
if(finalLightNavBar) {
if (state == State.COLLAPSED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if(state == State.EXPANDED) {
if(finalLightNavBar) {
} else if (state == State.EXPANDED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -159,7 +160,7 @@ public class RulesActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -188,15 +189,16 @@ public class RulesActivity extends AppCompatActivity {
rulesCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
new ParseRulesAsyncTask(response.body(), new ParseRulesAsyncTask.ParseRulesAsyncTaskListener() {
@Override
public void parseSuccessful(ArrayList<Rule> rules) {
progressBar.setVisibility(View.GONE);
if(rules == null || rules.size() == 0) {
if (rules == null || rules.size() == 0) {
errorTextView.setVisibility(View.VISIBLE);
errorTextView.setText(R.string.no_rule);
errorTextView.setOnClickListener(view -> {});
errorTextView.setOnClickListener(view -> {
});
}
mAdapter.changeDataset(rules);
}
@ -227,7 +229,7 @@ public class RulesActivity extends AppCompatActivity {
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
@ -250,11 +252,6 @@ public class RulesActivity extends AppCompatActivity {
private String response;
private ParseRulesAsyncTaskListener parseRulesAsyncTaskListener;
interface ParseRulesAsyncTaskListener {
void parseSuccessful(ArrayList<Rule> rules);
void parseFailed();
}
ParseRulesAsyncTask(String response, ParseRulesAsyncTaskListener parseRulesAsyncTaskListener) {
this.response = response;
this.parseRulesAsyncTaskListener = parseRulesAsyncTaskListener;
@ -265,10 +262,10 @@ public class RulesActivity extends AppCompatActivity {
try {
JSONArray rulesArray = new JSONObject(response).getJSONArray(JSONUtils.RULES_KEY);
ArrayList<Rule> rules = new ArrayList<>();
for(int i = 0; i < rulesArray.length(); i++) {
for (int i = 0; i < rulesArray.length(); i++) {
String shortName = rulesArray.getJSONObject(i).getString(JSONUtils.SHORT_NAME_KEY);
String description = null;
if(rulesArray.getJSONObject(i).has(JSONUtils.DESCRIPTION_KEY)) {
if (rulesArray.getJSONObject(i).has(JSONUtils.DESCRIPTION_KEY)) {
description = Utils.addSubredditAndUserLink(rulesArray.getJSONObject(i).getString(JSONUtils.DESCRIPTION_KEY));
}
rules.add(new Rule(shortName, description));
@ -282,11 +279,17 @@ public class RulesActivity extends AppCompatActivity {
@Override
protected void onPostExecute(ArrayList<Rule> rules) {
if(rules != null) {
if (rules != null) {
parseRulesAsyncTaskListener.parseSuccessful(rules);
} else {
parseRulesAsyncTaskListener.parseFailed();
}
}
interface ParseRulesAsyncTaskListener {
void parseSuccessful(ArrayList<Rule> rules);
void parseFailed();
}
}
}

View File

@ -32,11 +32,11 @@ import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
@ -59,18 +59,20 @@ public class SearchActivity extends AppCompatActivity {
private static final int SUBREDDIT_SELECTION_REQUEST_CODE = 0;
private static final int SUBREDDIT_SEARCH_REQUEST_CODE = 1;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.search_view_search_activity) SimpleSearchView simpleSearchView;
@BindView(R.id.subreddit_name_relative_layout_search_activity) RelativeLayout subredditNameRelativeLayout;
@BindView(R.id.subreddit_name_text_view_search_activity) TextView subredditNameTextView;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.search_view_search_activity)
SimpleSearchView simpleSearchView;
@BindView(R.id.subreddit_name_relative_layout_search_activity)
RelativeLayout subredditNameRelativeLayout;
@BindView(R.id.subreddit_name_text_view_search_activity)
TextView subredditNameTextView;
@Inject
SharedPreferences mSharedPreferences;
private String query;
private String subredditName;
private boolean subredditIsUser;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -92,9 +94,9 @@ public class SearchActivity extends AppCompatActivity {
EventBus.getDefault().register(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -110,7 +112,7 @@ public class SearchActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -147,15 +149,15 @@ public class SearchActivity extends AppCompatActivity {
simpleSearchView.setOnQueryTextListener(new SimpleSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if(searchOnlySubreddits) {
if (searchOnlySubreddits) {
Intent intent = new Intent(SearchActivity.this, SearchSubredditsResultActivity.class);
intent.putExtra(SearchSubredditsResultActivity.EXTRA_QUERY, query);
startActivityForResult(intent, SUBREDDIT_SEARCH_REQUEST_CODE);
} else {
Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
intent.putExtra(SearchResultActivity.EXTRA_QUERY, query);
if(subredditName != null) {
if(subredditIsUser) {
if (subredditName != null) {
if (subredditIsUser) {
intent.putExtra(SearchResultActivity.EXTRA_SUBREDDIT_NAME, "u_" + subredditName);
} else {
intent.putExtra(SearchResultActivity.EXTRA_SUBREDDIT_NAME, subredditName);
@ -178,11 +180,11 @@ public class SearchActivity extends AppCompatActivity {
}
});
if(savedInstanceState != null) {
if (savedInstanceState != null) {
subredditName = savedInstanceState.getString(SUBREDDIT_NAME_STATE);
subredditIsUser = savedInstanceState.getBoolean(SUBREDDIT_IS_USER_STATE);
if(subredditName == null) {
if (subredditName == null) {
subredditNameTextView.setText(R.string.all_subreddits);
} else {
subredditNameTextView.setText(subredditName);
@ -191,7 +193,7 @@ public class SearchActivity extends AppCompatActivity {
query = getIntent().getStringExtra(EXTRA_QUERY);
}
if(searchOnlySubreddits) {
if (searchOnlySubreddits) {
subredditNameRelativeLayout.setVisibility(View.GONE);
} else {
subredditNameRelativeLayout.setOnClickListener(view -> {
@ -202,7 +204,7 @@ public class SearchActivity extends AppCompatActivity {
}
Intent intent = getIntent();
if(intent.hasExtra(EXTRA_SUBREDDIT_NAME)) {
if (intent.hasExtra(EXTRA_SUBREDDIT_NAME)) {
subredditName = intent.getExtras().getString(EXTRA_SUBREDDIT_NAME);
subredditNameTextView.setText(subredditName);
subredditIsUser = intent.getExtras().getBoolean(EXTRA_SUBREDDIT_IS_USER);
@ -215,14 +217,14 @@ public class SearchActivity extends AppCompatActivity {
simpleSearchView.showSearch(false);
simpleSearchView.getSearchEditText().requestFocus();
if(query != null) {
if (query != null) {
simpleSearchView.getSearchEditText().setText(query);
simpleSearchView.getSearchEditText().setSelection(query.length());
query = null;
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
@ -230,8 +232,8 @@ public class SearchActivity extends AppCompatActivity {
@Override
protected void onPause() {
super.onPause();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(simpleSearchView.getSearchEditText().getWindowToken(), 0);
}
}
@ -242,19 +244,19 @@ public class SearchActivity extends AppCompatActivity {
return;
}
if(requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if (requestCode == SUBREDDIT_SELECTION_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
subredditName = data.getExtras().getString(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_NAME);
subredditIsUser = data.getExtras().getBoolean(SubredditSelectionActivity.EXTRA_RETURN_SUBREDDIT_IS_USER);
if(subredditName == null) {
if (subredditName == null) {
subredditNameTextView.setText(R.string.all_subreddits);
} else {
subredditNameTextView.setText(subredditName);
}
}
} else if(requestCode == SUBREDDIT_SEARCH_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
} else if (requestCode == SUBREDDIT_SEARCH_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String name = data.getExtras().getString(SearchSubredditsResultActivity.EXTRA_RETURN_SUBREDDIT_NAME);
String iconUrl = data.getExtras().getString(SearchSubredditsResultActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL);
Intent returnIntent = new Intent();
@ -277,7 +279,7 @@ public class SearchActivity extends AppCompatActivity {
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}

View File

@ -33,23 +33,23 @@ import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.Fragment.SearchPostSortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.Fragment.SearchUserAndSubredditSortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Fragment.SubredditListingFragment;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import ml.docilealligator.infinityforreddit.Fragment.UserListingFragment;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
@ -64,29 +64,27 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos
private static final String NULL_ACCESS_TOKEN_STATE = "NATS";
private static final String ACCESS_TOKEN_STATE = "ATS";
private static final String ACCOUNT_NAME_STATE = "ANS";
@BindView(R.id.appbar_layout_search_result_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_search_result_activity)
Toolbar toolbar;
@BindView(R.id.tab_layout_search_result_activity)
TabLayout tabLayout;
@BindView(R.id.view_pager_search_result_activity)
ViewPager viewPager;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
private String mQuery;
private String mSubredditName;
@BindView(R.id.appbar_layout_search_result_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_search_result_activity) Toolbar toolbar;
@BindView(R.id.tab_layout_search_result_activity) TabLayout tabLayout;
@BindView(R.id.view_pager_search_result_activity) ViewPager viewPager;
private SectionsPagerAdapter sectionsPagerAdapter;
private SearchPostSortTypeBottomSheetFragment searchPostSortTypeBottomSheetFragment;
private SearchUserAndSubredditSortTypeBottomSheetFragment searchUserAndSubredditSortTypeBottomSheetFragment;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -111,12 +109,12 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Resources resources = getResources();
if(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
@ -125,12 +123,12 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if(state == State.COLLAPSED) {
if(finalLightNavBar) {
if (state == State.COLLAPSED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if(state == State.EXPANDED) {
if(finalLightNavBar) {
} else if (state == State.EXPANDED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -156,7 +154,7 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -167,13 +165,13 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(savedInstanceState == null) {
if (savedInstanceState == null) {
getCurrentAccountAndInitializeViewPager();
} else {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndInitializeViewPager();
} else {
initializeViewPager();
@ -192,7 +190,7 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos
mSubredditName = intent.getStringExtra(EXTRA_SUBREDDIT_NAME);
if(query != null) {
if (query != null) {
mQuery = query;
setTitle(query);
}
@ -200,7 +198,7 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos
private void getCurrentAccountAndInitializeViewPager() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -404,7 +402,7 @@ public class SearchResultActivity extends AppCompatActivity implements SearchPos
}
public void changeNSFW(boolean nsfw) {
if(postFragment != null) {
if (postFragment != null) {
postFragment.changeNSFW(nsfw);
}
}

View File

@ -29,15 +29,15 @@ import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Fragment.SubredditListingFragment;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.Fragment.SubredditListingFragment;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
@ -56,21 +56,19 @@ public class SearchSubredditsResultActivity extends AppCompatActivity {
private static final String ACCOUNT_NAME_STATE = "ANS";
private static final String FRAGMENT_OUT_STATE = "FOS";
@BindView(R.id.appbar_layout_search_subreddits_result_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_search_subreddits_result_activity) Toolbar toolbar;
@BindView(R.id.appbar_layout_search_subreddits_result_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_search_subreddits_result_activity)
Toolbar toolbar;
Fragment mFragment;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
Fragment mFragment;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -95,12 +93,12 @@ public class SearchSubredditsResultActivity extends AppCompatActivity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Resources resources = getResources();
if(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
@ -109,12 +107,12 @@ public class SearchSubredditsResultActivity extends AppCompatActivity {
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if(state == State.COLLAPSED) {
if(finalLightNavBar) {
if (state == State.COLLAPSED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if(state == State.EXPANDED) {
if(finalLightNavBar) {
} else if (state == State.EXPANDED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -140,7 +138,7 @@ public class SearchSubredditsResultActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -153,13 +151,13 @@ public class SearchSubredditsResultActivity extends AppCompatActivity {
String query = getIntent().getExtras().getString(EXTRA_QUERY);
if(savedInstanceState == null) {
if (savedInstanceState == null) {
getCurrentAccountAndInitializeFragment(query);
} else {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndInitializeFragment(query);
} else {
mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE);
@ -170,7 +168,7 @@ public class SearchSubredditsResultActivity extends AppCompatActivity {
private void getCurrentAccountAndInitializeFragment(String query) {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -198,7 +196,7 @@ public class SearchSubredditsResultActivity extends AppCompatActivity {
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}

View File

@ -19,14 +19,14 @@ import androidx.preference.PreferenceFragmentCompat;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.Settings.AboutPreferenceFragment;
import ml.docilealligator.infinityforreddit.Settings.MainPreferenceFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
@ -40,7 +40,8 @@ public class SettingsActivity extends AppCompatActivity implements
private static final String TITLE_STATE = "TS";
@BindView(R.id.toolbar_settings_activity) Toolbar toolbar;
@BindView(R.id.toolbar_settings_activity)
Toolbar toolbar;
@Inject
SharedPreferences mSharedPreferences;
@ -64,9 +65,9 @@ public class SettingsActivity extends AppCompatActivity implements
ButterKnife.bind(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Window window = getWindow();
if((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
window.setNavigationBarColor(ContextCompat.getColor(this, R.color.navBarColor));
@ -82,7 +83,7 @@ public class SettingsActivity extends AppCompatActivity implements
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -113,7 +114,7 @@ public class SettingsActivity extends AppCompatActivity implements
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}

View File

@ -8,10 +8,6 @@ import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import ml.docilealligator.infinityforreddit.Activity.PostImageActivity;
import ml.docilealligator.infinityforreddit.Activity.PostLinkActivity;
import ml.docilealligator.infinityforreddit.Activity.PostTextActivity;
import ml.docilealligator.infinityforreddit.Activity.PostVideoActivity;
import ml.docilealligator.infinityforreddit.R;
public class ShareDataResolverActivity extends AppCompatActivity {
@ -24,11 +20,11 @@ public class ShareDataResolverActivity extends AppCompatActivity {
String action = receivedIntent.getAction();
String type = receivedIntent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null) {
if("text/plain".equals(type)) {
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
String text = receivedIntent.getStringExtra(Intent.EXTRA_TEXT);
if(text != null) {
if(Patterns.WEB_URL.matcher(text).matches()) {
if (text != null) {
if (Patterns.WEB_URL.matcher(text).matches()) {
//It's a link
Intent intent = new Intent(this, PostLinkActivity.class);
intent.putExtra(PostLinkActivity.EXTRA_LINK, text);
@ -41,9 +37,9 @@ public class ShareDataResolverActivity extends AppCompatActivity {
} else {
Toast.makeText(this, R.string.no_data_received, Toast.LENGTH_SHORT).show();
}
} else if(type.equals("image/gif")) {
} else if (type.equals("image/gif")) {
Uri videoUri = receivedIntent.getParcelableExtra(Intent.EXTRA_STREAM);
if(videoUri != null) {
if (videoUri != null) {
Intent intent = new Intent(this, PostVideoActivity.class);
intent.setData(videoUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
@ -51,9 +47,9 @@ public class ShareDataResolverActivity extends AppCompatActivity {
} else {
Toast.makeText(this, R.string.no_video_path_received, Toast.LENGTH_SHORT).show();
}
} else if(type.startsWith("image/")) {
} else if (type.startsWith("image/")) {
Uri imageUri = receivedIntent.getParcelableExtra(Intent.EXTRA_STREAM);
if(imageUri != null) {
if (imageUri != null) {
Intent intent = new Intent(this, PostImageActivity.class);
intent.setData(imageUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
@ -61,9 +57,9 @@ public class ShareDataResolverActivity extends AppCompatActivity {
} else {
Toast.makeText(this, R.string.no_image_path_received, Toast.LENGTH_SHORT).show();
}
} else if(type.startsWith("video/")) {
} else if (type.startsWith("video/")) {
Uri videoUri = receivedIntent.getParcelableExtra(Intent.EXTRA_STREAM);
if(videoUri != null) {
if (videoUri != null) {
Intent intent = new Intent(this, PostVideoActivity.class);
intent.setData(videoUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

View File

@ -71,27 +71,24 @@ public class SubredditSelectionActivity extends AppCompatActivity {
private static final String ACCOUNT_PROFILE_IMAGE_URL = "APIU";
private static final String FRAGMENT_OUT_STATE = "FOS";
@BindView(R.id.appbar_layout_subreddit_selection_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_subreddit_selection_activity) Toolbar toolbar;
@BindView(R.id.appbar_layout_subreddit_selection_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_subreddit_selection_activity)
Toolbar toolbar;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
private String mAccountProfileImageUrl;
private boolean mInsertSuccess = false;
private Fragment mFragment;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -116,29 +113,29 @@ public class SubredditSelectionActivity extends AppCompatActivity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Resources resources = getResources();
if(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
View decorView = window.getDecorView();
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if(state == State.COLLAPSED) {
if(finalLightNavBar) {
if (state == State.COLLAPSED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if(state == State.EXPANDED) {
if(finalLightNavBar) {
} else if (state == State.EXPANDED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -164,7 +161,7 @@ public class SubredditSelectionActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -175,7 +172,7 @@ public class SubredditSelectionActivity extends AppCompatActivity {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(savedInstanceState == null) {
if (savedInstanceState == null) {
getCurrentAccountAndBindView();
} else {
mInsertSuccess = savedInstanceState.getBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE);
@ -184,7 +181,7 @@ public class SubredditSelectionActivity extends AppCompatActivity {
mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE);
mAccountProfileImageUrl = savedInstanceState.getString(ACCOUNT_PROFILE_IMAGE_URL);
if(!mNullAccessToken && mAccountName == null) {
if (!mNullAccessToken && mAccountName == null) {
getCurrentAccountAndBindView();
} else {
mFragment = getSupportFragmentManager().getFragment(savedInstanceState, FRAGMENT_OUT_STATE);
@ -195,7 +192,7 @@ public class SubredditSelectionActivity extends AppCompatActivity {
private void getCurrentAccountAndBindView() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -214,7 +211,7 @@ public class SubredditSelectionActivity extends AppCompatActivity {
bundle.putString(SubscribedSubredditsListingFragment.EXTRA_ACCOUNT_NAME, mAccountName);
bundle.putString(SubscribedSubredditsListingFragment.EXTRA_ACCOUNT_PROFILE_IMAGE_URL, mAccountProfileImageUrl);
bundle.putBoolean(SubscribedSubredditsListingFragment.EXTRA_IS_SUBREDDIT_SELECTION, true);
if(getIntent().hasExtra(EXTRA_EXTRA_CLEAR_SELECTION)) {
if (getIntent().hasExtra(EXTRA_EXTRA_CLEAR_SELECTION)) {
bundle.putBoolean(SubscribedSubredditsListingFragment.EXTRA_EXTRA_CLEAR_SELECTION,
getIntent().getExtras().getBoolean(EXTRA_EXTRA_CLEAR_SELECTION));
}
@ -282,8 +279,8 @@ public class SubredditSelectionActivity extends AppCompatActivity {
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode == SUBREDDIT_SEARCH_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
if (requestCode == SUBREDDIT_SEARCH_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String name = data.getStringExtra(SearchActivity.EXTRA_RETURN_SUBREDDIT_NAME);
String iconUrl = data.getStringExtra(SearchActivity.EXTRA_RETURN_SUBREDDIT_ICON_URL);
Intent returnIntent = new Intent();

View File

@ -64,28 +64,27 @@ public class SubscribedThingListingActivity extends AppCompatActivity {
private static final String ACCESS_TOKEN_STATE = "ATS";
private static final String ACCOUNT_NAME_STATE = "ANS";
@BindView(R.id.appbar_layout_subscribed_thing_listing_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_subscribed_thing_listing_activity) Toolbar toolbar;
@BindView(R.id.tab_layout_subscribed_thing_listing_activity) TabLayout tabLayout;
@BindView(R.id.view_pager_subscribed_thing_listing_activity) ViewPager viewPager;
@BindView(R.id.appbar_layout_subscribed_thing_listing_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_subscribed_thing_listing_activity)
Toolbar toolbar;
@BindView(R.id.tab_layout_subscribed_thing_listing_activity)
TabLayout tabLayout;
@BindView(R.id.view_pager_subscribed_thing_listing_activity)
ViewPager viewPager;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
private boolean mInsertSuccess = false;
private SectionsPagerAdapter sectionsPagerAdapter;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -110,29 +109,29 @@ public class SubscribedThingListingActivity extends AppCompatActivity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Resources resources = getResources();
if(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
View decorView = window.getDecorView();
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if(state == State.COLLAPSED) {
if(finalLightNavBar) {
if (state == State.COLLAPSED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if(state == State.EXPANDED) {
if(finalLightNavBar) {
} else if (state == State.EXPANDED) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -158,7 +157,7 @@ public class SubscribedThingListingActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -169,12 +168,12 @@ public class SubscribedThingListingActivity extends AppCompatActivity {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(savedInstanceState != null) {
if (savedInstanceState != null) {
mInsertSuccess = savedInstanceState.getBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE);
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
mAccountName = savedInstanceState.getString(ACCOUNT_NAME_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndInitializeViewPager();
} else {
initializeViewPagerAndLoadSubscriptions();
@ -186,7 +185,7 @@ public class SubscribedThingListingActivity extends AppCompatActivity {
private void getCurrentAccountAndInitializeViewPager() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -207,7 +206,7 @@ public class SubscribedThingListingActivity extends AppCompatActivity {
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
@ -280,8 +279,7 @@ public class SubscribedThingListingActivity extends AppCompatActivity {
fragment.setArguments(bundle);
return fragment;
}
default:
{
default: {
FollowedUsersListingFragment fragment = new FollowedUsersListingFragment();
Bundle bundle = new Bundle();
bundle.putString(FollowedUsersListingFragment.EXTRA_ACCOUNT_NAME, mAccountName);

View File

@ -59,35 +59,31 @@ import ml.docilealligator.infinityforreddit.TitleFontStyle;
public class ViewImageActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
public static final String TITLE_KEY = "TK";
public static final String IMAGE_URL_KEY = "IUK";
public static final String FILE_NAME_KEY = "FNK";
@BindView(R.id.parent_relative_layout_view_image_activity) RelativeLayout mRelativeLayout;
@BindView(R.id.progress_bar_view_image_activity) ProgressBar mProgressBar;
@BindView(R.id.image_view_view_image_activity) GestureImageView mImageView;
@BindView(R.id.load_image_error_linear_layout_view_image_activity) LinearLayout mLoadErrorLinearLayout;
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
@BindView(R.id.parent_relative_layout_view_image_activity)
RelativeLayout mRelativeLayout;
@BindView(R.id.progress_bar_view_image_activity)
ProgressBar mProgressBar;
@BindView(R.id.image_view_view_image_activity)
GestureImageView mImageView;
@BindView(R.id.load_image_error_linear_layout_view_image_activity)
LinearLayout mLoadErrorLinearLayout;
@Inject
SharedPreferences mSharedPreferences;
private boolean isActionBarHidden = false;
private boolean isDownloading = false;
private Menu mMenu;
private Swipe swipe;
private String mImageUrl;
private String mImageFileName;
private float totalLengthY = 0.0f;
private float touchY = -1.0f;
private float zoom = 1.0f;
private boolean isSwiping = false;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -118,7 +114,7 @@ public class ViewImageActivity extends AppCompatActivity {
mImageFileName = intent.getStringExtra(FILE_NAME_KEY) + ".jpg";
mLoadErrorLinearLayout.setOnClickListener(view -> {
if(!isSwiping) {
if (!isSwiping) {
mProgressBar.setVisibility(View.VISIBLE);
mLoadErrorLinearLayout.setVisibility(View.GONE);
loadImage();
@ -146,7 +142,7 @@ public class ViewImageActivity extends AppCompatActivity {
actionBarElementColorAnimation.addUpdateListener(valueAnimator -> {
upArrow.setColorFilter((int) valueAnimator.getAnimatedValue(), PorterDuff.Mode.SRC_IN);
if(mMenu != null) {
if (mMenu != null) {
Drawable drawable = mMenu.getItem(0).getIcon();
//drawable.mutate();
drawable.setColorFilter((int) valueAnimator.getAnimatedValue(), PorterDuff.Mode.SRC_IN);
@ -398,7 +394,7 @@ public class ViewImageActivity extends AppCompatActivity {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if(zoom == 1.0) {
if (zoom == 1.0) {
swipe.dispatchTouchEvent(ev);
}
return super.dispatchTouchEvent(ev);
@ -406,10 +402,10 @@ public class ViewImageActivity extends AppCompatActivity {
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) {
if(grantResults[0] == PackageManager.PERMISSION_DENIED) {
if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
} else if(grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) {
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) {
saveImage();
}
isDownloading = false;
@ -424,25 +420,25 @@ public class ViewImageActivity extends AppCompatActivity {
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//Android Q support
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, mImageFileName);
} else {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File directory = new File(path + "/Infinity/");
boolean saveToInfinityFolder = true;
if(!directory.exists()) {
if(!directory.mkdir()) {
if (!directory.exists()) {
if (!directory.mkdir()) {
saveToInfinityFolder = false;
}
} else {
if(directory.isFile()) {
if(!(directory.delete() && directory.mkdir())) {
if (directory.isFile()) {
if (!(directory.delete() && directory.mkdir())) {
saveToInfinityFolder = false;
}
}
}
if(saveToInfinityFolder) {
if (saveToInfinityFolder) {
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES + "/Infinity/", mImageFileName);
} else {
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, mImageFileName);
@ -451,7 +447,7 @@ public class ViewImageActivity extends AppCompatActivity {
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
if(manager == null) {
if (manager == null) {
Toast.makeText(this, R.string.download_failed, Toast.LENGTH_SHORT).show();
return;
}

View File

@ -39,20 +39,20 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.Adapter.MessageRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchAccountAsyncTask;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FetchMessages;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.Adapter.MessageRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.MessageViewModel;
import ml.docilealligator.infinityforreddit.NetworkState;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import retrofit2.Retrofit;
@ -69,34 +69,35 @@ public class ViewMessageActivity extends AppCompatActivity {
private static final String ACCESS_TOKEN_STATE = "ATS";
private static final String NEW_ACCOUNT_NAME_STATE = "NANS";
@BindView(R.id.collapsing_toolbar_layout_view_message_activity) CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.appbar_layout_view_message_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_view_message_activity) Toolbar toolbar;
@BindView(R.id.progress_bar_view_message_activity) CircleProgressBar mProgressBar;
@BindView(R.id.recycler_view_view_message_activity) RecyclerView recyclerView;
@BindView(R.id.fetch_messages_info_linear_layout_view_message_activity) LinearLayout mFetchMessageInfoLinearLayout;
@BindView(R.id.fetch_messages_info_image_view_view_message_activity) ImageView mFetchMessageInfoImageView;
@BindView(R.id.fetch_messages_info_text_view_view_message_activity) TextView mFetchMessageInfoTextView;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mNewAccountName;
private MessageRecyclerViewAdapter mAdapter;
private RequestManager mGlide;
@BindView(R.id.collapsing_toolbar_layout_view_message_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.appbar_layout_view_message_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_view_message_activity)
Toolbar toolbar;
@BindView(R.id.progress_bar_view_message_activity)
CircleProgressBar mProgressBar;
@BindView(R.id.recycler_view_view_message_activity)
RecyclerView recyclerView;
@BindView(R.id.fetch_messages_info_linear_layout_view_message_activity)
LinearLayout mFetchMessageInfoLinearLayout;
@BindView(R.id.fetch_messages_info_image_view_view_message_activity)
ImageView mFetchMessageInfoImageView;
@BindView(R.id.fetch_messages_info_text_view_view_message_activity)
TextView mFetchMessageInfoTextView;
MessageViewModel mMessageViewModel;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mNewAccountName;
private MessageRecyclerViewAdapter mAdapter;
private RequestManager mGlide;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -130,24 +131,24 @@ public class ViewMessageActivity extends AppCompatActivity {
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
View decorView = window.getDecorView();
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if (state == State.COLLAPSED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if (state == State.EXPANDED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -177,7 +178,7 @@ public class ViewMessageActivity extends AppCompatActivity {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -188,12 +189,12 @@ public class ViewMessageActivity extends AppCompatActivity {
toolbar.setTitle(R.string.inbox);
setSupportActionBar(toolbar);
if(savedInstanceState != null) {
if (savedInstanceState != null) {
mNullAccessToken = savedInstanceState.getBoolean(NULL_ACCESS_TOKEN_STATE);
mAccessToken = savedInstanceState.getString(ACCESS_TOKEN_STATE);
mNewAccountName = savedInstanceState.getString(NEW_ACCOUNT_NAME_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndFetchMessage();
} else {
bindView();
@ -206,14 +207,14 @@ public class ViewMessageActivity extends AppCompatActivity {
private void getCurrentAccountAndFetchMessage() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(mNewAccountName != null) {
if(account == null || !account.getUsername().equals(mNewAccountName)) {
if (mNewAccountName != null) {
if (account == null || !account.getUsername().equals(mNewAccountName)) {
new SwitchAccountAsyncTask(mRedditDataRoomDatabase, mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
mNewAccountName = null;
if(newAccount == null) {
if (newAccount == null) {
mNullAccessToken = true;
} else {
mAccessToken = newAccount.getAccessToken();
@ -226,7 +227,7 @@ public class ViewMessageActivity extends AppCompatActivity {
bindView();
}
} else {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -253,7 +254,7 @@ public class ViewMessageActivity extends AppCompatActivity {
mMessageViewModel.hasMessage().observe(this, hasMessage -> {
mProgressBar.setVisibility(View.GONE);
if(hasMessage) {
if (hasMessage) {
mFetchMessageInfoLinearLayout.setVisibility(View.GONE);
} else {
mFetchMessageInfoLinearLayout.setOnClickListener(view -> {
@ -264,9 +265,9 @@ public class ViewMessageActivity extends AppCompatActivity {
});
mMessageViewModel.getInitialLoadingState().observe(this, networkState -> {
if(networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
if (networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
mProgressBar.setVisibility(View.GONE);
} else if(networkState.getStatus().equals(NetworkState.Status.FAILED)) {
} else if (networkState.getStatus().equals(NetworkState.Status.FAILED)) {
mProgressBar.setVisibility(View.GONE);
mFetchMessageInfoLinearLayout.setOnClickListener(view -> {
mFetchMessageInfoLinearLayout.setVisibility(View.GONE);
@ -299,11 +300,11 @@ public class ViewMessageActivity extends AppCompatActivity {
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId() == R.id.action_refresh_view_message_activity) {
if (item.getItemId() == R.id.action_refresh_view_message_activity) {
mMessageViewModel.refresh();
mAdapter.setNetworkState(null);
return true;
} else if(item.getItemId() == android.R.id.home) {
} else if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
@ -326,7 +327,7 @@ public class ViewMessageActivity extends AppCompatActivity {
@Subscribe
public void onAccountSwitchEvent(SwitchAccountEvent event) {
if(!getClass().getName().equals(event.excludeActivityClassName)) {
if (!getClass().getName().equals(event.excludeActivityClassName)) {
finish();
}
}

View File

@ -48,26 +48,28 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWBlurEvent;
import ml.docilealligator.infinityforreddit.Event.ChangeSpoilerBlurEvent;
import ml.docilealligator.infinityforreddit.Adapter.CommentAndPostRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchAccountAsyncTask;
import ml.docilealligator.infinityforreddit.CommentData;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.DeleteThing;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWBlurEvent;
import ml.docilealligator.infinityforreddit.Event.ChangeSpoilerBlurEvent;
import ml.docilealligator.infinityforreddit.Event.PostUpdateEventToDetailActivity;
import ml.docilealligator.infinityforreddit.Event.PostUpdateEventToPostList;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FetchComment;
import ml.docilealligator.infinityforreddit.FetchPost;
import ml.docilealligator.infinityforreddit.Flair;
import ml.docilealligator.infinityforreddit.Fragment.FlairBottomSheetFragment;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Fragment.FlairBottomSheetFragment;
import ml.docilealligator.infinityforreddit.HidePost;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.ParseComment;
import ml.docilealligator.infinityforreddit.ParsePost;
import ml.docilealligator.infinityforreddit.Post;
import ml.docilealligator.infinityforreddit.Event.PostUpdateEventToDetailActivity;
import ml.docilealligator.infinityforreddit.Event.PostUpdateEventToPostList;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.ReadMessage;
import ml.docilealligator.infinityforreddit.RedditAPI;
@ -75,8 +77,6 @@ import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.RedditUtils;
import ml.docilealligator.infinityforreddit.SaveThing;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import retrofit2.Call;
import retrofit2.Callback;
@ -98,20 +98,8 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
public static final String EXTRA_SINGLE_COMMENT_ID = "ESCI";
public static final String EXTRA_MESSAGE_FULLNAME = "ENI";
public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN";
private static final int EDIT_POST_REQUEST_CODE = 2;
public static final int EDIT_COMMENT_REQUEST_CODE = 3;
private RequestManager mGlide;
private Locale mLocale;
private Menu mMenu;
private int orientation;
private int postListPosition = -1;
private String mSingleCommentId;
private boolean mNeedBlurNsfw;
private boolean mNeedBlurSpoiler;
private static final int EDIT_POST_REQUEST_CODE = 2;
@State
boolean mNullAccessToken = false;
@State
@ -140,32 +128,43 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
String mMessageFullname;
@State
String mNewAccountName;
private boolean showToast = false;
private LinearLayoutManager mLinearLayoutManager;
private CommentAndPostRecyclerViewAdapter mAdapter;
@BindView(R.id.coordinator_layout_view_post_detail) CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.appbar_layout_view_post_detail_activity) AppBarLayout appBarLayout;
@BindView(R.id.toolbar_view_post_detail_activity) Toolbar toolbar;
@BindView(R.id.progress_bar_view_post_detail_activity) ProgressBar mProgressBar;
@BindView(R.id.recycler_view_view_post_detail) RecyclerView mRecyclerView;
@BindView(R.id.fetch_post_info_linear_layout_view_post_detail_activity) LinearLayout mFetchPostInfoLinearLayout;
@BindView(R.id.fetch_post_info_image_view_view_post_detail_activity) ImageView mFetchPostInfoImageView;
@BindView(R.id.fetch_post_info_text_view_view_post_detail_activity) TextView mFetchPostInfoTextView;
@Inject @Named("no_oauth")
@BindView(R.id.coordinator_layout_view_post_detail)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.appbar_layout_view_post_detail_activity)
AppBarLayout appBarLayout;
@BindView(R.id.toolbar_view_post_detail_activity)
Toolbar toolbar;
@BindView(R.id.progress_bar_view_post_detail_activity)
ProgressBar mProgressBar;
@BindView(R.id.recycler_view_view_post_detail)
RecyclerView mRecyclerView;
@BindView(R.id.fetch_post_info_linear_layout_view_post_detail_activity)
LinearLayout mFetchPostInfoLinearLayout;
@BindView(R.id.fetch_post_info_image_view_view_post_detail_activity)
ImageView mFetchPostInfoImageView;
@BindView(R.id.fetch_post_info_text_view_view_post_detail_activity)
TextView mFetchPostInfoTextView;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject @Named("oauth")
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private RequestManager mGlide;
private Locale mLocale;
private Menu mMenu;
private int orientation;
private int postListPosition = -1;
private String mSingleCommentId;
private boolean mNeedBlurNsfw;
private boolean mNeedBlurSpoiler;
private boolean showToast = false;
private LinearLayoutManager mLinearLayoutManager;
private CommentAndPostRecyclerViewAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -199,24 +198,24 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
View decorView = window.getDecorView();
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if (state == State.COLLAPSED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if (state == State.EXPANDED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -247,7 +246,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -268,8 +267,8 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mSingleCommentId = getIntent().hasExtra(EXTRA_SINGLE_COMMENT_ID) ? getIntent().getExtras().getString(EXTRA_SINGLE_COMMENT_ID) : null;
if(savedInstanceState == null) {
if(mSingleCommentId != null) {
if (savedInstanceState == null) {
if (mSingleCommentId != null) {
isSingleCommentThreadMode = true;
}
mMessageFullname = getIntent().getStringExtra(EXTRA_MESSAGE_FULLNAME);
@ -278,27 +277,27 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
orientation = getResources().getConfiguration().orientation;
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndBindView();
} else {
bindView();
}
if(getIntent().hasExtra(EXTRA_POST_LIST_POSITION)) {
if (getIntent().hasExtra(EXTRA_POST_LIST_POSITION)) {
postListPosition = getIntent().getIntExtra(EXTRA_POST_LIST_POSITION, -1);
}
}
private void getCurrentAccountAndBindView() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(mNewAccountName != null) {
if(account == null || !account.getUsername().equals(mNewAccountName)) {
if (mNewAccountName != null) {
if (account == null || !account.getUsername().equals(mNewAccountName)) {
new SwitchAccountAsyncTask(mRedditDataRoomDatabase, mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
mNewAccountName = null;
if(newAccount == null) {
if (newAccount == null) {
mNullAccessToken = true;
} else {
mAccessToken = newAccount.getAccessToken();
@ -313,7 +312,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
bindView();
}
} else {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -326,7 +325,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
}
private void bindView() {
if(mAccessToken != null && mMessageFullname != null) {
if (mAccessToken != null && mMessageFullname != null) {
ReadMessage.readMessage(mOauthRetrofit, mAccessToken, mMessageFullname, new ReadMessage.ReadMessageListener() {
@Override
public void readSuccess() {
@ -340,21 +339,21 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
});
}
if(mPost == null) {
if (mPost == null) {
mPost = getIntent().getParcelableExtra(EXTRA_POST_DATA);
}
if(mPost == null) {
if (mPost == null) {
fetchPostAndCommentsById(getIntent().getStringExtra(EXTRA_POST_ID));
} else {
if(mMenu != null) {
if (mMenu != null) {
MenuItem saveItem = mMenu.findItem(R.id.action_save_view_post_detail_activity);
MenuItem hideItem = mMenu.findItem(R.id.action_hide_view_post_detail_activity);
mMenu.findItem(R.id.action_comment_view_post_detail_activity).setVisible(true);
if(mAccessToken != null) {
if(mPost.isSaved()) {
if (mAccessToken != null) {
if (mPost.isSaved()) {
saveItem.setVisible(true);
saveItem.setIcon(R.drawable.ic_baseline_bookmark_24px);
} else {
@ -362,7 +361,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
saveItem.setIcon(R.drawable.ic_baseline_bookmark_border_24px);
}
if(mPost.isHidden()) {
if (mPost.isHidden()) {
hideItem.setVisible(true);
hideItem.setTitle(R.string.action_unhide_post);
} else {
@ -374,15 +373,15 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
hideItem.setVisible(false);
}
if(mPost.getAuthor().equals(mAccountName)) {
if(mPost.getPostType() == Post.TEXT_TYPE) {
if (mPost.getAuthor().equals(mAccountName)) {
if (mPost.getPostType() == Post.TEXT_TYPE) {
mMenu.findItem(R.id.action_edit_view_post_detail_activity).setVisible(true);
}
mMenu.findItem(R.id.action_delete_view_post_detail_activity).setVisible(true);
MenuItem nsfwItem = mMenu.findItem(R.id.action_nsfw_view_post_detail_activity);
nsfwItem.setVisible(true);
if(mPost.isNSFW()) {
if (mPost.isNSFW()) {
nsfwItem.setTitle(R.string.action_unmark_nsfw);
} else {
nsfwItem.setTitle(R.string.action_mark_nsfw);
@ -390,7 +389,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
MenuItem spoilerItem = mMenu.findItem(R.id.action_spoiler_view_post_detail_activity);
spoilerItem.setVisible(true);
if(mPost.isSpoiler()) {
if (mPost.isSpoiler()) {
spoilerItem.setTitle(R.string.action_unmark_spoiler);
} else {
spoilerItem.setTitle(R.string.action_mark_spoiler);
@ -426,15 +425,15 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
});
mRecyclerView.setAdapter(mAdapter);
if(comments == null) {
if (comments == null) {
fetchComments(false);
} else {
if(isRefreshing) {
if (isRefreshing) {
isRefreshing = false;
refresh(true, true);
} else {
mAdapter.addComments(comments, hasMoreChildren);
if(isLoadingMoreChildren) {
if (isLoadingMoreChildren) {
isLoadingMoreChildren = false;
fetchMoreComments();
}
@ -450,14 +449,14 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
mGlide.clear(mFetchPostInfoImageView);
Call<String> postAndComments;
if(mAccessToken == null) {
if(isSingleCommentThreadMode && mSingleCommentId != null) {
if (mAccessToken == null) {
if (isSingleCommentThreadMode && mSingleCommentId != null) {
postAndComments = mRetrofit.create(RedditAPI.class).getPostAndCommentsSingleThreadById(subredditId, mSingleCommentId);
} else {
postAndComments = mRetrofit.create(RedditAPI.class).getPostAndCommentsById(subredditId);
}
} else {
if(isSingleCommentThreadMode && mSingleCommentId != null) {
if (isSingleCommentThreadMode && mSingleCommentId != null) {
postAndComments = mOauthRetrofit.create(RedditAPI.class).getPostAndCommentsSingleThreadByIdOauth(subredditId,
mSingleCommentId, RedditUtils.getOAuthHeader(mAccessToken));
} else {
@ -470,20 +469,20 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
mProgressBar.setVisibility(View.GONE);
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParsePost.parsePost(response.body(), mLocale, new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(Post post) {
mPost = post;
if(mMenu != null) {
if (mMenu != null) {
MenuItem saveItem = mMenu.findItem(R.id.action_save_view_post_detail_activity);
MenuItem hideItem = mMenu.findItem(R.id.action_hide_view_post_detail_activity);
mMenu.findItem(R.id.action_comment_view_post_detail_activity).setVisible(true);
if(mAccessToken != null) {
if(post.isSaved()) {
if (mAccessToken != null) {
if (post.isSaved()) {
saveItem.setVisible(true);
saveItem.setIcon(R.drawable.ic_baseline_bookmark_24px);
} else {
@ -491,7 +490,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
saveItem.setIcon(R.drawable.ic_baseline_bookmark_border_24px);
}
if(post.isHidden()) {
if (post.isHidden()) {
hideItem.setVisible(true);
hideItem.setTitle(R.string.action_unhide_post);
} else {
@ -503,8 +502,8 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
hideItem.setVisible(false);
}
if(mPost.getAuthor().equals(mAccountName)) {
if(mPost.getPostType() == Post.TEXT_TYPE) {
if (mPost.getAuthor().equals(mAccountName)) {
if (mPost.getPostType() == Post.TEXT_TYPE) {
mMenu.findItem(R.id.action_edit_view_post_detail_activity).setVisible(true);
}
mMenu.findItem(R.id.action_delete_view_post_detail_activity).setVisible(true);
@ -547,13 +546,13 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
hasMoreChildren = children.size() != 0;
mAdapter.addComments(expandedComments, hasMoreChildren);
if(children.size() > 0) {
if (children.size() > 0) {
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if(!isLoadingMoreChildren && loadMoreChildrenSuccess) {
if (!isLoadingMoreChildren && loadMoreChildrenSuccess) {
int visibleItemCount = mLinearLayoutManager.getChildCount();
int totalItemCount = mLinearLayoutManager.getItemCount();
int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
@ -595,56 +594,56 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
mAdapter.setSingleComment(mSingleCommentId, isSingleCommentThreadMode);
mAdapter.initiallyLoading();
String commentId = null;
if(isSingleCommentThreadMode) {
if (isSingleCommentThreadMode) {
commentId = mSingleCommentId;
}
Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit;
FetchComment.fetchComments(retrofit, mAccessToken, mPost.getId(), commentId, mLocale, new FetchComment.FetchCommentListener() {
@Override
public void onFetchCommentSuccess(ArrayList<CommentData> expandedComments,
String parentId, ArrayList<String> children) {
ViewPostDetailActivity.this.children = children;
@Override
public void onFetchCommentSuccess(ArrayList<CommentData> expandedComments,
String parentId, ArrayList<String> children) {
ViewPostDetailActivity.this.children = children;
comments = expandedComments;
hasMoreChildren = children.size() != 0;
mAdapter.addComments(expandedComments, hasMoreChildren);
comments = expandedComments;
hasMoreChildren = children.size() != 0;
mAdapter.addComments(expandedComments, hasMoreChildren);
if(children.size() > 0) {
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (children.size() > 0) {
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if(!isLoadingMoreChildren && loadMoreChildrenSuccess) {
int visibleItemCount = mLinearLayoutManager.getChildCount();
int totalItemCount = mLinearLayoutManager.getItemCount();
int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
if (!isLoadingMoreChildren && loadMoreChildrenSuccess) {
int visibleItemCount = mLinearLayoutManager.getChildCount();
int totalItemCount = mLinearLayoutManager.getItemCount();
int firstVisibleItemPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) {
fetchMoreComments();
}
}
if ((visibleItemCount + firstVisibleItemPosition >= totalItemCount) && firstVisibleItemPosition >= 0) {
fetchMoreComments();
}
});
}
}
if(changeRefreshState) {
isRefreshing = false;
}
}
});
}
if (changeRefreshState) {
isRefreshing = false;
}
}
@Override
public void onFetchCommentFailed() {
mAdapter.initiallyLoadCommentsFailed();
if(changeRefreshState) {
isRefreshing = false;
}
}
});
@Override
public void onFetchCommentFailed() {
mAdapter.initiallyLoadCommentsFailed();
if (changeRefreshState) {
isRefreshing = false;
}
}
});
}
void fetchMoreComments() {
if(isLoadingMoreChildren || !loadMoreChildrenSuccess) {
if (isLoadingMoreChildren || !loadMoreChildrenSuccess) {
return;
}
@ -672,24 +671,24 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
}
private void refresh(boolean fetchPost, boolean fetchComments) {
if(!isRefreshing) {
if (!isRefreshing) {
isRefreshing = true;
mChildrenStartingIndex = 0;
mFetchPostInfoLinearLayout.setVisibility(View.GONE);
mGlide.clear(mFetchPostInfoImageView);
if(fetchComments) {
if(!fetchPost) {
if (fetchComments) {
if (!fetchPost) {
fetchComments(true);
} else {
fetchComments(false);
}
}
if(fetchPost) {
if (fetchPost) {
Retrofit retrofit;
if(mAccessToken == null) {
if (mAccessToken == null) {
retrofit = mRetrofit;
} else {
retrofit = mOauthRetrofit;
@ -702,14 +701,14 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
mAdapter.updatePost(mPost);
EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition));
isRefreshing = false;
if(mMenu != null) {
if (mMenu != null) {
MenuItem saveItem = mMenu.findItem(R.id.action_save_view_post_detail_activity);
MenuItem hideItem = mMenu.findItem(R.id.action_hide_view_post_detail_activity);
mMenu.findItem(R.id.action_comment_view_post_detail_activity).setVisible(true);
if(mAccessToken != null) {
if(post.isSaved()) {
if (mAccessToken != null) {
if (post.isSaved()) {
saveItem.setVisible(true);
saveItem.setIcon(R.drawable.ic_baseline_bookmark_24px);
} else {
@ -717,7 +716,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
saveItem.setIcon(R.drawable.ic_baseline_bookmark_border_24px);
}
if(post.isHidden()) {
if (post.isHidden()) {
hideItem.setVisible(true);
hideItem.setTitle(R.string.action_unhide_post);
} else {
@ -752,7 +751,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
}
private void showMessage(int resId) {
if(showToast) {
if (showToast) {
Toast.makeText(ViewPostDetailActivity.this, resId, Toast.LENGTH_SHORT).show();
} else {
Snackbar.make(mCoordinatorLayout, resId, Snackbar.LENGTH_SHORT).show();
@ -760,7 +759,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
}
private void markNSFW() {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw);
}
@ -768,37 +767,37 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
params.put(RedditUtils.ID_KEY, mPost.getFullName());
mOauthRetrofit.create(RedditAPI.class).markNSFW(RedditUtils.getOAuthHeader(mAccessToken), params)
.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if(mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw);
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {
if (mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw);
}
refresh(true, false);
showMessage(R.string.mark_nsfw_success);
} else {
if (mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw);
}
showMessage(R.string.mark_nsfw_failed);
}
}
refresh(true, false);
showMessage(R.string.mark_nsfw_success);
} else {
if(mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw);
@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
if (mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw);
}
showMessage(R.string.mark_nsfw_failed);
}
showMessage(R.string.mark_nsfw_failed);
}
}
@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
if(mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw);
}
showMessage(R.string.mark_nsfw_failed);
}
});
});
}
private void unmarkNSFW() {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw);
}
@ -808,15 +807,15 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if(mMenu != null) {
if (response.isSuccessful()) {
if (mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_mark_nsfw);
}
refresh(true, false);
showMessage(R.string.unmark_nsfw_success);
} else {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw);
}
@ -826,7 +825,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_nsfw_view_post_detail_activity).setTitle(R.string.action_unmark_nsfw);
}
@ -836,7 +835,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
}
private void markSpoiler() {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_unmark_spoiler);
}
@ -846,15 +845,15 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if(mMenu != null) {
if (response.isSuccessful()) {
if (mMenu != null) {
mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_unmark_spoiler);
}
refresh(true, false);
showMessage(R.string.mark_spoiler_success);
} else {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_mark_spoiler);
}
@ -864,7 +863,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_mark_spoiler);
}
@ -874,7 +873,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
}
private void unmarkSpoiler() {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_mark_spoiler);
}
@ -884,15 +883,15 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if(mMenu != null) {
if (response.isSuccessful()) {
if (mMenu != null) {
mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_mark_spoiler);
}
refresh(true, false);
showMessage(R.string.unmark_spoiler_success);
} else {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_unmark_spoiler);
}
@ -902,7 +901,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_spoiler_view_post_detail_activity).setTitle(R.string.action_unmark_spoiler);
}
@ -940,11 +939,11 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
@Subscribe
public void onPostUpdateEvent(PostUpdateEventToDetailActivity event) {
if(mPost.getId().equals(event.post.getId())) {
if (mPost.getId().equals(event.post.getId())) {
mPost.setVoteType(event.post.getVoteType());
mPost.setSaved(event.post.isSaved());
if(mMenu != null) {
if(event.post.isSaved()) {
if (mMenu != null) {
if (event.post.isSaved()) {
mMenu.findItem(R.id.action_save_view_post_detail_activity).setIcon(getResources()
.getDrawable(R.drawable.ic_baseline_bookmark_24px));
} else {
@ -970,7 +969,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
private void refreshAdapter() {
int previousPosition = -1;
if(mLinearLayoutManager != null) {
if (mLinearLayoutManager != null) {
previousPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
}
@ -980,14 +979,14 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(layoutManager);
if(previousPosition > 0) {
if (previousPosition > 0) {
mRecyclerView.scrollToPosition(previousPosition);
}
}
@Subscribe
public void onAccountSwitchEvent(SwitchAccountEvent event) {
if(!getClass().getName().equals(event.excludeActivityClassName)) {
if (!getClass().getName().equals(event.excludeActivityClassName)) {
finish();
}
}
@ -996,14 +995,14 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.view_post_detail_activity, menu);
mMenu = menu;
if(mPost != null) {
if (mPost != null) {
MenuItem saveItem = mMenu.findItem(R.id.action_save_view_post_detail_activity);
MenuItem hideItem = mMenu.findItem(R.id.action_hide_view_post_detail_activity);
mMenu.findItem(R.id.action_comment_view_post_detail_activity).setVisible(true);
if(mAccessToken != null) {
if(mPost.isSaved()) {
if (mAccessToken != null) {
if (mPost.isSaved()) {
saveItem.setVisible(true);
saveItem.setIcon(R.drawable.ic_baseline_bookmark_24px);
} else {
@ -1011,7 +1010,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
saveItem.setIcon(R.drawable.ic_baseline_bookmark_border_24px);
}
if(mPost.isHidden()) {
if (mPost.isHidden()) {
hideItem.setVisible(true);
hideItem.setTitle(R.string.action_unhide_post);
} else {
@ -1023,15 +1022,15 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
hideItem.setVisible(false);
}
if(mPost.getAuthor().equals(mAccountName)) {
if(mPost.getPostType() == Post.TEXT_TYPE) {
if (mPost.getAuthor().equals(mAccountName)) {
if (mPost.getPostType() == Post.TEXT_TYPE) {
menu.findItem(R.id.action_edit_view_post_detail_activity).setVisible(true);
}
menu.findItem(R.id.action_delete_view_post_detail_activity).setVisible(true);
MenuItem nsfwItem = menu.findItem(R.id.action_nsfw_view_post_detail_activity);
nsfwItem.setVisible(true);
if(mPost.isNSFW()) {
if (mPost.isNSFW()) {
nsfwItem.setTitle(R.string.action_unmark_nsfw);
} else {
nsfwItem.setTitle(R.string.action_mark_nsfw);
@ -1039,7 +1038,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
MenuItem spoilerItem = menu.findItem(R.id.action_spoiler_view_post_detail_activity);
spoilerItem.setVisible(true);
if(mPost.isSpoiler()) {
if (mPost.isSpoiler()) {
spoilerItem.setTitle(R.string.action_unmark_spoiler);
} else {
spoilerItem.setTitle(R.string.action_mark_spoiler);
@ -1060,18 +1059,18 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
refresh(true, true);
return true;
case R.id.action_comment_view_post_detail_activity:
if(mPost != null) {
if(mPost.isArchived()) {
if (mPost != null) {
if (mPost.isArchived()) {
showMessage(R.string.archived_post_reply_unavailable);
return true;
}
if(mPost.isLocked()) {
if (mPost.isLocked()) {
showMessage(R.string.locked_post_comment_unavailable);
return true;
}
if(mAccessToken == null) {
if (mAccessToken == null) {
showMessage(R.string.login_first);
return true;
}
@ -1085,8 +1084,8 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
}
return true;
case R.id.action_save_view_post_detail_activity:
if(mPost != null && mAccessToken != null) {
if(mPost.isSaved()) {
if (mPost != null && mAccessToken != null) {
if (mPost.isSaved()) {
item.setIcon(R.drawable.ic_baseline_bookmark_border_24px);
SaveThing.unsaveThing(mOauthRetrofit, mAccessToken, mPost.getFullName(),
new SaveThing.SaveThingListener() {
@ -1135,8 +1134,8 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
startActivity(crosspostIntent);
return true;
case R.id.action_hide_view_post_detail_activity:
if(mPost != null && mAccessToken != null) {
if(mPost.isHidden()) {
if (mPost != null && mAccessToken != null) {
if (mPost.isHidden()) {
item.setTitle(R.string.action_hide_post);
HidePost.unhidePost(mOauthRetrofit, mAccessToken, mPost.getFullName(), new HidePost.HidePostListener() {
@ -1208,14 +1207,14 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
.show();
return true;
case R.id.action_nsfw_view_post_detail_activity:
if(mPost.isNSFW()) {
if (mPost.isNSFW()) {
unmarkNSFW();
} else {
markNSFW();
}
return true;
case R.id.action_spoiler_view_post_detail_activity:
if(mPost.isSpoiler()) {
if (mPost.isSpoiler()) {
unmarkSpoiler();
} else {
markSpoiler();
@ -1239,16 +1238,16 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == WRITE_COMMENT_REQUEST_CODE) {
if(data != null && resultCode == RESULT_OK) {
if(data.hasExtra(EXTRA_COMMENT_DATA_KEY)) {
if (requestCode == WRITE_COMMENT_REQUEST_CODE) {
if (data != null && resultCode == RESULT_OK) {
if (data.hasExtra(EXTRA_COMMENT_DATA_KEY)) {
CommentData comment = data.getParcelableExtra(EXTRA_COMMENT_DATA_KEY);
if(comment != null && comment.getDepth() == 0) {
if (comment != null && comment.getDepth() == 0) {
mAdapter.addComment(comment);
} else {
String parentFullname = data.getStringExtra(CommentActivity.EXTRA_PARENT_FULLNAME_KEY);
int parentPosition = data.getIntExtra(CommentActivity.EXTRA_PARENT_POSITION_KEY, -1);
if(parentFullname != null && parentPosition >= 0) {
if (parentFullname != null && parentPosition >= 0) {
mAdapter.addChildComment(comment, parentFullname, parentPosition);
}
}
@ -1256,12 +1255,12 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
Toast.makeText(this, R.string.send_comment_failed, Toast.LENGTH_SHORT).show();
}
}
} else if(requestCode == EDIT_POST_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
} else if (requestCode == EDIT_POST_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
refresh(true, false);
}
} else if(requestCode == EDIT_COMMENT_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
} else if (requestCode == EDIT_COMMENT_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
mAdapter.editComment(data.getStringExtra(EditCommentActivity.EXTRA_EDITED_COMMENT_CONTENT),
data.getExtras().getInt(EditCommentActivity.EXTRA_EDITED_COMMENT_POSITION));
}
@ -1277,7 +1276,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
@Override
public void onBackPressed() {
if(orientation == getResources().getConfiguration().orientation) {
if (orientation == getResources().getConfiguration().orientation) {
super.onBackPressed();
} else {
finish();
@ -1303,7 +1302,7 @@ public class ViewPostDetailActivity extends AppCompatActivity implements FlairBo
RedditUtils.getOAuthHeader(mAccessToken), params).enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
refresh(true, false);
showMessage(R.string.update_flair_success);
} else {

View File

@ -91,19 +91,40 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
private static final String MESSAGE_FULLNAME_STATE = "MFS";
private static final String NEW_ACCOUNT_NAME_STATE = "NANS";
@BindView(R.id.coordinator_layout_view_subreddit_detail_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_view_subreddit_detail) AppBarLayout appBarLayout;
@BindView(R.id.collapsing_toolbar_layout_view_subreddit_detail_activity) CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.banner_image_view_view_subreddit_detail_activity) GifImageView 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;
@BindView(R.id.fab_view_subreddit_detail_activity) FloatingActionButton fab;
@BindView(R.id.coordinator_layout_view_subreddit_detail_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_view_subreddit_detail)
AppBarLayout appBarLayout;
@BindView(R.id.collapsing_toolbar_layout_view_subreddit_detail_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.banner_image_view_view_subreddit_detail_activity)
GifImageView 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;
@BindView(R.id.fab_view_subreddit_detail_activity)
FloatingActionButton fab;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
@ -115,30 +136,14 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
private boolean showToast = false;
private String mMessageFullname;
private String mNewAccountName;
private RequestManager glide;
private Fragment mFragment;
private Menu mMenu;
private AppBarLayout.LayoutParams params;
private PostTypeBottomSheetFragment postTypeBottomSheetFragment;
private SortTypeBottomSheetFragment sortTypeBottomSheetFragment;
private SubredditViewModel mSubredditViewModel;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -163,12 +168,12 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
Resources resources = getResources();
if(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || resources.getBoolean(R.bool.isTablet)) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
@ -178,11 +183,11 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if (state == State.COLLAPSED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
} else if (state == State.EXPANDED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
}
@ -210,7 +215,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -220,7 +225,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME_KEY);
if(savedInstanceState == null) {
if (savedInstanceState == null) {
mMessageFullname = getIntent().getStringExtra(EXTRA_MESSAGE_FULLNAME);
mNewAccountName = getIntent().getStringExtra(EXTRA_NEW_ACCOUNT_NAME);
getCurrentAccountAndBindView();
@ -234,7 +239,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
mMessageFullname = savedInstanceState.getString(MESSAGE_FULLNAME_STATE);
mNewAccountName = savedInstanceState.getString(NEW_ACCOUNT_NAME_STATE);
if(!mNullAccessToken && mAccessToken == null) {
if (!mNullAccessToken && mAccessToken == null) {
getCurrentAccountAndBindView();
} else {
bindView(false);
@ -242,7 +247,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout_view_subreddit_detail_activity, mFragment).commit();
}
if(mFetchSubredditInfoSuccess) {
if (mFetchSubredditInfoSuccess) {
nOnlineSubscribersTextView.setText(getString(R.string.online_subscribers_number_detail, mNCurrentOnlineSubscribers));
}
}
@ -280,8 +285,8 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
new SubredditViewModel.Factory(getApplication(), mRedditDataRoomDatabase, subredditName))
.get(SubredditViewModel.class);
mSubredditViewModel.getSubredditLiveData().observe(this, subredditData -> {
if(subredditData != null) {
if(subredditData.getBannerUrl().equals("")) {
if (subredditData != null) {
if (subredditData.getBannerUrl().equals("")) {
iconGifImageView.setOnClickListener(view -> {
//Do nothing as it has no image
});
@ -296,7 +301,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
});
}
if(subredditData.getIconUrl().equals("")) {
if (subredditData.getIconUrl().equals("")) {
glide.load(getDrawable(R.drawable.subreddit_default_icon))
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(216, 0)))
.into(iconGifImageView);
@ -319,13 +324,13 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
}
String subredditFullName = "r/" + subredditData.getName();
if(!title.equals(subredditFullName)) {
if (!title.equals(subredditFullName)) {
getSupportActionBar().setTitle(subredditFullName);
}
subredditNameTextView.setText(subredditFullName);
String nSubscribers = getString(R.string.subscribers_number_detail, subredditData.getNSubscribers());
nSubscribersTextView.setText(nSubscribers);
if(subredditData.getDescription().equals("")) {
if (subredditData.getDescription().equals("")) {
descriptionTextView.setVisibility(View.GONE);
} else {
descriptionTextView.setVisibility(View.VISIBLE);
@ -335,7 +340,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
});
fab.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(ViewSubredditDetailActivity.this, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
@ -346,14 +351,14 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
private void getCurrentAccountAndBindView() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(mNewAccountName != null) {
if(account == null || !account.getUsername().equals(mNewAccountName)) {
if (mNewAccountName != null) {
if (account == null || !account.getUsername().equals(mNewAccountName)) {
new SwitchAccountAsyncTask(mRedditDataRoomDatabase, mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
mNewAccountName = null;
if(newAccount == null) {
if (newAccount == null) {
mNullAccessToken = true;
} else {
mAccessToken = newAccount.getAccessToken();
@ -368,7 +373,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
bindView(true);
}
} else {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -381,7 +386,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
}
private void fetchSubredditData() {
if(!mFetchSubredditInfoSuccess) {
if (!mFetchSubredditInfoSuccess) {
FetchSubredditData.fetchSubredditData(mRetrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() {
@Override
public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
@ -400,7 +405,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
}
private void bindView(boolean initializeFragment) {
if(mAccessToken != null && mMessageFullname != null) {
if (mAccessToken != null && mMessageFullname != null) {
ReadMessage.readMessage(mOauthRetrofit, mAccessToken, mMessageFullname, new ReadMessage.ReadMessageListener() {
@Override
public void readSuccess() {
@ -415,14 +420,14 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
}
subscribeSubredditChip.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(ViewSubredditDetailActivity.this, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
if(subscriptionReady) {
if (subscriptionReady) {
subscriptionReady = false;
if(subscribeSubredditChip.getText().equals(getResources().getString(R.string.subscribe))) {
if (subscribeSubredditChip.getText().equals(getResources().getString(R.string.subscribe))) {
SubredditSubscription.subscribeToSubreddit(mOauthRetrofit, mRetrofit, mAccessToken,
subredditName, mAccountName, mRedditDataRoomDatabase,
new SubredditSubscription.SubredditSubscriptionListener() {
@ -479,7 +484,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
}
}).execute();
if(initializeFragment) {
if (initializeFragment) {
mFragment = new PostFragment();
Bundle bundle = new Bundle();
bundle.putString(PostFragment.EXTRA_NAME, subredditName);
@ -497,7 +502,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
getMenuInflater().inflate(R.menu.view_subreddit_detail_activity, menu);
mMenu = menu;
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_view_subreddit_detail_activity);
if(isInLazyMode) {
if (isInLazyMode) {
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED);
collapsingToolbarLayout.setLayoutParams(params);
@ -527,10 +532,10 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
startActivity(intent);
break;
case R.id.action_refresh_view_subreddit_detail_activity:
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_lazy_mode_view_subreddit_detail_activity).setTitle(R.string.action_start_lazy_mode);
}
if(mFragment instanceof FragmentCommunicator) {
if (mFragment instanceof FragmentCommunicator) {
((FragmentCommunicator) mFragment).refresh();
mFetchSubredditInfoSuccess = false;
fetchSubredditData();
@ -538,7 +543,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
break;
case R.id.action_lazy_mode_view_subreddit_detail_activity:
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_view_subreddit_detail_activity);
if(isInLazyMode) {
if (isInLazyMode) {
isInLazyMode = false;
((FragmentCommunicator) mFragment).stopLazyMode();
lazyModeItem.setTitle(R.string.action_start_lazy_mode);
@ -547,7 +552,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
collapsingToolbarLayout.setLayoutParams(params);
} else {
isInLazyMode = true;
if(((FragmentCommunicator) mFragment).startLazyMode()) {
if (((FragmentCommunicator) mFragment).startLazyMode()) {
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
appBarLayout.setExpanded(false);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED);
@ -581,10 +586,10 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
}
private void makeSnackbar(int resId, boolean retry) {
if(showToast) {
if (showToast) {
Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
} else {
if(retry) {
if (retry) {
Snackbar.make(coordinatorLayout, resId, Snackbar.LENGTH_SHORT).setAction(R.string.retry,
view -> fetchSubredditData()).show();
} else {
@ -634,7 +639,7 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
@Subscribe
public void onAccountSwitchEvent(SwitchAccountEvent event) {
if(!getClass().getName().equals(event.excludeActivityClassName)) {
if (!getClass().getName().equals(event.excludeActivityClassName)) {
finish();
}
}
@ -647,14 +652,9 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
private static class InsertSubredditDataAsyncTask extends AsyncTask<Void, Void, Void> {
interface InsertSubredditDataAsyncTaskListener {
void insertSuccess();
}
private SubredditDao mSubredditDao;
private SubredditData subredditData;
private InsertSubredditDataAsyncTaskListener insertSubredditDataAsyncTaskListener;
InsertSubredditDataAsyncTask(RedditDataRoomDatabase db, SubredditData subredditData,
InsertSubredditDataAsyncTaskListener insertSubredditDataAsyncTaskListener) {
mSubredditDao = db.subredditDao();
@ -672,5 +672,9 @@ public class ViewSubredditDetailActivity extends AppCompatActivity implements So
protected void onPostExecute(Void aVoid) {
insertSubredditDataAsyncTaskListener.insertSuccess();
}
interface InsertSubredditDataAsyncTaskListener {
void insertSuccess();
}
}
}

View File

@ -43,35 +43,35 @@ import org.greenrobot.eventbus.Subscribe;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.AppBarStateChangeListener;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.AsyncTask.CheckIsFollowingUserAsyncTask;
import ml.docilealligator.infinityforreddit.Fragment.CommentsListingFragment;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchAccountAsyncTask;
import ml.docilealligator.infinityforreddit.ContentFontStyle;
import ml.docilealligator.infinityforreddit.DeleteThing;
import ml.docilealligator.infinityforreddit.Event.ChangeNSFWEvent;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.FetchUserData;
import ml.docilealligator.infinityforreddit.FontStyle;
import ml.docilealligator.infinityforreddit.Fragment.CommentsListingFragment;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.Fragment.UserThingSortTypeBottomSheetFragment;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.AsyncTask.GetCurrentAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.ReadMessage;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SharedPreferencesUtils;
import ml.docilealligator.infinityforreddit.SubscribedUserDatabase.SubscribedUserDao;
import ml.docilealligator.infinityforreddit.AsyncTask.SwitchAccountAsyncTask;
import ml.docilealligator.infinityforreddit.Event.SwitchAccountEvent;
import ml.docilealligator.infinityforreddit.TitleFontStyle;
import ml.docilealligator.infinityforreddit.User.UserDao;
import ml.docilealligator.infinityforreddit.User.UserData;
import ml.docilealligator.infinityforreddit.User.UserViewModel;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.UserFollowing;
import ml.docilealligator.infinityforreddit.Fragment.UserThingSortTypeBottomSheetFragment;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
@ -94,27 +94,43 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
private static final String MESSAGE_FULLNAME_STATE = "MFS";
private static final String NEW_ACCOUNT_NAME_STATE = "NANS";
@BindView(R.id.coordinator_layout_view_user_detail_activity) CoordinatorLayout coordinatorLayout;
@BindView(R.id.view_pager_view_user_detail_activity) ViewPager viewPager;
@BindView(R.id.appbar_layout_view_user_detail) AppBarLayout appBarLayout;
@BindView(R.id.tab_layout_view_user_detail_activity) TabLayout tabLayout;
@BindView(R.id.collapsing_toolbar_layout_view_user_detail_activity) CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.banner_image_view_view_user_detail_activity) GifImageView bannerImageView;
@BindView(R.id.icon_gif_image_view_view_user_detail_activity) GifImageView iconGifImageView;
@BindView(R.id.user_name_text_view_view_user_detail_activity) TextView userNameTextView;
@BindView(R.id.subscribe_user_chip_view_user_detail_activity) Chip subscribeUserChip;
@BindView(R.id.karma_text_view_view_user_detail_activity) TextView karmaTextView;
@BindView(R.id.coordinator_layout_view_user_detail_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.view_pager_view_user_detail_activity)
ViewPager viewPager;
@BindView(R.id.appbar_layout_view_user_detail)
AppBarLayout appBarLayout;
@BindView(R.id.tab_layout_view_user_detail_activity)
TabLayout tabLayout;
@BindView(R.id.collapsing_toolbar_layout_view_user_detail_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.banner_image_view_view_user_detail_activity)
GifImageView bannerImageView;
@BindView(R.id.icon_gif_image_view_view_user_detail_activity)
GifImageView iconGifImageView;
@BindView(R.id.user_name_text_view_view_user_detail_activity)
TextView userNameTextView;
@BindView(R.id.subscribe_user_chip_view_user_detail_activity)
Chip subscribeUserChip;
@BindView(R.id.karma_text_view_view_user_detail_activity)
TextView karmaTextView;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private SectionsPagerAdapter sectionsPagerAdapter;
private SubscribedUserDao subscribedUserDao;
private RequestManager glide;
private UserViewModel userViewModel;
private Menu mMenu;
private AppBarLayout.LayoutParams params;
private UserThingSortTypeBottomSheetFragment userThingSortTypeBottomSheetFragment;
private boolean mNullAccessToken = false;
private String mAccessToken;
private String mAccountName;
@ -132,20 +148,6 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
private String mMessageFullname;
private String mNewAccountName;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -177,7 +179,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
break;
case 2:
if(systemDefault) {
if (systemDefault) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO_BATTERY);
@ -246,7 +248,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
boolean lightNavBar = false;
if((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
if ((resources.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
lightNavBar = true;
}
boolean finalLightNavBar = lightNavBar;
@ -256,14 +258,14 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
if (state == State.COLLAPSED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
tabLayout.setTabTextColors(collapsedTabTextColor, collapsedTabTextColor);
tabLayout.setSelectedTabIndicatorColor(collapsedTabIndicatorColor);
tabLayout.setBackgroundColor(collapsedTabBackgroundColor);
} else if (state == State.EXPANDED) {
if(finalLightNavBar) {
if (finalLightNavBar) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
tabLayout.setTabTextColors(expandedTabTextColor, expandedTabTextColor);
@ -339,7 +341,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
if (userData.isCanBeFollowed()) {
subscribeUserChip.setVisibility(View.VISIBLE);
subscribeUserChip.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(ViewUserDetailActivity.this, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
@ -418,14 +420,14 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
private void getCurrentAccountAndInitializeViewPager() {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(mNewAccountName != null) {
if(account == null || !account.getUsername().equals(mNewAccountName)) {
if (mNewAccountName != null) {
if (account == null || !account.getUsername().equals(mNewAccountName)) {
new SwitchAccountAsyncTask(mRedditDataRoomDatabase, mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
mNewAccountName = null;
if(newAccount == null) {
if (newAccount == null) {
mNullAccessToken = true;
} else {
mAccessToken = newAccount.getAccessToken();
@ -440,7 +442,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
initializeViewPager();
}
} else {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -466,8 +468,8 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
@Override
public void onPageSelected(int position) {
if(isInLazyMode) {
if(viewPager.getCurrentItem() == 0) {
if (isInLazyMode) {
if (viewPager.getCurrentItem() == 0) {
sectionsPagerAdapter.resumeLazyMode();
} else {
sectionsPagerAdapter.pauseLazyMode();
@ -481,7 +483,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
}
});
if(mAccessToken != null && mMessageFullname != null) {
if (mAccessToken != null && mMessageFullname != null) {
ReadMessage.readMessage(mOauthRetrofit, mAccessToken, mMessageFullname, new ReadMessage.ReadMessageListener() {
@Override
public void readSuccess() {
@ -570,7 +572,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
startActivity(intent);
return true;
case R.id.action_refresh_view_user_detail_activity:
if(mMenu != null) {
if (mMenu != null) {
mMenu.findItem(R.id.action_lazy_mode_view_user_detail_activity).setTitle(R.string.action_start_lazy_mode);
}
sectionsPagerAdapter.refresh();
@ -579,7 +581,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
return true;
case R.id.action_lazy_mode_view_user_detail_activity:
MenuItem lazyModeItem = mMenu.findItem(R.id.action_lazy_mode_view_user_detail_activity);
if(isInLazyMode) {
if (isInLazyMode) {
isInLazyMode = false;
sectionsPagerAdapter.stopLazyMode();
lazyModeItem.setTitle(R.string.action_start_lazy_mode);
@ -588,7 +590,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
collapsingToolbarLayout.setLayoutParams(params);
} else {
isInLazyMode = true;
if(sectionsPagerAdapter.startLazyMode()) {
if (sectionsPagerAdapter.startLazyMode()) {
lazyModeItem.setTitle(R.string.action_stop_lazy_mode);
appBarLayout.setExpanded(false);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED);
@ -621,7 +623,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
}
private void showMessage(int resId, boolean retry) {
if(showToast) {
if (showToast) {
Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
} else {
if (retry) {
@ -640,7 +642,7 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
@Subscribe
public void onAccountSwitchEvent(SwitchAccountEvent event) {
if(!getClass().getName().equals(event.excludeActivityClassName)) {
if (!getClass().getName().equals(event.excludeActivityClassName)) {
finish();
}
}
@ -652,14 +654,9 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
private static class InsertUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
interface InsertUserDataAsyncTaskListener {
void insertSuccess();
}
private UserDao userDao;
private UserData subredditData;
private InsertUserDataAsyncTaskListener insertUserDataAsyncTaskListener;
InsertUserDataAsyncTask(UserDao userDao, UserData userData,
InsertUserDataAsyncTaskListener insertUserDataAsyncTaskListener) {
this.userDao = userDao;
@ -677,6 +674,10 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
protected void onPostExecute(Void aVoid) {
insertUserDataAsyncTaskListener.insertSuccess();
}
interface InsertUserDataAsyncTaskListener {
void insertSuccess();
}
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
@ -744,55 +745,55 @@ public class ViewUserDetailActivity extends AppCompatActivity implements UserThi
public void refresh() {
if (viewPager.getCurrentItem() == 0) {
if(postFragment != null) {
if (postFragment != null) {
postFragment.refresh();
}
} else {
if(commentsListingFragment != null) {
if (commentsListingFragment != null) {
commentsListingFragment.refresh();
}
}
}
boolean startLazyMode() {
if(postFragment != null) {
if (postFragment != null) {
return ((FragmentCommunicator) postFragment).startLazyMode();
}
return false;
}
void stopLazyMode() {
if(postFragment != null) {
if (postFragment != null) {
((FragmentCommunicator) postFragment).stopLazyMode();
}
}
void resumeLazyMode() {
if(postFragment != null) {
if (postFragment != null) {
((FragmentCommunicator) postFragment).resumeLazyMode(false);
}
}
void pauseLazyMode() {
if(postFragment != null) {
if (postFragment != null) {
((FragmentCommunicator) postFragment).pauseLazyMode(false);
}
}
public void changeSortType(String sortType) {
if(viewPager.getCurrentItem() == 0) {
if(postFragment != null) {
if (viewPager.getCurrentItem() == 0) {
if (postFragment != null) {
postFragment.changeSortType(sortType);
}
} else {
if(commentsListingFragment != null) {
if (commentsListingFragment != null) {
commentsListingFragment.changeSortType(sortType);
}
}
}
public void changeNSFW(boolean nsfw) {
if(postFragment != null) {
if (postFragment != null) {
postFragment.changeNSFW(nsfw);
}
}

View File

@ -50,14 +50,14 @@ import ml.docilealligator.infinityforreddit.R;
public class ViewVideoActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
public static final String TITLE_KEY = "TK";
public static final String SUBREDDIT_KEY = "SK";
public static final String ID_KEY = "IK";
@BindView(R.id.relative_layout_view_video_activity) RelativeLayout relativeLayout;
@BindView(R.id.player_view_view_video_activity) PlayerView videoPlayerView;
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
@BindView(R.id.relative_layout_view_video_activity)
RelativeLayout relativeLayout;
@BindView(R.id.player_view_view_video_activity)
PlayerView videoPlayerView;
private Uri mVideoUri;
private SimpleExoPlayer player;
@ -122,7 +122,7 @@ public class ViewVideoActivity extends AppCompatActivity {
actionBarElementColorAnimation.addUpdateListener(valueAnimator -> {
upArrow.setColorFilter((int) valueAnimator.getAnimatedValue(), PorterDuff.Mode.SRC_IN);
if(mMenu != null) {
if (mMenu != null) {
Drawable drawable = mMenu.getItem(0).getIcon();
drawable.setColorFilter((int) valueAnimator.getAnimatedValue(), PorterDuff.Mode.SRC_IN);
}
@ -134,7 +134,7 @@ public class ViewVideoActivity extends AppCompatActivity {
public void onSwipingUp(final MotionEvent event) {
float nowY = event.getY();
float offset;
if(touchY == -1.0f) {
if (touchY == -1.0f) {
offset = 0.0f;
} else {
offset = nowY - touchY;
@ -154,7 +154,7 @@ public class ViewVideoActivity extends AppCompatActivity {
.setDuration(300)
.start();
if(totalLengthY < -pxHeight / 8) {
if (totalLengthY < -pxHeight / 8) {
videoPlayerView.animate()
.y(-pxHeight)
.setDuration(300)
@ -172,10 +172,12 @@ public class ViewVideoActivity extends AppCompatActivity {
}
@Override
public void onAnimationCancel(Animator animator) {}
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {}
public void onAnimationRepeat(Animator animator) {
}
})
.start();
} else {
@ -194,7 +196,7 @@ public class ViewVideoActivity extends AppCompatActivity {
public void onSwipingDown(final MotionEvent event) {
float nowY = event.getY();
float offset;
if(touchY == -1.0f) {
if (touchY == -1.0f) {
offset = 0.0f;
} else {
offset = nowY - touchY;
@ -209,7 +211,7 @@ public class ViewVideoActivity extends AppCompatActivity {
@Override
public boolean onSwipedDown(final MotionEvent event) {
if(totalLengthY > pxHeight / 8) {
if (totalLengthY > pxHeight / 8) {
videoPlayerView.animate()
.y(pxHeight)
.setDuration(300)
@ -227,10 +229,12 @@ public class ViewVideoActivity extends AppCompatActivity {
}
@Override
public void onAnimationCancel(Animator animator) {}
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {}
public void onAnimationRepeat(Animator animator) {
}
})
.start();
} else {
@ -333,7 +337,7 @@ public class ViewVideoActivity extends AppCompatActivity {
@Override
protected void onStart() {
super.onStart();
if(wasPlaying) {
if (wasPlaying) {
player.setPlayWhenReady(true);
}
}
@ -347,10 +351,10 @@ public class ViewVideoActivity extends AppCompatActivity {
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) {
if(grantResults[0] == PackageManager.PERMISSION_DENIED) {
if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
} else if(grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) {
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) {
download();
}
isDownloading = false;

View File

@ -15,28 +15,20 @@ import com.bumptech.glide.request.RequestOptions;
import java.util.List;
import ml.docilealligator.infinityforreddit.Account.Account;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.Account.Account;
import ml.docilealligator.infinityforreddit.R;
import pl.droidsonroids.gif.GifImageView;
public class AccountRecyclerViewAdapter extends RecyclerView.Adapter<AccountRecyclerViewAdapter.AccountViewHolder> {
public interface ItemSelectedListener {
void accountSelected(Account account);
void addAccountSelected();
void anonymousSelected();
void logoutSelected();
}
private List<Account> mAccounts;
private String mCurrentAccountName;
private Context mContext;
private RequestManager mGlide;
private ItemSelectedListener mItemSelectedListener;
public AccountRecyclerViewAdapter(Context context, RequestManager glide, String currentAccountName, ItemSelectedListener itemSelectedListener) {
mContext = context;
mGlide = glide;
@ -52,14 +44,14 @@ public class AccountRecyclerViewAdapter extends RecyclerView.Adapter<AccountRecy
@Override
public void onBindViewHolder(@NonNull AccountViewHolder holder, int position) {
if(mAccounts == null) {
if (mAccounts == null) {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(128, 0)))
.into(holder.profileImageGifImageView);
holder.usernameTextView.setText(R.string.add_account);
holder.itemView.setOnClickListener(view -> mItemSelectedListener.addAccountSelected());
} else {
if(position < mAccounts.size()) {
if (position < mAccounts.size()) {
mGlide.load(mAccounts.get(position).getProfileImageUrl())
.error(mGlide.load(R.drawable.subreddit_default_icon))
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(128, 0)))
@ -69,14 +61,14 @@ public class AccountRecyclerViewAdapter extends RecyclerView.Adapter<AccountRecy
mCurrentAccountName = mAccounts.get(position).getUsername();
mItemSelectedListener.accountSelected(mAccounts.get(position));
});
} else if(position == mAccounts.size()) {
} else if (position == mAccounts.size()) {
holder.profileImageGifImageView.setColorFilter(ContextCompat.getColor(mContext, R.color.primaryTextColor), android.graphics.PorterDuff.Mode.SRC_IN);
mGlide.load(R.drawable.ic_outline_add_circle_outline_24px)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(128, 0)))
.into(holder.profileImageGifImageView);
holder.usernameTextView.setText(R.string.add_account);
holder.itemView.setOnClickListener(view -> mItemSelectedListener.addAccountSelected());
} else if(position == mAccounts.size() + 1) {
} else if (position == mAccounts.size() + 1) {
holder.profileImageGifImageView.setColorFilter(ContextCompat.getColor(mContext, R.color.primaryTextColor), android.graphics.PorterDuff.Mode.SRC_IN);
mGlide.load(R.drawable.ic_outline_public_24px)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(128, 0)))
@ -96,10 +88,10 @@ public class AccountRecyclerViewAdapter extends RecyclerView.Adapter<AccountRecy
@Override
public int getItemCount() {
if(mAccounts == null) {
if (mAccounts == null) {
return 1;
} else {
if(mCurrentAccountName == null) {
if (mCurrentAccountName == null) {
return mAccounts.size() + 1;
} else {
return mAccounts.size() + 3;
@ -118,9 +110,21 @@ public class AccountRecyclerViewAdapter extends RecyclerView.Adapter<AccountRecy
notifyDataSetChanged();
}
public interface ItemSelectedListener {
void accountSelected(Account account);
void addAccountSelected();
void anonymousSelected();
void logoutSelected();
}
class AccountViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.profile_image_item_account) GifImageView profileImageGifImageView;
@BindView(R.id.username_text_view_item_account) TextView usernameTextView;
@BindView(R.id.profile_image_item_account)
GifImageView profileImageGifImageView;
@BindView(R.id.username_text_view_item_account)
TextView usernameTextView;
AccountViewHolder(@NonNull View itemView) {
super(itemView);

View File

@ -43,6 +43,20 @@ import ml.docilealligator.infinityforreddit.VoteThing;
import retrofit2.Retrofit;
public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<CommentData, RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1;
private static final int VIEW_TYPE_LOADING = 2;
private static final DiffUtil.ItemCallback<CommentData> DIFF_CALLBACK = new DiffUtil.ItemCallback<CommentData>() {
@Override
public boolean areItemsTheSame(@NonNull CommentData commentData, @NonNull CommentData t1) {
return commentData.getId().equals(t1.getId());
}
@Override
public boolean areContentsTheSame(@NonNull CommentData commentData, @NonNull CommentData t1) {
return commentData.getCommentContent().equals(t1.getCommentContent());
}
};
private Context mContext;
private Retrofit mOauthRetrofit;
private Markwon mMarkwon;
@ -50,21 +64,12 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
private String mAccountName;
private int mTextColorPrimaryDark;
private int mColorAccent;
private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1;
private static final int VIEW_TYPE_LOADING = 2;
private NetworkState networkState;
private RetryLoadingMoreCallback mRetryLoadingMoreCallback;
public interface RetryLoadingMoreCallback {
void retryLoadingMore();
}
public CommentsListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit,
String accessToken, String accountName,
RetryLoadingMoreCallback retryLoadingMoreCallback) {
String accessToken, String accountName,
RetryLoadingMoreCallback retryLoadingMoreCallback) {
super(DIFF_CALLBACK);
mContext = context;
mOauthRetrofit = oauthRetrofit;
@ -75,7 +80,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
builder.linkResolver((view, link) -> {
Intent intent = new Intent(mContext, LinkResolverActivity.class);
Uri uri = Uri.parse(link);
if(uri.getScheme() == null && uri.getHost() == null) {
if (uri.getScheme() == null && uri.getHost() == null) {
intent.setData(LinkResolverActivity.getRedditUriByPath(link));
} else {
intent.setData(uri);
@ -94,24 +99,12 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
mColorAccent = mContext.getResources().getColor(R.color.colorAccent);
}
private static final DiffUtil.ItemCallback<CommentData> DIFF_CALLBACK = new DiffUtil.ItemCallback<CommentData>() {
@Override
public boolean areItemsTheSame(@NonNull CommentData commentData, @NonNull CommentData t1) {
return commentData.getId().equals(t1.getId());
}
@Override
public boolean areContentsTheSame(@NonNull CommentData commentData, @NonNull CommentData t1) {
return commentData.getCommentContent().equals(t1.getCommentContent());
}
};
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_DATA) {
if (viewType == VIEW_TYPE_DATA) {
return new DataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment, parent, false));
} else if(viewType == VIEW_TYPE_ERROR) {
} else if (viewType == VIEW_TYPE_ERROR) {
return new ErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_error, parent, false));
} else {
return new LoadingViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_loading, parent, false));
@ -120,10 +113,10 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof DataViewHolder) {
if (holder instanceof DataViewHolder) {
CommentData comment = getItem(holder.getAdapterPosition());
if(comment != null) {
if(comment.getSubredditName().substring(2).equals(comment.getLinkAuthor())) {
if (comment != null) {
if (comment.getSubredditName().substring(2).equals(comment.getLinkAuthor())) {
((DataViewHolder) holder).authorTextView.setText("u/" + comment.getLinkAuthor());
((DataViewHolder) holder).authorTextView.setTextColor(mTextColorPrimaryDark);
((DataViewHolder) holder).authorTextView.setOnClickListener(view -> {
@ -160,7 +153,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
break;
}
if(comment.getAuthor().equals(mAccountName)) {
if (comment.getAuthor().equals(mAccountName)) {
((DataViewHolder) holder).moreButton.setVisibility(View.VISIBLE);
((DataViewHolder) holder).moreButton.setOnClickListener(view -> {
ModifyCommentBottomSheetFragment modifyCommentBottomSheetFragment = new ModifyCommentBottomSheetFragment();
@ -201,7 +194,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
((DataViewHolder) holder).replyButton.setVisibility(View.GONE);
((DataViewHolder) holder).upvoteButton.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(mContext, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
@ -211,7 +204,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
((DataViewHolder) holder).downvoteButton.clearColorFilter();
if(previousVoteType != CommentData.VOTE_TYPE_UPVOTE) {
if (previousVoteType != CommentData.VOTE_TYPE_UPVOTE) {
//Not upvoted before
comment.setVoteType(CommentData.VOTE_TYPE_UPVOTE);
newVoteType = RedditUtils.DIR_UPVOTE;
@ -231,7 +224,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position) {
if(newVoteType.equals(RedditUtils.DIR_UPVOTE)) {
if (newVoteType.equals(RedditUtils.DIR_UPVOTE)) {
comment.setVoteType(CommentData.VOTE_TYPE_UPVOTE);
((DataViewHolder) holder).upvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.upvoted), android.graphics.PorterDuff.Mode.SRC_IN);
((DataViewHolder) holder).scoreTextView.setTextColor(ContextCompat.getColor(mContext, R.color.upvoted));
@ -246,12 +239,13 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
}
@Override
public void onVoteThingFail(int position) { }
public void onVoteThingFail(int position) {
}
}, comment.getFullName(), newVoteType, holder.getAdapterPosition());
});
((DataViewHolder) holder).downvoteButton.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(mContext, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
@ -261,7 +255,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
((DataViewHolder) holder).upvoteButton.clearColorFilter();
if(previousVoteType != CommentData.VOTE_TYPE_DOWNVOTE) {
if (previousVoteType != CommentData.VOTE_TYPE_DOWNVOTE) {
//Not downvoted before
comment.setVoteType(CommentData.VOTE_TYPE_DOWNVOTE);
newVoteType = RedditUtils.DIR_DOWNVOTE;
@ -280,7 +274,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position1) {
if(newVoteType.equals(RedditUtils.DIR_DOWNVOTE)) {
if (newVoteType.equals(RedditUtils.DIR_DOWNVOTE)) {
comment.setVoteType(CommentData.VOTE_TYPE_DOWNVOTE);
((DataViewHolder) holder).downvoteButton.setColorFilter(ContextCompat.getColor(mContext, R.color.downvoted), android.graphics.PorterDuff.Mode.SRC_IN);
((DataViewHolder) holder).scoreTextView.setTextColor(ContextCompat.getColor(mContext, R.color.downvoted));
@ -295,11 +289,12 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
}
@Override
public void onVoteThingFail(int position1) { }
public void onVoteThingFail(int position1) {
}
}, comment.getFullName(), newVoteType, holder.getAdapterPosition());
});
if(comment.isSaved()) {
if (comment.isSaved()) {
((DataViewHolder) holder).saveButton.setImageResource(R.drawable.ic_bookmark_20dp);
} else {
((DataViewHolder) holder).saveButton.setImageResource(R.drawable.ic_bookmark_border_20dp);
@ -362,7 +357,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if(holder instanceof DataViewHolder) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).upvoteButton.clearColorFilter();
((DataViewHolder) holder).downvoteButton.clearColorFilter();
((DataViewHolder) holder).scoreTextView.setTextColor(ContextCompat.getColor(mContext, R.color.defaultTextColor));
@ -371,7 +366,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
@Override
public int getItemCount() {
if(hasExtraRow()) {
if (hasExtraRow()) {
return super.getItemCount() + 1;
}
return super.getItemCount();
@ -397,19 +392,35 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
}
}
public interface RetryLoadingMoreCallback {
void retryLoadingMore();
}
class DataViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.linear_layout_item_comment) LinearLayout linearLayout;
@BindView(R.id.vertical_block_item_post_comment) View verticalBlock;
@BindView(R.id.author_text_view_item_post_comment) TextView authorTextView;
@BindView(R.id.comment_time_text_view_item_post_comment) TextView commentTimeTextView;
@BindView(R.id.comment_markdown_view_item_post_comment) TextView commentMarkdownView;
@BindView(R.id.up_vote_button_item_post_comment) ImageView upvoteButton;
@BindView(R.id.score_text_view_item_post_comment) TextView scoreTextView;
@BindView(R.id.down_vote_button_item_post_comment) ImageView downvoteButton;
@BindView(R.id.more_button_item_post_comment) ImageView moreButton;
@BindView(R.id.save_button_item_post_comment) ImageView saveButton;
@BindView(R.id.share_button_item_post_comment) ImageView shareButton;
@BindView(R.id.reply_button_item_post_comment) ImageView replyButton;
@BindView(R.id.linear_layout_item_comment)
LinearLayout linearLayout;
@BindView(R.id.vertical_block_item_post_comment)
View verticalBlock;
@BindView(R.id.author_text_view_item_post_comment)
TextView authorTextView;
@BindView(R.id.comment_time_text_view_item_post_comment)
TextView commentTimeTextView;
@BindView(R.id.comment_markdown_view_item_post_comment)
TextView commentMarkdownView;
@BindView(R.id.up_vote_button_item_post_comment)
ImageView upvoteButton;
@BindView(R.id.score_text_view_item_post_comment)
TextView scoreTextView;
@BindView(R.id.down_vote_button_item_post_comment)
ImageView downvoteButton;
@BindView(R.id.more_button_item_post_comment)
ImageView moreButton;
@BindView(R.id.save_button_item_post_comment)
ImageView saveButton;
@BindView(R.id.share_button_item_post_comment)
ImageView shareButton;
@BindView(R.id.reply_button_item_post_comment)
ImageView replyButton;
DataViewHolder(View itemView) {
super(itemView);
@ -418,8 +429,10 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
}
class ErrorViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.error_text_view_item_footer_error) TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error) Button retryButton;
@BindView(R.id.error_text_view_item_footer_error)
TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error)
Button retryButton;
ErrorViewHolder(View itemView) {
super(itemView);

View File

@ -23,14 +23,9 @@ import ml.docilealligator.infinityforreddit.Flair;
import ml.docilealligator.infinityforreddit.R;
public class FlairBottomSheetRecyclerViewAdapter extends RecyclerView.Adapter<FlairBottomSheetRecyclerViewAdapter.FlairViewHolder> {
public interface ItemClickListener {
void onClick(Flair flair);
}
private Context context;
private ArrayList<Flair> flairs;
private ItemClickListener itemClickListener;
public FlairBottomSheetRecyclerViewAdapter(Context context, ItemClickListener itemClickListener) {
this.context = context;
this.itemClickListener = itemClickListener;
@ -44,14 +39,14 @@ public class FlairBottomSheetRecyclerViewAdapter extends RecyclerView.Adapter<Fl
@Override
public void onBindViewHolder(@NonNull FlairViewHolder holder, int position) {
if(flairs.get(holder.getAdapterPosition()).isEditable()) {
if (flairs.get(holder.getAdapterPosition()).isEditable()) {
holder.editFlairImageView.setVisibility(View.VISIBLE);
holder.editFlairImageView.setOnClickListener(view -> {
View dialogView = ((Activity) context).getLayoutInflater().inflate(R.layout.dialog_edit_flair, null);
EditText flairEditText = dialogView.findViewById(R.id.flair_edit_text_edit_flair_dialog);
flairEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null) {
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
new MaterialAlertDialogBuilder(context, R.style.MaterialAlertDialogTheme)
@ -68,7 +63,7 @@ public class FlairBottomSheetRecyclerViewAdapter extends RecyclerView.Adapter<Fl
});
}
if(flairs.get(holder.getAdapterPosition()).isEditable() && flairs.get(holder.getAdapterPosition()).getText().equals("")) {
if (flairs.get(holder.getAdapterPosition()).isEditable() && flairs.get(holder.getAdapterPosition()).getText().equals("")) {
holder.itemView.setOnClickListener(view -> holder.editFlairImageView.performClick());
} else {
holder.itemView.setOnClickListener(view -> itemClickListener.onClick(flairs.get(holder.getAdapterPosition())));
@ -93,10 +88,16 @@ public class FlairBottomSheetRecyclerViewAdapter extends RecyclerView.Adapter<Fl
notifyDataSetChanged();
}
public interface ItemClickListener {
void onClick(Flair flair);
}
class FlairViewHolder extends RecyclerView.ViewHolder {
View itemView;
@BindView(R.id.flair_text_view_item_flair) TextView flairTextView;
@BindView(R.id.edit_flair_image_view_item_flair) ImageView editFlairImageView;
@BindView(R.id.flair_text_view_item_flair)
TextView flairTextView;
@BindView(R.id.edit_flair_image_view_item_flair)
ImageView editFlairImageView;
FlairViewHolder(@NonNull View itemView) {
super(itemView);

View File

@ -16,10 +16,10 @@ import com.bumptech.glide.request.RequestOptions;
import java.util.List;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.Activity.ViewUserDetailActivity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.SubscribedUserDatabase.SubscribedUserData;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import pl.droidsonroids.gif.GifImageView;
public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@ -45,7 +45,7 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mSubscribedUserData.get(viewHolder.getAdapterPosition()).getName());
mContext.startActivity(intent);
});
if(!mSubscribedUserData.get(i).getIconUrl().equals("")) {
if (!mSubscribedUserData.get(i).getIconUrl().equals("")) {
glide.load(mSubscribedUserData.get(i).getIconUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
@ -61,7 +61,7 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
@Override
public int getItemCount() {
if(mSubscribedUserData != null) {
if (mSubscribedUserData != null) {
return mSubscribedUserData.size();
}
return 0;
@ -72,7 +72,7 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
glide.clear(((UserViewHolder) holder).iconGifImageView);
}
public void setSubscribedUsers(List<SubscribedUserData> subscribedUsers){
public void setSubscribedUsers(List<SubscribedUserData> subscribedUsers) {
mSubscribedUserData = subscribedUsers;
notifyDataSetChanged();
}

View File

@ -35,22 +35,27 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1;
private static final int VIEW_TYPE_LOADING = 2;
private static final DiffUtil.ItemCallback<Message> DIFF_CALLBACK = new DiffUtil.ItemCallback<Message>() {
@Override
public boolean areItemsTheSame(@NonNull Message message, @NonNull Message t1) {
return message.getId().equals(t1.getId());
}
@Override
public boolean areContentsTheSame(@NonNull Message message, @NonNull Message t1) {
return message.getBody().equals(t1.getBody());
}
};
private Context mContext;
private Retrofit mOauthRetrofit;
private Markwon mMarkwon;
private String mAccessToken;
private Resources mResources;
private NetworkState networkState;
private RetryLoadingMoreCallback mRetryLoadingMoreCallback;
public interface RetryLoadingMoreCallback {
void retryLoadingMore();
}
public MessageRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, String accessToken,
RetryLoadingMoreCallback retryLoadingMoreCallback) {
RetryLoadingMoreCallback retryLoadingMoreCallback) {
super(DIFF_CALLBACK);
mContext = context;
mOauthRetrofit = oauthRetrofit;
@ -62,7 +67,7 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
builder.linkResolver((view, link) -> {
Intent intent = new Intent(mContext, LinkResolverActivity.class);
Uri uri = Uri.parse(link);
if(uri.getScheme() == null && uri.getHost() == null) {
if (uri.getScheme() == null && uri.getHost() == null) {
intent.setData(LinkResolverActivity.getRedditUriByPath(link));
} else {
intent.setData(uri);
@ -78,24 +83,12 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
mResources = context.getResources();
}
private static final DiffUtil.ItemCallback<Message> DIFF_CALLBACK = new DiffUtil.ItemCallback<Message>() {
@Override
public boolean areItemsTheSame(@NonNull Message message, @NonNull Message t1) {
return message.getId().equals(t1.getId());
}
@Override
public boolean areContentsTheSame(@NonNull Message message, @NonNull Message t1) {
return message.getBody().equals(t1.getBody());
}
};
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_DATA) {
if (viewType == VIEW_TYPE_DATA) {
return new DataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message, parent, false));
} else if(viewType == VIEW_TYPE_ERROR) {
} else if (viewType == VIEW_TYPE_ERROR) {
return new ErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_error, parent, false));
} else {
return new LoadingViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_loading, parent, false));
@ -104,15 +97,15 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof DataViewHolder) {
if (holder instanceof DataViewHolder) {
Message message = getItem(holder.getAdapterPosition());
if(message != null) {
if(message.isNew()) {
if (message != null) {
if (message.isNew()) {
((DataViewHolder) holder).itemView.setBackgroundColor(
mResources.getColor(R.color.unreadMessageBackgroundColor));
}
if(message.wasComment()) {
if (message.wasComment()) {
((DataViewHolder) holder).authorTextView.setTextColor(mResources.getColor(R.color.colorPrimaryDarkDayNightTheme));
((DataViewHolder) holder).titleTextView.setText(message.getTitle());
} else {
@ -125,33 +118,34 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
mMarkwon.setMarkdown(((DataViewHolder) holder).contentCustomMarkwonView, message.getBody());
((DataViewHolder) holder).itemView.setOnClickListener(view -> {
if(message.getContext() != null && !message.getContext().equals("")) {
if (message.getContext() != null && !message.getContext().equals("")) {
Uri uri = LinkResolverActivity.getRedditUriByPath(message.getContext());
Intent intent = new Intent(mContext, LinkResolverActivity.class);
intent.setData(uri);
mContext.startActivity(intent);
}
if(message.isNew()) {
if (message.isNew()) {
((DataViewHolder) holder).itemView.setBackgroundColor(mResources.getColor(R.color.backgroundColor));
message.setNew(false);
ReadMessage.readMessage(mOauthRetrofit, mAccessToken, message.getFullname(),
new ReadMessage.ReadMessageListener() {
@Override
public void readSuccess() {}
@Override
public void readSuccess() {
}
@Override
public void readFailed() {
message.setNew(true);
((DataViewHolder) holder).itemView.setBackgroundColor(mResources.getColor(R.color.unreadMessageBackgroundColor));
}
});
@Override
public void readFailed() {
message.setNew(true);
((DataViewHolder) holder).itemView.setBackgroundColor(mResources.getColor(R.color.unreadMessageBackgroundColor));
}
});
}
});
((DataViewHolder) holder).authorTextView.setOnClickListener(view -> {
if(message.wasComment()) {
if (message.wasComment()) {
Intent intent = new Intent(mContext, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, message.getAuthor());
mContext.startActivity(intent);
@ -179,7 +173,7 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
@Override
public int getItemCount() {
if(hasExtraRow()) {
if (hasExtraRow()) {
return super.getItemCount() + 1;
}
return super.getItemCount();
@ -188,7 +182,7 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if(holder instanceof DataViewHolder) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).itemView.setBackgroundColor(mResources.getColor(R.color.backgroundColor));
((DataViewHolder) holder).titleTextView.setVisibility(View.VISIBLE);
((DataViewHolder) holder).authorTextView.setTextColor(mResources.getColor(R.color.primaryTextColor));
@ -215,12 +209,20 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
}
}
public interface RetryLoadingMoreCallback {
void retryLoadingMore();
}
class DataViewHolder extends RecyclerView.ViewHolder {
View itemView;
@BindView(R.id.author_text_view_item_message) TextView authorTextView;
@BindView(R.id.subject_text_view_item_message) TextView subjectTextView;
@BindView(R.id.title_text_view_item_message) TextView titleTextView;
@BindView(R.id.content_custom_markwon_view_item_message) TextView contentCustomMarkwonView;
@BindView(R.id.author_text_view_item_message)
TextView authorTextView;
@BindView(R.id.subject_text_view_item_message)
TextView subjectTextView;
@BindView(R.id.title_text_view_item_message)
TextView titleTextView;
@BindView(R.id.content_custom_markwon_view_item_message)
TextView contentCustomMarkwonView;
DataViewHolder(View itemView) {
super(itemView);
@ -230,8 +232,10 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<Message, Recycl
}
class ErrorViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.error_text_view_item_footer_error) TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error) Button retryButton;
@BindView(R.id.error_text_view_item_footer_error)
TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error)
Button retryButton;
ErrorViewHolder(View itemView) {
super(itemView);

View File

@ -70,6 +70,22 @@ import retrofit2.Retrofit;
*/
public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1;
private static final int VIEW_TYPE_LOADING = 2;
private static final DiffUtil.ItemCallback<Post> DIFF_CALLBACK = new DiffUtil.ItemCallback<Post>() {
@Override
public boolean areItemsTheSame(@NonNull Post post, @NonNull Post t1) {
return post.getId().equals(t1.getId());
}
@Override
public boolean areContentsTheSame(@NonNull Post post, @NonNull Post t1) {
return post.getTitle().equals(t1.getTitle()) && !(post.getSelfText() != null && t1.getSelfText() != null
&& !post.getSelfText().equals(t1.getSelfText()))
&& post.getScore() == t1.getScore() && post.getVoteType() == t1.getVoteType();
}
};
private Context mContext;
private Retrofit mOauthRetrofit;
private Retrofit mRetrofit;
@ -82,25 +98,15 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
private boolean mDisplaySubredditName;
private boolean mNeedBlurNSFW;
private boolean mNeedBlurSpoiler;
private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1;
private static final int VIEW_TYPE_LOADING = 2;
private NetworkState networkState;
private Callback mCallback;
public interface Callback {
void retryLoadingMore();
void typeChipClicked(int filter);
}
public PostRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, Retrofit retrofit,
RedditDataRoomDatabase redditDataRoomDatabase, String accessToken,
int postType, boolean displaySubredditName, boolean needBlurNSFW,
boolean needBlurSpoiler, Callback callback) {
super(DIFF_CALLBACK);
if(context != null) {
if (context != null) {
mContext = context;
mOauthRetrofit = oauthRetrofit;
mRetrofit = retrofit;
@ -116,20 +122,6 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
}
private static final DiffUtil.ItemCallback<Post> DIFF_CALLBACK = new DiffUtil.ItemCallback<Post>() {
@Override
public boolean areItemsTheSame(@NonNull Post post, @NonNull Post t1) {
return post.getId().equals(t1.getId());
}
@Override
public boolean areContentsTheSame(@NonNull Post post, @NonNull Post t1) {
return post.getTitle().equals(t1.getTitle()) && !(post.getSelfText() != null && t1.getSelfText() != null
&& !post.getSelfText().equals(t1.getSelfText()))
&& post.getScore() == t1.getScore() && post.getVoteType() == t1.getVoteType();
}
};
public void setCanStartActivity(boolean canStartActivity) {
this.canStartActivity = canStartActivity;
}
@ -137,10 +129,10 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_DATA) {
if (viewType == VIEW_TYPE_DATA) {
CardView cardView = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post, parent, false);
return new DataViewHolder(cardView);
} else if(viewType == VIEW_TYPE_ERROR) {
} else if (viewType == VIEW_TYPE_ERROR) {
RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_error, parent, false);
return new ErrorViewHolder(relativeLayout);
} else {
@ -151,9 +143,9 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
if(holder instanceof DataViewHolder) {
if (holder instanceof DataViewHolder) {
Post post = getItem(position);
if(post != null) {
if (post != null) {
final String id = post.getFullName();
final String subredditNamePrefixed = post.getSubredditNamePrefixed();
String subredditName = subredditNamePrefixed.substring(2);
@ -169,7 +161,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
boolean isArchived = post.isArchived();
((DataViewHolder) holder).cardView.setOnClickListener(view -> {
if(canStartActivity) {
if (canStartActivity) {
canStartActivity = false;
Intent intent = new Intent(mContext, ViewPostDetailActivity.class);
@ -179,12 +171,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
});
if(mDisplaySubredditName) {
if(authorPrefixed.equals(subredditNamePrefixed)) {
if(post.getAuthorIconUrl() == null) {
if (mDisplaySubredditName) {
if (authorPrefixed.equals(subredditNamePrefixed)) {
if (post.getAuthorIconUrl() == null) {
new LoadUserDataAsyncTask(mUserDao, post.getAuthor(), mRetrofit, iconImageUrl -> {
if(mContext != null && getItemCount() > 0) {
if(iconImageUrl == null || iconImageUrl.equals("")) {
if (mContext != null && getItemCount() > 0) {
if (iconImageUrl == null || iconImageUrl.equals("")) {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((DataViewHolder) holder).iconGifImageView);
@ -196,12 +188,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
.into(((DataViewHolder) holder).iconGifImageView);
}
if(holder.getAdapterPosition() >= 0) {
if (holder.getAdapterPosition() >= 0) {
post.setAuthorIconUrl(iconImageUrl);
}
}
}).execute();
} else if(!post.getAuthorIconUrl().equals("")) {
} else if (!post.getAuthorIconUrl().equals("")) {
mGlide.load(post.getAuthorIconUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@ -213,11 +205,11 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
.into(((DataViewHolder) holder).iconGifImageView);
}
} else {
if(post.getSubredditIconUrl() == null) {
if (post.getSubredditIconUrl() == null) {
new LoadSubredditIconAsyncTask(mRedditDataRoomDatabase, subredditName, mRetrofit,
iconImageUrl -> {
if(mContext != null && getItemCount() > 0) {
if(iconImageUrl == null || iconImageUrl.equals("")) {
if (mContext != null && getItemCount() > 0) {
if (iconImageUrl == null || iconImageUrl.equals("")) {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((DataViewHolder) holder).iconGifImageView);
@ -229,12 +221,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
.into(((DataViewHolder) holder).iconGifImageView);
}
if(holder.getAdapterPosition() >= 0) {
if (holder.getAdapterPosition() >= 0) {
post.setSubredditIconUrl(iconImageUrl);
}
}
}).execute();
} else if(!post.getSubredditIconUrl().equals("")) {
} else if (!post.getSubredditIconUrl().equals("")) {
mGlide.load(post.getSubredditIconUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@ -251,9 +243,9 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).nameTextView.setText(subredditNamePrefixed);
((DataViewHolder) holder).iconNameLinearLayout.setOnClickListener(view -> {
if(canStartActivity) {
if (canStartActivity) {
canStartActivity = false;
if(post.getSubredditNamePrefixed().startsWith("u/")) {
if (post.getSubredditNamePrefixed().startsWith("u/")) {
Intent intent = new Intent(mContext, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY,
post.getSubredditNamePrefixed().substring(2));
@ -267,11 +259,11 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
});
} else {
if(post.getAuthorIconUrl() == null) {
if (post.getAuthorIconUrl() == null) {
String authorName = post.getAuthor().equals("[deleted]") ? post.getSubredditNamePrefixed().substring(2) : post.getAuthor();
new LoadUserDataAsyncTask(mUserDao, authorName, mRetrofit, iconImageUrl -> {
if(mContext != null && getItemCount() > 0) {
if(iconImageUrl == null || iconImageUrl.equals("")) {
if (mContext != null && getItemCount() > 0) {
if (iconImageUrl == null || iconImageUrl.equals("")) {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((DataViewHolder) holder).iconGifImageView);
@ -283,12 +275,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
.into(((DataViewHolder) holder).iconGifImageView);
}
if(holder.getAdapterPosition() >= 0) {
if (holder.getAdapterPosition() >= 0) {
post.setAuthorIconUrl(iconImageUrl);
}
}
}).execute();
} else if(!post.getAuthorIconUrl().equals("")) {
} else if (!post.getAuthorIconUrl().equals("")) {
mGlide.load(post.getAuthorIconUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@ -304,7 +296,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).nameTextView.setText(authorPrefixed);
((DataViewHolder) holder).iconNameLinearLayout.setOnClickListener(view -> {
if(canStartActivity) {
if (canStartActivity) {
canStartActivity = false;
Intent intent = new Intent(mContext, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, post.getAuthor());
@ -317,19 +309,19 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).titleTextView.setText(title);
((DataViewHolder) holder).scoreTextView.setText(Integer.toString(post.getScore() + post.getVoteType()));
if(gilded > 0) {
if (gilded > 0) {
((DataViewHolder) holder).gildedImageView.setVisibility(View.VISIBLE);
((DataViewHolder) holder).gildedNumberTextView.setVisibility(View.VISIBLE);
String gildedNumber = mContext.getResources().getString(R.string.gilded_count, gilded);
((DataViewHolder) holder).gildedNumberTextView.setText(gildedNumber);
}
if(post.isLocked()) {
if (post.isLocked()) {
((DataViewHolder) holder).lockedImageView.setVisibility(View.VISIBLE);
}
if(nsfw) {
if(!(mContext instanceof FilteredThingActivity)) {
if (nsfw) {
if (!(mContext instanceof FilteredThingActivity)) {
((DataViewHolder) holder).nsfwTextView.setOnClickListener(view -> {
Intent intent = new Intent(mContext, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, post.getSubredditNamePrefixed().substring(2));
@ -342,15 +334,15 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE);
}
if(spoiler || flair != null) {
if (spoiler || flair != null) {
((DataViewHolder) holder).spoilerFlairLinearLayout.setVisibility(View.VISIBLE);
}
if(spoiler) {
if (spoiler) {
((DataViewHolder) holder).spoilerTextView.setVisibility(View.VISIBLE);
}
if(flair != null) {
if (flair != null) {
((DataViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
((DataViewHolder) holder).flairTextView.setText(flair);
}
@ -368,7 +360,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
break;
}
if(post.getPostType() != Post.TEXT_TYPE && post.getPostType() != Post.NO_PREVIEW_LINK_TYPE) {
if (post.getPostType() != Post.TEXT_TYPE && post.getPostType() != Post.NO_PREVIEW_LINK_TYPE) {
((DataViewHolder) holder).relativeLayout.setVisibility(View.VISIBLE);
((DataViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
((DataViewHolder) holder).imageView.setVisibility(View.VISIBLE);
@ -377,12 +369,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
loadImage(holder, post);
}
if(mPostType == PostDataSource.TYPE_SUBREDDIT && !mDisplaySubredditName && post.isStickied()) {
if (mPostType == PostDataSource.TYPE_SUBREDDIT && !mDisplaySubredditName && post.isStickied()) {
((DataViewHolder) holder).stickiedPostImageView.setVisibility(View.VISIBLE);
mGlide.load(R.drawable.ic_thumbtack_24dp).into(((DataViewHolder) holder).stickiedPostImageView);
}
if(isArchived) {
if (isArchived) {
((DataViewHolder) holder).archivedImageView.setVisibility(View.VISIBLE);
((DataViewHolder) holder).upvoteButton
@ -391,11 +383,11 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
.setColorFilter(ContextCompat.getColor(mContext, R.color.voteAndReplyUnavailableVoteButtonColor), android.graphics.PorterDuff.Mode.SRC_IN);
}
if(post.isCrosspost()) {
if (post.isCrosspost()) {
((DataViewHolder) holder).crosspostImageView.setVisibility(View.VISIBLE);
}
if(!(mContext instanceof FilteredThingActivity)) {
if (!(mContext instanceof FilteredThingActivity)) {
((DataViewHolder) holder).typeTextView.setOnClickListener(view -> mCallback.typeChipClicked(post.getPostType()));
}
@ -423,7 +415,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).imageView.setOnClickListener(view -> {
Intent intent = new Intent(mContext, LinkResolverActivity.class);
Uri uri = Uri.parse(post.getUrl());
if(uri.getScheme() == null && uri.getHost() == null) {
if (uri.getScheme() == null && uri.getHost() == null) {
intent.setData(LinkResolverActivity.getRedditUriByPath(post.getUrl()));
} else {
intent.setData(uri);
@ -468,7 +460,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).noPreviewLinkImageView.setOnClickListener(view -> {
Intent intent = new Intent(mContext, LinkResolverActivity.class);
Uri uri = Uri.parse(post.getUrl());
if(uri.getScheme() == null && uri.getHost() == null) {
if (uri.getScheme() == null && uri.getHost() == null) {
intent.setData(LinkResolverActivity.getRedditUriByPath(post.getUrl()));
} else {
intent.setData(uri);
@ -482,12 +474,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
((DataViewHolder) holder).upvoteButton.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(mContext, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
if(isArchived) {
if (isArchived) {
Toast.makeText(mContext, R.string.archived_post_vote_unavailable, Toast.LENGTH_SHORT).show();
return;
}
@ -501,7 +493,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).downvoteButton.clearColorFilter();
if(previousUpvoteButtonColorFilter == null) {
if (previousUpvoteButtonColorFilter == null) {
//Not upvoted before
post.setVoteType(1);
newVoteType = RedditUtils.DIR_UPVOTE;
@ -521,7 +513,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position1) {
if(newVoteType.equals(RedditUtils.DIR_UPVOTE)) {
if (newVoteType.equals(RedditUtils.DIR_UPVOTE)) {
post.setVoteType(1);
((DataViewHolder) holder).upvoteButton
.setColorFilter(ContextCompat.getColor(mContext, R.color.upvoted), android.graphics.PorterDuff.Mode.SRC_IN);
@ -553,12 +545,12 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
});
((DataViewHolder) holder).downvoteButton.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(mContext, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
if(isArchived) {
if (isArchived) {
Toast.makeText(mContext, R.string.archived_post_vote_unavailable, Toast.LENGTH_SHORT).show();
return;
}
@ -572,7 +564,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).upvoteButton.clearColorFilter();
if(previousDownvoteButtonColorFilter == null) {
if (previousDownvoteButtonColorFilter == null) {
//Not downvoted before
post.setVoteType(-1);
newVoteType = RedditUtils.DIR_DOWNVOTE;
@ -592,7 +584,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
VoteThing.voteThing(mOauthRetrofit, mAccessToken, new VoteThing.VoteThingListener() {
@Override
public void onVoteThingSuccess(int position1) {
if(newVoteType.equals(RedditUtils.DIR_DOWNVOTE)) {
if (newVoteType.equals(RedditUtils.DIR_DOWNVOTE)) {
post.setVoteType(-1);
((DataViewHolder) holder).downvoteButton
.setColorFilter(ContextCompat.getColor(mContext, R.color.downvoted), android.graphics.PorterDuff.Mode.SRC_IN);
@ -624,7 +616,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
});
((DataViewHolder) holder).commentButton.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(mContext, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
@ -639,19 +631,19 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).commentsCountTextView.setText(Integer.toString(post.getnComments()));
if(post.isSaved()) {
if (post.isSaved()) {
((DataViewHolder) holder).saveButton.setImageResource(R.drawable.ic_baseline_bookmark_24px);
} else {
((DataViewHolder) holder).saveButton.setImageResource(R.drawable.ic_baseline_bookmark_border_24px);
}
((DataViewHolder) holder).saveButton.setOnClickListener(view -> {
if(mAccessToken == null) {
if (mAccessToken == null) {
Toast.makeText(mContext, R.string.login_first, Toast.LENGTH_SHORT).show();
return;
}
if(post.isSaved()) {
if (post.isSaved()) {
((DataViewHolder) holder).saveButton.setImageResource(R.drawable.ic_baseline_bookmark_border_24px);
SaveThing.unsaveThing(mOauthRetrofit, mAccessToken, post.getFullName(),
new SaveThing.SaveThingListener() {
@ -715,7 +707,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
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(view -> {
((DataViewHolder) holder).errorRelativeLayout.setOnClickListener(view -> {
((DataViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
((DataViewHolder) holder).errorRelativeLayout.setVisibility(View.GONE);
loadImage(holder, post);
@ -731,7 +723,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
});
if((post.isNSFW() && mNeedBlurNSFW) || post.isSpoiler() && mNeedBlurSpoiler) {
if ((post.isNSFW() && mNeedBlurNSFW) || post.isSpoiler() && mNeedBlurSpoiler) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 2)))
.into(((DataViewHolder) holder).imageView);
} else {
@ -755,7 +747,7 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
@Override
public int getItemCount() {
if(hasExtraRow()) {
if (hasExtraRow()) {
return super.getItemCount() + 1;
}
return super.getItemCount();
@ -789,69 +781,9 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
}
}
class DataViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.card_view_item_post) MaterialCardView cardView;
@BindView(R.id.icon_name_linear_layout_view_item_post) LinearLayout iconNameLinearLayout;
@BindView(R.id.icon_gif_image_view_item_post) AspectRatioGifImageView iconGifImageView;
@BindView(R.id.name_text_view_item_post) TextView nameTextView;
@BindView(R.id.stickied_post_image_view_item_post) ImageView stickiedPostImageView;
@BindView(R.id.post_time_text_view_best_item_post) TextView postTimeTextView;
@BindView(R.id.title_text_view_best_item_post) TextView titleTextView;
@BindView(R.id.type_text_view_item_post) CustomTextView typeTextView;
@BindView(R.id.gilded_image_view_item_post) ImageView gildedImageView;
@BindView(R.id.gilded_number_text_view_item_post) TextView gildedNumberTextView;
@BindView(R.id.archived_image_view_item_post) ImageView archivedImageView;
@BindView(R.id.locked_image_view_item_post) ImageView lockedImageView;
@BindView(R.id.crosspost_image_view_item_post) ImageView crosspostImageView;
@BindView(R.id.nsfw_text_view_item_post) CustomTextView nsfwTextView;
@BindView(R.id.spoiler_flair_linear_layout_item_post) LinearLayout spoilerFlairLinearLayout;
@BindView(R.id.spoiler_custom_text_view_item_post) CustomTextView spoilerTextView;
@BindView(R.id.flair_custom_text_view_item_post) CustomTextView flairTextView;
@BindView(R.id.link_text_view_item_post) TextView linkTextView;
@BindView(R.id.image_view_wrapper_item_post) RelativeLayout relativeLayout;
@BindView(R.id.progress_bar_item_post) ProgressBar progressBar;
@BindView(R.id.image_view_best_post_item) AspectRatioGifImageView imageView;
@BindView(R.id.load_image_error_relative_layout_item_post) RelativeLayout errorRelativeLayout;
@BindView(R.id.image_view_no_preview_link_item_post) ImageView noPreviewLinkImageView;
@BindView(R.id.plus_button_item_post) ImageView upvoteButton;
@BindView(R.id.score_text_view_item_post) TextView scoreTextView;
@BindView(R.id.minus_button_item_post) ImageView downvoteButton;
@BindView(R.id.comment_button_item_post) ImageView commentButton;
@BindView(R.id.comments_count_item_post) TextView commentsCountTextView;
@BindView(R.id.save_button_item_post) ImageView saveButton;
@BindView(R.id.share_button_item_post) ImageView shareButton;
DataViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
scoreTextView.setOnClickListener(view -> {
//Do nothing in order to prevent clicking this to start ViewPostDetailActivity
});
}
}
class ErrorViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.error_text_view_item_footer_error) TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error) Button retryButton;
ErrorViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
errorTextView.setText(R.string.load_posts_error);
retryButton.setOnClickListener(view -> mCallback.retryLoadingMore());
}
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
LoadingViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if(holder instanceof DataViewHolder) {
if (holder instanceof DataViewHolder) {
mGlide.clear(((DataViewHolder) holder).imageView);
mGlide.clear(((DataViewHolder) holder).iconGifImageView);
((DataViewHolder) holder).stickiedPostImageView.setVisibility(View.GONE);
@ -875,4 +807,102 @@ public class PostRecyclerViewAdapter extends PagedListAdapter<Post, RecyclerView
((DataViewHolder) holder).downvoteButton.clearColorFilter();
}
}
public interface Callback {
void retryLoadingMore();
void typeChipClicked(int filter);
}
class DataViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.card_view_item_post)
MaterialCardView cardView;
@BindView(R.id.icon_name_linear_layout_view_item_post)
LinearLayout iconNameLinearLayout;
@BindView(R.id.icon_gif_image_view_item_post)
AspectRatioGifImageView iconGifImageView;
@BindView(R.id.name_text_view_item_post)
TextView nameTextView;
@BindView(R.id.stickied_post_image_view_item_post)
ImageView stickiedPostImageView;
@BindView(R.id.post_time_text_view_best_item_post)
TextView postTimeTextView;
@BindView(R.id.title_text_view_best_item_post)
TextView titleTextView;
@BindView(R.id.type_text_view_item_post)
CustomTextView typeTextView;
@BindView(R.id.gilded_image_view_item_post)
ImageView gildedImageView;
@BindView(R.id.gilded_number_text_view_item_post)
TextView gildedNumberTextView;
@BindView(R.id.archived_image_view_item_post)
ImageView archivedImageView;
@BindView(R.id.locked_image_view_item_post)
ImageView lockedImageView;
@BindView(R.id.crosspost_image_view_item_post)
ImageView crosspostImageView;
@BindView(R.id.nsfw_text_view_item_post)
CustomTextView nsfwTextView;
@BindView(R.id.spoiler_flair_linear_layout_item_post)
LinearLayout spoilerFlairLinearLayout;
@BindView(R.id.spoiler_custom_text_view_item_post)
CustomTextView spoilerTextView;
@BindView(R.id.flair_custom_text_view_item_post)
CustomTextView flairTextView;
@BindView(R.id.link_text_view_item_post)
TextView linkTextView;
@BindView(R.id.image_view_wrapper_item_post)
RelativeLayout relativeLayout;
@BindView(R.id.progress_bar_item_post)
ProgressBar progressBar;
@BindView(R.id.image_view_best_post_item)
AspectRatioGifImageView imageView;
@BindView(R.id.load_image_error_relative_layout_item_post)
RelativeLayout errorRelativeLayout;
@BindView(R.id.image_view_no_preview_link_item_post)
ImageView noPreviewLinkImageView;
@BindView(R.id.plus_button_item_post)
ImageView upvoteButton;
@BindView(R.id.score_text_view_item_post)
TextView scoreTextView;
@BindView(R.id.minus_button_item_post)
ImageView downvoteButton;
@BindView(R.id.comment_button_item_post)
ImageView commentButton;
@BindView(R.id.comments_count_item_post)
TextView commentsCountTextView;
@BindView(R.id.save_button_item_post)
ImageView saveButton;
@BindView(R.id.share_button_item_post)
ImageView shareButton;
DataViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
scoreTextView.setOnClickListener(view -> {
//Do nothing in order to prevent clicking this to start ViewPostDetailActivity
});
}
}
class ErrorViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.error_text_view_item_footer_error)
TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error)
Button retryButton;
ErrorViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
errorTextView.setText(R.string.load_posts_error);
retryButton.setOnClickListener(view -> mCallback.retryLoadingMore());
}
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
LoadingViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}

View File

@ -37,7 +37,7 @@ public class RulesRecyclerViewAdapter extends RecyclerView.Adapter<RulesRecycler
builder.linkResolver((view, link) -> {
Intent intent = new Intent(context, LinkResolverActivity.class);
Uri uri = Uri.parse(link);
if(uri.getScheme() == null && uri.getHost() == null) {
if (uri.getScheme() == null && uri.getHost() == null) {
intent.setData(LinkResolverActivity.getRedditUriByPath(link));
} else {
intent.setData(uri);
@ -60,7 +60,7 @@ public class RulesRecyclerViewAdapter extends RecyclerView.Adapter<RulesRecycler
@Override
public void onBindViewHolder(@NonNull RuleViewHolder holder, int position) {
holder.shortNameTextView.setText(rules.get(holder.getAdapterPosition()).getShortName());
if(rules.get(holder.getAdapterPosition()).getDescriptionHtml() == null) {
if (rules.get(holder.getAdapterPosition()).getDescriptionHtml() == null) {
holder.descriptionMarkwonView.setVisibility(View.GONE);
} else {
markwon.setMarkdown(holder.descriptionMarkwonView, rules.get(holder.getAdapterPosition()).getDescriptionHtml());
@ -84,8 +84,10 @@ public class RulesRecyclerViewAdapter extends RecyclerView.Adapter<RulesRecycler
}
class RuleViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.short_name_text_view_item_rule) TextView shortNameTextView;
@BindView(R.id.description_markwon_view_item_rule) TextView descriptionMarkwonView;
@BindView(R.id.short_name_text_view_item_rule)
TextView shortNameTextView;
@BindView(R.id.description_markwon_view_item_rule)
TextView descriptionMarkwonView;
RuleViewHolder(@NonNull View itemView) {
super(itemView);

View File

@ -33,17 +33,21 @@ import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<SubredditData, RecyclerView.ViewHolder> {
public interface Callback {
void retryLoadingMore();
void subredditSelected(String subredditName, String iconUrl);
}
private RequestManager glide;
private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1;
private static final int VIEW_TYPE_LOADING = 2;
private static final DiffUtil.ItemCallback<SubredditData> DIFF_CALLBACK = new DiffUtil.ItemCallback<SubredditData>() {
@Override
public boolean areItemsTheSame(@NonNull SubredditData oldItem, @NonNull SubredditData newItem) {
return oldItem.getId().equals(newItem.getId());
}
@Override
public boolean areContentsTheSame(@NonNull SubredditData oldItem, @NonNull SubredditData newItem) {
return true;
}
};
private RequestManager glide;
private Context context;
private Retrofit oauthRetrofit;
private Retrofit retrofit;
@ -69,25 +73,13 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
glide = Glide.with(context.getApplicationContext());
}
private static final DiffUtil.ItemCallback<SubredditData> DIFF_CALLBACK = new DiffUtil.ItemCallback<SubredditData>() {
@Override
public boolean areItemsTheSame(@NonNull SubredditData oldItem, @NonNull SubredditData newItem) {
return oldItem.getId().equals(newItem.getId());
}
@Override
public boolean areContentsTheSame(@NonNull SubredditData oldItem, @NonNull SubredditData newItem) {
return true;
}
};
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_DATA) {
if (viewType == VIEW_TYPE_DATA) {
ConstraintLayout constraintLayout = (ConstraintLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_subreddit_listing, parent, false);
return new DataViewHolder(constraintLayout);
} else if(viewType == VIEW_TYPE_ERROR) {
} else if (viewType == VIEW_TYPE_ERROR) {
RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_error, parent, false);
return new ErrorViewHolder(relativeLayout);
} else {
@ -98,12 +90,12 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof DataViewHolder) {
if (holder instanceof DataViewHolder) {
SubredditData subredditData = getItem(position);
((DataViewHolder) holder).constraintLayout.setOnClickListener(view ->
callback.subredditSelected(subredditData.getName(), subredditData.getIconUrl()));
if(!subredditData.getIconUrl().equals("")) {
if (!subredditData.getIconUrl().equals("")) {
glide.load(subredditData.getIconUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
@ -164,7 +156,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
@Override
public int getItemCount() {
if(hasExtraRow()) {
if (hasExtraRow()) {
return super.getItemCount() + 1;
}
return super.getItemCount();
@ -190,11 +182,29 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
}
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if (holder instanceof DataViewHolder) {
glide.clear(((DataViewHolder) holder).iconGifImageView);
((DataViewHolder) holder).subscribeButton.setVisibility(View.GONE);
}
}
public interface Callback {
void retryLoadingMore();
void subredditSelected(String subredditName, String iconUrl);
}
class DataViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.constraint_layout_item_subreddit_listing) ConstraintLayout constraintLayout;
@BindView(R.id.subreddit_icon_gif_image_view_item_subreddit_listing) GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_item_subreddit_listing) TextView subredditNameTextView;
@BindView(R.id.subscribe_image_view_item_subreddit_listing) ImageView subscribeButton;
@BindView(R.id.constraint_layout_item_subreddit_listing)
ConstraintLayout constraintLayout;
@BindView(R.id.subreddit_icon_gif_image_view_item_subreddit_listing)
GifImageView iconGifImageView;
@BindView(R.id.subreddit_name_text_view_item_subreddit_listing)
TextView subredditNameTextView;
@BindView(R.id.subscribe_image_view_item_subreddit_listing)
ImageView subscribeButton;
DataViewHolder(View itemView) {
super(itemView);
@ -203,8 +213,10 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
}
class ErrorViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.error_text_view_item_footer_error) TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error) Button retryButton;
@BindView(R.id.error_text_view_item_footer_error)
TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error)
Button retryButton;
ErrorViewHolder(View itemView) {
super(itemView);
@ -220,12 +232,4 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
ButterKnife.bind(this, itemView);
}
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if(holder instanceof DataViewHolder) {
glide.clear(((DataViewHolder) holder).iconGifImageView);
((DataViewHolder) holder).subscribeButton.setVisibility(View.GONE);
}
}
}

View File

@ -16,10 +16,10 @@ import com.bumptech.glide.request.RequestOptions;
import java.util.List;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.Activity.ViewSubredditDetailActivity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.SubscribedSubredditDatabase.SubscribedSubredditData;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import pl.droidsonroids.gif.GifImageView;
public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@ -32,10 +32,6 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
private String userIconUrl;
private boolean hasClearSelectionRow;
public interface ItemClickListener {
void onClick(String name, String iconUrl, boolean subredditIsUser);
}
public SubscribedSubredditsRecyclerViewAdapter(Context context) {
mContext = context;
glide = Glide.with(context.getApplicationContext());
@ -59,13 +55,13 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
String name;
String iconUrl;
if(itemClickListener != null) {
if(hasClearSelectionRow) {
if(viewHolder.getAdapterPosition() == 0) {
if (itemClickListener != null) {
if (hasClearSelectionRow) {
if (viewHolder.getAdapterPosition() == 0) {
((SubredditViewHolder) viewHolder).subredditNameTextView.setText(R.string.all_subreddits);
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(null, null, false));
return;
} else if(viewHolder.getAdapterPosition() == 1) {
} else if (viewHolder.getAdapterPosition() == 1) {
name = username;
iconUrl = userIconUrl;
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, true));
@ -75,7 +71,7 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, false));
}
} else {
if(viewHolder.getAdapterPosition() == 0) {
if (viewHolder.getAdapterPosition() == 0) {
name = username;
iconUrl = userIconUrl;
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, true));
@ -96,7 +92,7 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
});
}
if(iconUrl != null && !iconUrl.equals("")) {
if (iconUrl != null && !iconUrl.equals("")) {
glide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
@ -112,9 +108,9 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
@Override
public int getItemCount() {
if(mSubscribedSubredditData != null) {
if(itemClickListener != null) {
if(hasClearSelectionRow) {
if (mSubscribedSubredditData != null) {
if (itemClickListener != null) {
if (hasClearSelectionRow) {
return mSubscribedSubredditData.size() + 2;
} else {
return mSubscribedSubredditData.size() + 1;
@ -131,7 +127,7 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
glide.clear(((SubredditViewHolder) holder).iconGifImageView);
}
public void setSubscribedSubreddits(List<SubscribedSubredditData> subscribedSubreddits){
public void setSubscribedSubreddits(List<SubscribedSubredditData> subscribedSubreddits) {
mSubscribedSubredditData = subscribedSubreddits;
notifyDataSetChanged();
}
@ -141,6 +137,10 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
this.userIconUrl = userIconUrl;
}
public interface ItemClickListener {
void onClick(String name, String iconUrl, boolean subredditIsUser);
}
private class SubredditViewHolder extends RecyclerView.ViewHolder {
private final GifImageView iconGifImageView;
private final TextView subredditNameTextView;

View File

@ -21,54 +21,23 @@ import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.Activity.ViewUserDetailActivity;
import ml.docilealligator.infinityforreddit.AsyncTask.CheckIsFollowingUserAsyncTask;
import ml.docilealligator.infinityforreddit.NetworkState;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.SubscribedUserDatabase.SubscribedUserDao;
import ml.docilealligator.infinityforreddit.User.UserData;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import ml.docilealligator.infinityforreddit.UserFollowing;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, RecyclerView.ViewHolder> {
public interface RetryLoadingMoreCallback {
void retryLoadingMore();
}
private RequestManager glide;
private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1;
private static final int VIEW_TYPE_LOADING = 2;
private Context context;
private Retrofit oauthRetrofit;
private Retrofit retrofit;
private String accessToken;
private String accountName;
private SubscribedUserDao subscribedUserDao;
private NetworkState networkState;
private UserListingRecyclerViewAdapter.RetryLoadingMoreCallback retryLoadingMoreCallback;
public UserListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, Retrofit retrofit,
String accessToken, String accountName, SubscribedUserDao subscribedUserDao,
UserListingRecyclerViewAdapter.RetryLoadingMoreCallback retryLoadingMoreCallback) {
super(DIFF_CALLBACK);
this.context = context;
this.oauthRetrofit = oauthRetrofit;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.subscribedUserDao = subscribedUserDao;
this.retryLoadingMoreCallback = retryLoadingMoreCallback;
glide = Glide.with(context.getApplicationContext());
}
private static final DiffUtil.ItemCallback<UserData> DIFF_CALLBACK = new DiffUtil.ItemCallback<UserData>() {
@Override
public boolean areItemsTheSame(@NonNull UserData oldItem, @NonNull UserData newItem) {
@ -80,14 +49,38 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R
return true;
}
};
private RequestManager glide;
private Context context;
private Retrofit oauthRetrofit;
private Retrofit retrofit;
private String accessToken;
private String accountName;
private SubscribedUserDao subscribedUserDao;
private NetworkState networkState;
private UserListingRecyclerViewAdapter.RetryLoadingMoreCallback retryLoadingMoreCallback;
public UserListingRecyclerViewAdapter(Context context, Retrofit oauthRetrofit, Retrofit retrofit,
String accessToken, String accountName, SubscribedUserDao subscribedUserDao,
UserListingRecyclerViewAdapter.RetryLoadingMoreCallback retryLoadingMoreCallback) {
super(DIFF_CALLBACK);
this.context = context;
this.oauthRetrofit = oauthRetrofit;
this.retrofit = retrofit;
this.accessToken = accessToken;
this.accountName = accountName;
this.subscribedUserDao = subscribedUserDao;
this.retryLoadingMoreCallback = retryLoadingMoreCallback;
glide = Glide.with(context.getApplicationContext());
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_DATA) {
if (viewType == VIEW_TYPE_DATA) {
ConstraintLayout constraintLayout = (ConstraintLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user_listing, parent, false);
return new UserListingRecyclerViewAdapter.DataViewHolder(constraintLayout);
} else if(viewType == VIEW_TYPE_ERROR) {
} else if (viewType == VIEW_TYPE_ERROR) {
RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_error, parent, false);
return new UserListingRecyclerViewAdapter.ErrorViewHolder(relativeLayout);
} else {
@ -98,7 +91,7 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof UserListingRecyclerViewAdapter.DataViewHolder) {
if (holder instanceof UserListingRecyclerViewAdapter.DataViewHolder) {
UserData userData = getItem(position);
((UserListingRecyclerViewAdapter.DataViewHolder) holder).constraintLayout.setOnClickListener(view -> {
Intent intent = new Intent(context, ViewUserDetailActivity.class);
@ -106,7 +99,7 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R
context.startActivity(intent);
});
if(!userData.getIconUrl().equals("")) {
if (!userData.getIconUrl().equals("")) {
glide.load(userData.getIconUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
@ -167,7 +160,7 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R
@Override
public int getItemCount() {
if(hasExtraRow()) {
if (hasExtraRow()) {
return super.getItemCount() + 1;
}
return super.getItemCount();
@ -193,11 +186,27 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R
}
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if (holder instanceof UserListingRecyclerViewAdapter.DataViewHolder) {
glide.clear(((UserListingRecyclerViewAdapter.DataViewHolder) holder).iconGifImageView);
((UserListingRecyclerViewAdapter.DataViewHolder) holder).subscribeButton.setVisibility(View.GONE);
}
}
public interface RetryLoadingMoreCallback {
void retryLoadingMore();
}
class DataViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.constraint_layout_item_user_listing) ConstraintLayout constraintLayout;
@BindView(R.id.user_icon_gif_image_view_item_user_listing) GifImageView iconGifImageView;
@BindView(R.id.user_name_text_view_item_user_listing) TextView UserNameTextView;
@BindView(R.id.subscribe_image_view_item_user_listing) ImageView subscribeButton;
@BindView(R.id.constraint_layout_item_user_listing)
ConstraintLayout constraintLayout;
@BindView(R.id.user_icon_gif_image_view_item_user_listing)
GifImageView iconGifImageView;
@BindView(R.id.user_name_text_view_item_user_listing)
TextView UserNameTextView;
@BindView(R.id.subscribe_image_view_item_user_listing)
ImageView subscribeButton;
DataViewHolder(View itemView) {
super(itemView);
@ -206,8 +215,10 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R
}
class ErrorViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.error_text_view_item_footer_error) TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error) Button retryButton;
@BindView(R.id.error_text_view_item_footer_error)
TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error)
Button retryButton;
ErrorViewHolder(View itemView) {
super(itemView);
@ -223,12 +234,4 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R
ButterKnife.bind(this, itemView);
}
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if(holder instanceof UserListingRecyclerViewAdapter.DataViewHolder) {
glide.clear(((UserListingRecyclerViewAdapter.DataViewHolder) holder).iconGifImageView);
((UserListingRecyclerViewAdapter.DataViewHolder) holder).subscribeButton.setVisibility(View.GONE);
}
}
}

View File

@ -3,13 +3,6 @@ package ml.docilealligator.infinityforreddit;
import com.google.android.material.appbar.AppBarLayout;
public abstract class AppBarStateChangeListener implements AppBarLayout.OnOffsetChangedListener {
// State
public enum State {
EXPANDED,
COLLAPSED,
IDLE
}
private AppBarStateChangeListener.State mCurrentState = AppBarStateChangeListener.State.IDLE;
@Override
@ -34,8 +27,16 @@ public abstract class AppBarStateChangeListener implements AppBarLayout.OnOffset
/**
* Notifies on state change
*
* @param appBarLayout Layout
* @param state Collapse state
* @param state Collapse state
*/
public abstract void onStateChanged(AppBarLayout appBarLayout, AppBarStateChangeListener.State state);
// State
public enum State {
EXPANDED,
COLLAPSED,
IDLE
}
}

View File

@ -2,6 +2,7 @@ package ml.docilealligator.infinityforreddit;
import javax.inject.Singleton;
import dagger.Component;
import ml.docilealligator.infinityforreddit.Activity.AccountPostsActivity;
import ml.docilealligator.infinityforreddit.Activity.AccountSavedThingActivity;
import ml.docilealligator.infinityforreddit.Activity.CommentActivity;
@ -36,45 +37,79 @@ import ml.docilealligator.infinityforreddit.Fragment.SubscribedSubredditsListing
import ml.docilealligator.infinityforreddit.Fragment.UserListingFragment;
import ml.docilealligator.infinityforreddit.Settings.MainPreferenceFragment;
import ml.docilealligator.infinityforreddit.Settings.NotificationPreferenceFragment;
import dagger.Component;
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
void inject(MainActivity mainActivity);
void inject(LoginActivity loginActivity);
void inject(PostFragment postFragment);
void inject(SubredditListingFragment subredditListingFragment);
void inject(UserListingFragment userListingFragment);
void inject(ViewPostDetailActivity viewPostDetailActivity);
void inject(ViewSubredditDetailActivity viewSubredditDetailActivity);
void inject(ViewUserDetailActivity viewUserDetailActivity);
void inject(CommentActivity commentActivity);
void inject(SubscribedThingListingActivity subscribedThingListingActivity);
void inject(PostTextActivity postTextActivity);
void inject(SubscribedSubredditsListingFragment subscribedSubredditsListingFragment);
void inject(PostLinkActivity postLinkActivity);
void inject(PostImageActivity postImageActivity);
void inject(PostVideoActivity postVideoActivity);
void inject(FlairBottomSheetFragment flairBottomSheetFragment);
void inject(RulesActivity rulesActivity);
void inject(CommentsListingFragment commentsListingFragment);
void inject(SubmitPostService submitPostService);
void inject(FilteredThingActivity filteredPostsActivity);
void inject(SearchResultActivity searchResultActivity);
void inject(SearchSubredditsResultActivity searchSubredditsResultActivity);
void inject(FollowedUsersListingFragment followedUsersListingFragment);
void inject(SubredditSelectionActivity subredditSelectionActivity);
void inject(EditPostActivity editPostActivity);
void inject(EditCommentActivity editCommentActivity);
void inject(AccountPostsActivity accountPostsActivity);
void inject(PullNotificationWorker pullNotificationWorker);
void inject(ViewMessageActivity viewMessageActivity);
void inject(NotificationPreferenceFragment notificationPreferenceFragment);
void inject(LinkResolverActivity linkResolverActivity);
void inject(SearchActivity searchActivity);
void inject(SettingsActivity settingsActivity);
void inject(MainPreferenceFragment mainPreferenceFragment);
void inject(AccountSavedThingActivity accountSavedThingActivity);
void inject(ViewImageActivity viewImageActivity);
}

View File

@ -22,7 +22,8 @@ class AppModule {
mApplication = application;
}
@Provides @Named("oauth")
@Provides
@Named("oauth")
@Singleton
Retrofit provideOauthRetrofit(OkHttpClient okHttpClient) {
return new Retrofit.Builder()
@ -32,7 +33,8 @@ class AppModule {
.build();
}
@Provides @Named("oauth_without_authenticator")
@Provides
@Named("oauth_without_authenticator")
@Singleton
Retrofit provideOauthWithoutAuthenticatorRetrofit() {
return new Retrofit.Builder()
@ -41,7 +43,8 @@ class AppModule {
.build();
}
@Provides @Named("no_oauth")
@Provides
@Named("no_oauth")
@Singleton
Retrofit provideRetrofit() {
return new Retrofit.Builder()
@ -50,7 +53,8 @@ class AppModule {
.build();
}
@Provides @Named("upload_media")
@Provides
@Named("upload_media")
@Singleton
Retrofit provideUploadMediaRetrofit() {
return new Retrofit.Builder()
@ -59,7 +63,8 @@ class AppModule {
.build();
}
@Provides @Named("upload_video")
@Provides
@Named("upload_video")
@Singleton
Retrofit provideUploadVideoRetrofit() {
return new Retrofit.Builder()

View File

@ -12,11 +12,6 @@ public class CheckIsFollowingUserAsyncTask extends AsyncTask<Void, Void, Void> {
private SubscribedUserData subscribedUserData;
private CheckIsFollowingUserListener checkIsFollowingUserListener;
public interface CheckIsFollowingUserListener {
void isSubscribed();
void isNotSubscribed();
}
public CheckIsFollowingUserAsyncTask(SubscribedUserDao subscribedUserDao, String username, String accountName,
CheckIsFollowingUserListener checkIsFollowingUserListener) {
this.subscribedUserDao = subscribedUserDao;
@ -34,10 +29,16 @@ public class CheckIsFollowingUserAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(subscribedUserData != null) {
if (subscribedUserData != null) {
checkIsFollowingUserListener.isSubscribed();
} else {
checkIsFollowingUserListener.isNotSubscribed();
}
}
public interface CheckIsFollowingUserListener {
void isSubscribed();
void isNotSubscribed();
}
}

View File

@ -13,16 +13,11 @@ public class CheckIsSubscribedToSubredditAsyncTask extends AsyncTask<Void, Void,
private SubscribedSubredditData subscribedSubredditData;
private CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener;
public interface CheckIsSubscribedToSubredditListener {
void isSubscribed();
void isNotSubscribed();
}
public CheckIsSubscribedToSubredditAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase,
String subredditName, String accountName,
CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener) {
String subredditName, String accountName,
CheckIsSubscribedToSubredditListener checkIsSubscribedToSubredditListener) {
this.redditDataRoomDatabase = redditDataRoomDatabase;
this.subredditName =subredditName;
this.subredditName = subredditName;
this.accountName = accountName;
this.checkIsSubscribedToSubredditListener = checkIsSubscribedToSubredditListener;
}
@ -36,10 +31,16 @@ public class CheckIsSubscribedToSubredditAsyncTask extends AsyncTask<Void, Void,
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(subscribedSubredditData != null) {
if (subscribedSubredditData != null) {
checkIsSubscribedToSubredditListener.isSubscribed();
} else {
checkIsSubscribedToSubredditListener.isNotSubscribed();
}
}
public interface CheckIsSubscribedToSubredditListener {
void isSubscribed();
void isNotSubscribed();
}
}

View File

@ -7,14 +7,9 @@ import ml.docilealligator.infinityforreddit.Account.AccountDao;
public class GetCurrentAccountAsyncTask extends AsyncTask<Void, Void, Void> {
public interface GetCurrentAccountAsyncTaskListener {
void success(Account account);
}
Account account;
AccountDao accountDao;
GetCurrentAccountAsyncTaskListener getCurrentAccountAsyncTaskListener;
public GetCurrentAccountAsyncTask(AccountDao accountDao, GetCurrentAccountAsyncTaskListener getCurrentAccountAsyncTaskListener) {
this.accountDao = accountDao;
this.getCurrentAccountAsyncTaskListener = getCurrentAccountAsyncTaskListener;
@ -30,4 +25,8 @@ public class GetCurrentAccountAsyncTask extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void aVoid) {
getCurrentAccountAsyncTaskListener.success(account);
}
public interface GetCurrentAccountAsyncTaskListener {
void success(Account account);
}
}

View File

@ -16,10 +16,6 @@ import ml.docilealligator.infinityforreddit.SubscribedUserDatabase.SubscribedUse
public class InsertSubscribedThingsAsyncTask extends AsyncTask<Void, Void, Void> {
public interface InsertSubscribedThingListener {
void insertSuccess();
}
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private String mAccountName;
private SubscribedSubredditDao mSubscribedSubredditDao;
@ -29,12 +25,11 @@ public class InsertSubscribedThingsAsyncTask extends AsyncTask<Void, Void, Void>
private List<SubscribedUserData> subscribedUserData;
private List<SubredditData> subredditData;
private InsertSubscribedThingListener insertSubscribedThingListener;
public InsertSubscribedThingsAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, @Nullable String accountName,
List<SubscribedSubredditData> subscribedSubredditData,
List<SubscribedUserData> subscribedUserData,
List<SubredditData> subredditData,
InsertSubscribedThingListener insertSubscribedThingListener) {
List<SubscribedSubredditData> subscribedSubredditData,
List<SubscribedUserData> subscribedUserData,
List<SubredditData> subredditData,
InsertSubscribedThingListener insertSubscribedThingListener) {
mRedditDataRoomDatabase = redditDataRoomDatabase;
mAccountName = accountName;
mSubscribedSubredditDao = redditDataRoomDatabase.subscribedSubredditDao();
@ -49,23 +44,23 @@ public class InsertSubscribedThingsAsyncTask extends AsyncTask<Void, Void, Void>
@Override
protected Void doInBackground(final Void... params) {
if(mAccountName != null && mRedditDataRoomDatabase.accountDao().getAccountData(mAccountName) == null) {
if (mAccountName != null && mRedditDataRoomDatabase.accountDao().getAccountData(mAccountName) == null) {
return null;
}
if(subscribedSubredditData != null) {
if (subscribedSubredditData != null) {
for (SubscribedSubredditData s : subscribedSubredditData) {
mSubscribedSubredditDao.insert(s);
}
}
if(subscribedUserData != null) {
if (subscribedUserData != null) {
for (SubscribedUserData s : subscribedUserData) {
mUserDao.insert(s);
}
}
if(subredditData != null) {
if (subredditData != null) {
for (SubredditData s : subredditData) {
mSubredditDao.insert(s);
}
@ -77,4 +72,8 @@ public class InsertSubscribedThingsAsyncTask extends AsyncTask<Void, Void, Void>
protected void onPostExecute(Void aVoid) {
insertSubscribedThingListener.insertSuccess();
}
public interface InsertSubscribedThingListener {
void insertSuccess();
}
}

View File

@ -2,18 +2,14 @@ package ml.docilealligator.infinityforreddit.AsyncTask;
import android.os.AsyncTask;
import ml.docilealligator.infinityforreddit.User.UserData;
import ml.docilealligator.infinityforreddit.User.UserDao;
import ml.docilealligator.infinityforreddit.User.UserData;
public class InsertUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
private UserDao userDao;
private UserData userData;
private InsertUserDataCallback insertUserDataCallback;
public interface InsertUserDataCallback {
void insertSuccess();
}
public InsertUserDataAsyncTask(UserDao userDao, UserData userData, InsertUserDataCallback insertUserDataCallback) {
this.userDao = userDao;
this.userData = userData;
@ -29,8 +25,12 @@ public class InsertUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(insertUserDataCallback != null) {
if (insertUserDataCallback != null) {
insertUserDataCallback.insertSuccess();
}
}
public interface InsertUserDataCallback {
void insertSuccess();
}
}

View File

@ -11,10 +11,6 @@ import ml.docilealligator.infinityforreddit.SubredditDatabase.SubredditData;
import retrofit2.Retrofit;
public class LoadSubredditIconAsyncTask extends AsyncTask<Void, Void, Void> {
public interface LoadSubredditIconAsyncTaskListener {
void loadIconSuccess(String iconImageUrl);
}
private RedditDataRoomDatabase redditDataRoomDatabase;
private SubredditDao subredditDao;
private String subredditName;
@ -22,9 +18,8 @@ public class LoadSubredditIconAsyncTask extends AsyncTask<Void, Void, Void> {
private String iconImageUrl;
private boolean hasSubredditInDb;
private LoadSubredditIconAsyncTaskListener loadSubredditIconAsyncTaskListener;
public LoadSubredditIconAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, String subredditName, Retrofit retrofit,
LoadSubredditIconAsyncTaskListener loadSubredditIconAsyncTaskListener) {
LoadSubredditIconAsyncTaskListener loadSubredditIconAsyncTaskListener) {
this.redditDataRoomDatabase = redditDataRoomDatabase;
this.subredditDao = redditDataRoomDatabase.subredditDao();
this.subredditName = subredditName;
@ -35,7 +30,7 @@ public class LoadSubredditIconAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
SubredditData subredditData = subredditDao.getSubredditData(subredditName);
if(subredditData != null) {
if (subredditData != null) {
iconImageUrl = subredditDao.getSubredditData(subredditName).getIconUrl();
hasSubredditInDb = true;
} else {
@ -47,8 +42,8 @@ public class LoadSubredditIconAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(!isCancelled()) {
if(hasSubredditInDb) {
if (!isCancelled()) {
if (hasSubredditInDb) {
loadSubredditIconAsyncTaskListener.loadIconSuccess(iconImageUrl);
} else {
FetchSubredditData.fetchSubredditData(retrofit, subredditName, new FetchSubredditData.FetchSubredditDataListener() {
@ -69,4 +64,8 @@ public class LoadSubredditIconAsyncTask extends AsyncTask<Void, Void, Void> {
}
}
}
public interface LoadSubredditIconAsyncTaskListener {
void loadIconSuccess(String iconImageUrl);
}
}

View File

@ -3,22 +3,17 @@ package ml.docilealligator.infinityforreddit.AsyncTask;
import android.os.AsyncTask;
import ml.docilealligator.infinityforreddit.FetchUserData;
import ml.docilealligator.infinityforreddit.User.UserData;
import ml.docilealligator.infinityforreddit.User.UserDao;
import ml.docilealligator.infinityforreddit.User.UserData;
import retrofit2.Retrofit;
public class LoadUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
public interface LoadUserDataAsyncTaskListener {
void loadUserDataSuccess(String iconImageUrl);
}
private UserDao userDao;
private String userName;
private String iconImageUrl;
private boolean hasUserInDb;
private Retrofit retrofit;
private LoadUserDataAsyncTaskListener loadUserDataAsyncTaskListener;
public LoadUserDataAsyncTask(UserDao userDao, String userName, Retrofit retrofit, LoadUserDataAsyncTaskListener loadUserDataAsyncTaskListener) {
this.userDao = userDao;
this.userName = userName;
@ -28,7 +23,7 @@ public class LoadUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
if(userDao.getUserData(userName) != null) {
if (userDao.getUserData(userName) != null) {
iconImageUrl = userDao.getUserData(userName).getIconUrl();
hasUserInDb = true;
} else {
@ -40,7 +35,7 @@ public class LoadUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(hasUserInDb) {
if (hasUserInDb) {
loadUserDataAsyncTaskListener.loadUserDataSuccess(iconImageUrl);
} else {
FetchUserData.fetchUserData(retrofit, userName, new FetchUserData.FetchUserDataListener() {
@ -56,4 +51,8 @@ public class LoadUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
});
}
}
public interface LoadUserDataAsyncTaskListener {
void loadUserDataSuccess(String iconImageUrl);
}
}

View File

@ -7,10 +7,6 @@ import ml.docilealligator.infinityforreddit.Account.AccountDao;
public class ParseAndInsertNewAccountAsyncTask extends AsyncTask<Void, Void, Void> {
public interface ParseAndInsertAccountListener {
void success();
}
private String username;
private String accessToken;
private String refreshToken;
@ -20,10 +16,9 @@ public class ParseAndInsertNewAccountAsyncTask extends AsyncTask<Void, Void, Voi
private String code;
private AccountDao accountDao;
private ParseAndInsertAccountListener parseAndInsertAccountListener;
public ParseAndInsertNewAccountAsyncTask(String username, String accessToken, String refreshToken, String profileImageUrl, String bannerImageUrl,
int karma, String code, AccountDao accountDao,
ParseAndInsertAccountListener parseAndInsertAccountListener) {
int karma, String code, AccountDao accountDao,
ParseAndInsertAccountListener parseAndInsertAccountListener) {
this.username = username;
this.accessToken = accessToken;
this.refreshToken = refreshToken;
@ -48,4 +43,8 @@ public class ParseAndInsertNewAccountAsyncTask extends AsyncTask<Void, Void, Voi
protected void onPostExecute(Void aVoid) {
parseAndInsertAccountListener.success();
}
public interface ParseAndInsertAccountListener {
void success();
}
}

View File

@ -6,15 +6,10 @@ import ml.docilealligator.infinityforreddit.Account.Account;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
public class SwitchAccountAsyncTask extends AsyncTask<Void, Void, Void> {
public interface SwitchAccountAsyncTaskListener {
void switched(Account account);
}
private RedditDataRoomDatabase redditDataRoomDatabase;
private String newAccountName;
private Account account;
private SwitchAccountAsyncTaskListener switchAccountAsyncTaskListener;
public SwitchAccountAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, String newAccountName,
SwitchAccountAsyncTaskListener switchAccountAsyncTaskListener) {
this.redditDataRoomDatabase = redditDataRoomDatabase;
@ -34,4 +29,8 @@ public class SwitchAccountAsyncTask extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void aVoid) {
switchAccountAsyncTaskListener.switched(account);
}
public interface SwitchAccountAsyncTaskListener {
void switched(Account account);
}
}

View File

@ -6,16 +6,11 @@ import ml.docilealligator.infinityforreddit.Account.AccountDao;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
public class SwitchToAnonymousAccountAsyncTask extends AsyncTask<Void, Void, Void> {
public interface SwitchToAnonymousAccountAsyncTaskListener {
void logoutSuccess();
}
private RedditDataRoomDatabase redditDataRoomDatabase;
private boolean removeCurrentAccount;
private SwitchToAnonymousAccountAsyncTaskListener switchToAnonymousAccountAsyncTaskListener;
public SwitchToAnonymousAccountAsyncTask(RedditDataRoomDatabase redditDataRoomDatabase, boolean removeCurrentAccount,
SwitchToAnonymousAccountAsyncTaskListener switchToAnonymousAccountAsyncTaskListener) {
SwitchToAnonymousAccountAsyncTaskListener switchToAnonymousAccountAsyncTaskListener) {
this.redditDataRoomDatabase = redditDataRoomDatabase;
this.removeCurrentAccount = removeCurrentAccount;
this.switchToAnonymousAccountAsyncTaskListener = switchToAnonymousAccountAsyncTaskListener;
@ -24,7 +19,7 @@ public class SwitchToAnonymousAccountAsyncTask extends AsyncTask<Void, Void, Voi
@Override
protected Void doInBackground(Void... voids) {
AccountDao accountDao = redditDataRoomDatabase.accountDao();
if(removeCurrentAccount) {
if (removeCurrentAccount) {
accountDao.deleteCurrentAccount();
}
accountDao.markAllAccountsNonCurrent();
@ -35,4 +30,8 @@ public class SwitchToAnonymousAccountAsyncTask extends AsyncTask<Void, Void, Voi
protected void onPostExecute(Void aVoid) {
switchToAnonymousAccountAsyncTaskListener.logoutSuccess();
}
public interface SwitchToAnonymousAccountAsyncTaskListener {
void logoutSuccess();
}
}

View File

@ -9,7 +9,17 @@ public class CommentData implements Parcelable {
public static final int VOTE_TYPE_NO_VOTE = 0;
public static final int VOTE_TYPE_UPVOTE = 1;
public static final int VOTE_TYPE_DOWNVOTE = -1;
public static final Creator<CommentData> CREATOR = new Creator<CommentData>() {
@Override
public CommentData createFromParcel(Parcel in) {
return new CommentData(in);
}
@Override
public CommentData[] newArray(int size) {
return new CommentData[size];
}
};
private String id;
private String fullName;
private String author;
@ -33,15 +43,14 @@ public class CommentData implements Parcelable {
private ArrayList<CommentData> children;
private ArrayList<String> moreChildrenFullnames;
private int moreChildrenStartingIndex;
private boolean isPlaceHolder;
private boolean isLoadingMoreChildren;
private boolean loadMoreChildrenFailed;
public CommentData(String id, String fullName, String author, String linkAuthor, String commentTime,
String commentContent, String linkId, String subredditName, String parentId, int score,
int voteType, boolean isSubmitter, String distinguished, String permalink,
int depth, boolean collapsed, boolean hasReply, boolean scoreHidden, boolean saved) {
String commentContent, String linkId, String subredditName, String parentId, int score,
int voteType, boolean isSubmitter, String distinguished, String permalink,
int depth, boolean collapsed, boolean hasReply, boolean scoreHidden, boolean saved) {
this.id = id;
this.fullName = fullName;
this.author = author;
@ -102,18 +111,6 @@ public class CommentData implements Parcelable {
loadMoreChildrenFailed = in.readByte() != 0;
}
public static final Creator<CommentData> CREATOR = new Creator<CommentData>() {
@Override
public CommentData createFromParcel(Parcel in) {
return new CommentData(in);
}
@Override
public CommentData[] newArray(int size) {
return new CommentData[size];
}
};
public String getId() {
return id;
}
@ -235,10 +232,10 @@ public class CommentData implements Parcelable {
}
public void addChildren(ArrayList<CommentData> moreChildren) {
if(children == null || children.size() == 0) {
if (children == null || children.size() == 0) {
setChildren(moreChildren);
} else {
if(children.get(children.size() - 1).isPlaceHolder) {
if (children.get(children.size() - 1).isPlaceHolder) {
children.addAll(children.size() - 2, moreChildren);
} else {
children.addAll(moreChildren);
@ -251,7 +248,7 @@ public class CommentData implements Parcelable {
}
public void addChild(CommentData comment, int position) {
if(children == null) {
if (children == null) {
children = new ArrayList<>();
}
children.add(position, comment);

View File

@ -71,11 +71,11 @@ public class CommentDataSource extends PageKeyedDataSource<String, CommentData>
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> commentsCall;
if(areSavedComments) {
if (areSavedComments) {
commentsCall = api.getUserSavedCommentsOauth(username, PostDataSource.USER_WHERE_SAVED,
null, sortType, RedditUtils.getOAuthHeader(accessToken));
} else {
if(accessToken == null) {
if (accessToken == null) {
commentsCall = api.getUserComments(username, null, sortType);
} else {
commentsCall = api.getUserCommentsOauth(RedditUtils.getOAuthHeader(accessToken), username,
@ -85,17 +85,17 @@ public class CommentDataSource extends PageKeyedDataSource<String, CommentData>
commentsCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
new ParseCommentAsyncTask(response.body(), locale, new ParseCommentAsyncTask.ParseCommentAsyncTaskListener() {
@Override
public void parseSuccessful(ArrayList<CommentData> comments, String after) {
if(comments.size() == 0) {
if (comments.size() == 0) {
hasPostLiveData.postValue(false);
} else {
hasPostLiveData.postValue(true);
}
if(after == null || after.equals("") || after.equals("null")) {
if (after == null || after.equals("") || after.equals("null")) {
callback.onResult(comments, null, null);
} else {
callback.onResult(comments, null, after);
@ -134,11 +134,11 @@ public class CommentDataSource extends PageKeyedDataSource<String, CommentData>
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> commentsCall;
if(areSavedComments) {
if (areSavedComments) {
commentsCall = api.getUserSavedCommentsOauth(username, PostDataSource.USER_WHERE_SAVED, params.key,
sortType, RedditUtils.getOAuthHeader(accessToken));
} else {
if(accessToken == null) {
if (accessToken == null) {
commentsCall = api.getUserComments(username, params.key, sortType);
} else {
commentsCall = api.getUserCommentsOauth(RedditUtils.getOAuthHeader(accessToken),
@ -148,11 +148,11 @@ public class CommentDataSource extends PageKeyedDataSource<String, CommentData>
commentsCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
new ParseCommentAsyncTask(response.body(), locale, new ParseCommentAsyncTask.ParseCommentAsyncTaskListener() {
@Override
public void parseSuccessful(ArrayList<CommentData> comments, String after) {
if(after == null || after.equals("") || after.equals("null")) {
if (after == null || after.equals("") || after.equals("null")) {
callback.onResult(comments, null);
} else {
callback.onResult(comments, after);
@ -184,11 +184,6 @@ public class CommentDataSource extends PageKeyedDataSource<String, CommentData>
private boolean parseFailed;
private ParseCommentAsyncTaskListener parseCommentAsyncTaskListener;
interface ParseCommentAsyncTaskListener {
void parseSuccessful(ArrayList<CommentData> comments, String after);
void parseFailed();
}
ParseCommentAsyncTask(String response, Locale locale, ParseCommentAsyncTaskListener parseCommentAsyncTaskListener) {
this.locale = locale;
this.parseCommentAsyncTaskListener = parseCommentAsyncTaskListener;
@ -205,16 +200,17 @@ public class CommentDataSource extends PageKeyedDataSource<String, CommentData>
@Override
protected ArrayList<CommentData> doInBackground(Void... voids) {
if(parseFailed) {
if (parseFailed) {
return null;
}
ArrayList<CommentData> comments = new ArrayList<>();
for(int i = 0; i < commentsJSONArray.length(); i++) {
for (int i = 0; i < commentsJSONArray.length(); i++) {
try {
JSONObject commentJSON = commentsJSONArray.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
comments.add(ParseComment.parseSingleComment(commentJSON, 0, locale));
} catch (JSONException ignored) {}
} catch (JSONException ignored) {
}
}
return comments;
}
@ -222,11 +218,17 @@ public class CommentDataSource extends PageKeyedDataSource<String, CommentData>
@Override
protected void onPostExecute(ArrayList<CommentData> commentData) {
super.onPostExecute(commentData);
if(commentData != null) {
if (commentData != null) {
parseCommentAsyncTaskListener.parseSuccessful(commentData, after);
} else {
parseCommentAsyncTaskListener.parseFailed();
}
}
interface ParseCommentAsyncTaskListener {
void parseSuccessful(ArrayList<CommentData> comments, String after);
void parseFailed();
}
}
}

View File

@ -10,6 +10,11 @@ public enum ContentFontStyle {
private int resId;
private String title;
ContentFontStyle(int resId, String title) {
this.resId = resId;
this.title = title;
}
public int getResId() {
return resId;
}
@ -17,9 +22,4 @@ public enum ContentFontStyle {
public String getTitle() {
return title;
}
ContentFontStyle(int resId, String title) {
this.resId = resId;
this.title = title;
}
}

View File

@ -9,6 +9,17 @@ import pl.droidsonroids.gif.GifImageView;
public class AspectRatioGifImageView extends GifImageView {
private float ratio;
public AspectRatioGifImageView(Context context) {
super(context);
this.ratio = 1.0F;
}
public AspectRatioGifImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.ratio = 1.0F;
this.init(context, attrs);
}
public final float getRatio() {
return this.ratio;
}
@ -32,23 +43,12 @@ public class AspectRatioGifImageView extends GifImageView {
int height = this.getMeasuredHeight();
if (width != 0 || height != 0) {
if (width > 0) {
height = (int)((float)width * this.ratio);
height = (int) ((float) width * this.ratio);
} else {
width = (int)((float)height / this.ratio);
width = (int) ((float) height / this.ratio);
}
this.setMeasuredDimension(width, height);
}
}
public AspectRatioGifImageView(Context context) {
super(context);
this.ratio = 1.0F;
}
public AspectRatioGifImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.ratio = 1.0F;
this.init(context, attrs);
}
}

View File

@ -11,18 +11,13 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class DeleteThing {
public interface DeleteThingListener {
void deleteSuccess();
void deleteFailed();
}
public static void delete(Retrofit oauthRetrofit, String fullname, String accessToken, DeleteThingListener deleteThingListener) {
Map<String, String> params = new HashMap<>();
params.put(RedditUtils.ID_KEY, fullname);
oauthRetrofit.create(RedditAPI.class).delete(RedditUtils.getOAuthHeader(accessToken), params).enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
deleteThingListener.deleteSuccess();
} else {
deleteThingListener.deleteFailed();
@ -35,4 +30,10 @@ public class DeleteThing {
}
});
}
public interface DeleteThingListener {
void deleteSuccess();
void deleteFailed();
}
}

View File

@ -1,3 +1,4 @@
package ml.docilealligator.infinityforreddit.Event;
public class ChangeFontSizeEvent { }
public class ChangeFontSizeEvent {
}

View File

@ -2,6 +2,7 @@ package ml.docilealligator.infinityforreddit.Event;
public class ChangeNSFWBlurEvent {
public boolean needBlurNSFW;
public ChangeNSFWBlurEvent(boolean needBlurNSFW) {
this.needBlurNSFW = needBlurNSFW;
}

View File

@ -2,6 +2,7 @@ package ml.docilealligator.infinityforreddit.Event;
public class ChangeNSFWEvent {
public boolean nsfw;
public ChangeNSFWEvent(boolean nsfw) {
this.nsfw = nsfw;
}

View File

@ -2,6 +2,7 @@ package ml.docilealligator.infinityforreddit.Event;
public class ChangeSpoilerBlurEvent {
public boolean needBlurSpoiler;
public ChangeSpoilerBlurEvent(boolean needBlurSpoiler) {
this.needBlurSpoiler = needBlurSpoiler;
}

View File

@ -2,7 +2,10 @@ package ml.docilealligator.infinityforreddit.Event;
public class SwitchAccountEvent {
public String excludeActivityClassName;
public SwitchAccountEvent() {}
public SwitchAccountEvent() {
}
public SwitchAccountEvent(String excludeActivityClassName) {
this.excludeActivityClassName = excludeActivityClassName;
}

View File

@ -12,28 +12,18 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class FetchComment {
public interface FetchCommentListener {
void onFetchCommentSuccess(ArrayList<CommentData> expandedComments, String parentId, ArrayList<String> children);
void onFetchCommentFailed();
}
public interface FetchMoreCommentListener {
void onFetchMoreCommentSuccess(ArrayList<CommentData> expandedComments, int childrenStartingIndex);
void onFetchMoreCommentFailed();
}
public static void fetchComments(Retrofit retrofit, @Nullable String accessToken, String article, String commentId,
Locale locale, FetchCommentListener fetchCommentListener) {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> comments;
if(accessToken == null) {
if(commentId == null) {
if (accessToken == null) {
if (commentId == null) {
comments = api.getPostAndCommentsById(article);
} else {
comments = api.getPostAndCommentsSingleThreadById(article, commentId);
}
} else {
if(commentId == null) {
if (commentId == null) {
comments = api.getPostAndCommentsByIdOauth(article, RedditUtils.getOAuthHeader(accessToken));
} else {
comments = api.getPostAndCommentsSingleThreadByIdOauth(article, commentId, RedditUtils.getOAuthHeader(accessToken));
@ -43,7 +33,7 @@ public class FetchComment {
comments.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParseComment.parseComment(response.body(), new ArrayList<>(),
locale, new ParseComment.ParseCommentListener() {
@Override
@ -74,14 +64,14 @@ public class FetchComment {
ArrayList<String> allChildren, int startingIndex,
int depth, Locale locale, FetchMoreCommentListener fetchMoreCommentListener) {
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < 100; i++) {
if(allChildren.size() <= startingIndex + i) {
for (int i = 0; i < 100; i++) {
if (allChildren.size() <= startingIndex + i) {
break;
}
stringBuilder.append(allChildren.get(startingIndex + i)).append(",");
}
if(stringBuilder.length() == 0) {
if (stringBuilder.length() == 0) {
return;
}
@ -89,7 +79,7 @@ public class FetchComment {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> moreComments;
if(accessToken == null) {
if (accessToken == null) {
moreComments = api.getInfo(stringBuilder.toString());
} else {
moreComments = api.getInfoOauth(stringBuilder.toString(), RedditUtils.getOAuthHeader(accessToken));
@ -98,7 +88,7 @@ public class FetchComment {
moreComments.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParseComment.parseMoreComment(response.body(), new ArrayList<>(), locale,
depth, new ParseComment.ParseCommentListener() {
@Override
@ -124,4 +114,16 @@ public class FetchComment {
}
});
}
public interface FetchCommentListener {
void onFetchCommentSuccess(ArrayList<CommentData> expandedComments, String parentId, ArrayList<String> children);
void onFetchCommentFailed();
}
public interface FetchMoreCommentListener {
void onFetchMoreCommentSuccess(ArrayList<CommentData> expandedComments, int childrenStartingIndex);
void onFetchMoreCommentFailed();
}
}

View File

@ -15,11 +15,6 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class FetchFlairs {
public interface FetchFlairsInSubredditListener {
void fetchSuccessful(ArrayList<Flair> flairs);
void fetchFailed();
}
public static void fetchFlairsInSubreddit(Retrofit oauthRetrofit, String accessToken, String subredditName, FetchFlairsInSubredditListener fetchFlairsInSubredditListener) {
RedditAPI api = oauthRetrofit.create(RedditAPI.class);
@ -39,7 +34,7 @@ public class FetchFlairs {
fetchFlairsInSubredditListener.fetchFailed();
}
}).execute();
} else if(response.code() == 403) {
} else if (response.code() == 403) {
//No flairs
fetchFlairsInSubredditListener.fetchSuccessful(null);
} else {
@ -54,15 +49,15 @@ public class FetchFlairs {
});
}
private static class ParseFlairsAsyncTask extends AsyncTask<Void, ArrayList<Flair>, ArrayList<Flair>> {
interface ParseFlairsAsyncTaskListener {
void parseSuccessful(ArrayList<Flair> flairs);
void parseFailed();
}
public interface FetchFlairsInSubredditListener {
void fetchSuccessful(ArrayList<Flair> flairs);
void fetchFailed();
}
private static class ParseFlairsAsyncTask extends AsyncTask<Void, ArrayList<Flair>, ArrayList<Flair>> {
private String response;
private ParseFlairsAsyncTaskListener parseFlairsAsyncTaskListener;
ParseFlairsAsyncTask(String response, ParseFlairsAsyncTaskListener parseFlairsAsyncTaskListener) {
this.response = response;
this.parseFlairsAsyncTaskListener = parseFlairsAsyncTaskListener;
@ -73,7 +68,7 @@ public class FetchFlairs {
try {
JSONArray jsonArray = new JSONArray(response);
ArrayList<Flair> flairs = new ArrayList<>();
for(int i = 0; i < jsonArray.length(); i++) {
for (int i = 0; i < jsonArray.length(); i++) {
String id = jsonArray.getJSONObject(i).getString(JSONUtils.ID_KEY);
String text = jsonArray.getJSONObject(i).getString(JSONUtils.TEXT_KEY);
boolean editable = jsonArray.getJSONObject(i).getBoolean(JSONUtils.TEXT_EDITABLE_KEY);
@ -89,11 +84,17 @@ public class FetchFlairs {
@Override
protected void onPostExecute(ArrayList<Flair> strings) {
if(strings != null) {
if (strings != null) {
parseFlairsAsyncTaskListener.parseSuccessful(strings);
} else {
parseFlairsAsyncTaskListener.parseFailed();
}
}
interface ParseFlairsAsyncTaskListener {
void parseSuccessful(ArrayList<Flair> flairs);
void parseFailed();
}
}
}

View File

@ -21,11 +21,6 @@ import retrofit2.Retrofit;
public class FetchMessages {
interface FetchMessagesListener {
void fetchSuccess(ArrayList<Message> messages, @Nullable String after);
void fetchFailed();
}
public static final String WHERE_INBOX = "inbox";
public static final String WHERE_UNREAD = "unread";
public static final String WHERE_SENT = "sent";
@ -37,7 +32,7 @@ public class FetchMessages {
.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
new ParseMessageAsnycTask(response.body(), locale, fetchMessagesListener::fetchSuccess).execute();
} else {
fetchMessagesListener.fetchFailed();
@ -62,7 +57,7 @@ public class FetchMessages {
}
ArrayList<Message> messages = new ArrayList<>();
for(int i = 0; i < messageArray.length(); i++) {
for (int i = 0; i < messageArray.length(); i++) {
try {
JSONObject messageJSON = messageArray.getJSONObject(i);
String kind = messageJSON.getString(JSONUtils.KIND_KEY);
@ -100,18 +95,19 @@ public class FetchMessages {
return messages;
}
private static class ParseMessageAsnycTask extends AsyncTask<Void, Void, Void> {
interface FetchMessagesListener {
void fetchSuccess(ArrayList<Message> messages, @Nullable String after);
interface ParseMessageAsyncTaskListener {
void parseSuccess(ArrayList<Message> messages, @Nullable String after);
}
void fetchFailed();
}
private static class ParseMessageAsnycTask extends AsyncTask<Void, Void, Void> {
private String response;
private Locale locale;
private ArrayList<Message> messages;
private String after;
private ParseMessageAsyncTaskListener parseMessageAsyncTaskListener;
ParseMessageAsnycTask(String response, Locale locale, ParseMessageAsyncTaskListener parseMessageAsnycTaskListener) {
this.response = response;
this.locale = locale;
@ -135,5 +131,9 @@ public class FetchMessages {
super.onPostExecute(aVoid);
parseMessageAsyncTaskListener.parseSuccess(messages, after);
}
interface ParseMessageAsyncTaskListener {
void parseSuccess(ArrayList<Message> messages, @Nullable String after);
}
}
}

View File

@ -1,7 +1,5 @@
package ml.docilealligator.infinityforreddit;
import android.util.Log;
import androidx.annotation.NonNull;
import retrofit2.Call;
@ -10,11 +8,6 @@ import retrofit2.Retrofit;
public class FetchMyInfo {
public interface FetchUserMyListener {
void onFetchMyInfoSuccess(String response);
void onFetchMyInfoFail();
}
public static void fetchAccountInfo(final Retrofit retrofit, String accessToken,
final FetchUserMyListener fetchUserMyListener) {
RedditAPI api = retrofit.create(RedditAPI.class);
@ -23,7 +16,7 @@ public class FetchMyInfo {
userInfo.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
fetchUserMyListener.onFetchMyInfoSuccess(response.body());
} else {
fetchUserMyListener.onFetchMyInfoFail();
@ -36,4 +29,10 @@ public class FetchMyInfo {
}
});
}
public interface FetchUserMyListener {
void onFetchMyInfoSuccess(String response);
void onFetchMyInfoFail();
}
}

View File

@ -10,14 +10,9 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class FetchPost {
public interface FetchPostListener {
void fetchPostSuccess(Post post);
void fetchPostFailed();
}
public static void fetchPost(Retrofit retrofit, String id, String accessToken, Locale locale, FetchPostListener fetchPostListener) {
Call<String> postCall;
if(accessToken == null) {
if (accessToken == null) {
postCall = retrofit.create(RedditAPI.class).getPost(id);
} else {
postCall = retrofit.create(RedditAPI.class).getPostOauth(id, RedditUtils.getOAuthHeader(accessToken));
@ -25,7 +20,7 @@ public class FetchPost {
postCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParsePost.parsePost(response.body(), locale, new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(Post post) {
@ -48,4 +43,10 @@ public class FetchPost {
}
});
}
public interface FetchPostListener {
void fetchPostSuccess(Post post);
void fetchPostFailed();
}
}

View File

@ -11,16 +11,6 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class FetchSubredditData {
public interface FetchSubredditDataListener {
void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers);
void onFetchSubredditDataFail();
}
interface FetchSubredditListingDataListener {
void onFetchSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after);
void onFetchSubredditListingDataFail();
}
public static void fetchSubredditData(Retrofit retrofit, String subredditName, final FetchSubredditDataListener fetchSubredditDataListener) {
RedditAPI api = retrofit.create(RedditAPI.class);
@ -28,7 +18,7 @@ public class FetchSubredditData {
subredditData.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParseSubredditData.parseSubredditData(response.body(), new ParseSubredditData.ParseSubredditDataListener() {
@Override
public void onParseSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
@ -60,7 +50,7 @@ public class FetchSubredditData {
subredditDataCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParseSubredditData.parseSubredditListingData(response.body(), new ParseSubredditData.ParseSubredditListingDataListener() {
@Override
public void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after) {
@ -83,4 +73,16 @@ public class FetchSubredditData {
}
});
}
public interface FetchSubredditDataListener {
void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers);
void onFetchSubredditDataFail();
}
interface FetchSubredditListingDataListener {
void onFetchSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after);
void onFetchSubredditListingDataFail();
}
}

View File

@ -13,13 +13,6 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class FetchSubscribedThing {
public interface FetchSubscribedThingListener {
void onFetchSubscribedThingSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData,
ArrayList<SubredditData> subredditData);
void onFetchSubscribedThingFail();
}
public static void fetchSubscribedThing(final Retrofit retrofit, String accessToken, String accountName,
final String lastItem, final ArrayList<SubscribedSubredditData> subscribedSubredditData,
final ArrayList<SubscribedUserData> subscribedUserData,
@ -31,7 +24,7 @@ public class FetchSubscribedThing {
subredditDataCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParseSubscribedThing.parseSubscribedSubreddits(response.body(), accountName,
subscribedSubredditData, subscribedUserData, subredditData,
new ParseSubscribedThing.ParseSubscribedSubredditsListener() {
@ -41,7 +34,7 @@ public class FetchSubscribedThing {
ArrayList<SubscribedUserData> subscribedUserData,
ArrayList<SubredditData> subredditData,
String lastItem) {
if(lastItem.equals("null")) {
if (lastItem.equals("null")) {
fetchSubscribedThingListener.onFetchSubscribedThingSuccess(
subscribedSubredditData, subscribedUserData, subredditData);
} else {
@ -67,4 +60,12 @@ public class FetchSubscribedThing {
}
});
}
public interface FetchSubscribedThingListener {
void onFetchSubscribedThingSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData,
ArrayList<SubredditData> subredditData);
void onFetchSubscribedThingFail();
}
}

View File

@ -10,16 +10,6 @@ import retrofit2.Callback;
import retrofit2.Retrofit;
public class FetchUserData {
public interface FetchUserDataListener {
void onFetchUserDataSuccess(UserData userData);
void onFetchUserDataFailed();
}
public interface FetchUserListingDataListener {
void onFetchUserListingDataSuccess(ArrayList<UserData> userData, String after);
void onFetchUserListingDataFailed();
}
public static void fetchUserData(Retrofit retrofit, String userName, FetchUserDataListener fetchUserDataListener) {
RedditAPI api = retrofit.create(RedditAPI.class);
@ -27,7 +17,7 @@ public class FetchUserData {
userInfo.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParseUserData.parseUserData(response.body(), new ParseUserData.ParseUserDataListener() {
@Override
public void onParseUserDataSuccess(UserData userData) {
@ -59,7 +49,7 @@ public class FetchUserData {
userInfo.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParseUserData.parseUserListingData(response.body(), new ParseUserData.ParseUserListingDataListener() {
@Override
public void onParseUserListingDataSuccess(ArrayList<UserData> userData, String after) {
@ -82,4 +72,16 @@ public class FetchUserData {
}
});
}
public interface FetchUserDataListener {
void onFetchUserDataSuccess(UserData userData);
void onFetchUserDataFailed();
}
public interface FetchUserListingDataListener {
void onFetchUserListingDataSuccess(ArrayList<UserData> userData, String after);
void onFetchUserListingDataFailed();
}
}

View File

@ -4,6 +4,17 @@ import android.os.Parcel;
import android.os.Parcelable;
public class Flair implements Parcelable {
public static final Creator<Flair> CREATOR = new Creator<Flair>() {
@Override
public Flair createFromParcel(Parcel in) {
return new Flair(in);
}
@Override
public Flair[] newArray(int size) {
return new Flair[size];
}
};
private String id;
private String text;
private boolean editable;
@ -20,18 +31,6 @@ public class Flair implements Parcelable {
editable = in.readByte() != 0;
}
public static final Creator<Flair> CREATOR = new Creator<Flair>() {
@Override
public Flair createFromParcel(Parcel in) {
return new Flair(in);
}
@Override
public Flair[] newArray(int size) {
return new Flair[size];
}
};
public String getId() {
return id;
}

View File

@ -9,6 +9,11 @@ public enum FontStyle {
private int resId;
private String title;
FontStyle(int resId, String title) {
this.resId = resId;
this.title = title;
}
public int getResId() {
return resId;
}
@ -16,9 +21,4 @@ public enum FontStyle {
public String getTitle() {
return title;
}
FontStyle(int resId, String title) {
this.resId = resId;
this.title = title;
}
}

View File

@ -55,33 +55,32 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
private static final String NULL_ACCESS_TOKEN_STATE = "NATS";
private static final String ACCESS_TOKEN_STATE = "ATS";
@BindView(R.id.coordinator_layout_comments_listing_fragment) CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.recycler_view_comments_listing_fragment) RecyclerView mCommentRecyclerView;
@BindView(R.id.progress_bar_comments_listing_fragment) CircleProgressBar mProgressBar;
@BindView(R.id.fetch_comments_info_linear_layout_comments_listing_fragment) LinearLayout mFetchCommentInfoLinearLayout;
@BindView(R.id.fetch_comments_info_image_view_comments_listing_fragment) ImageView mFetchCommentInfoImageView;
@BindView(R.id.fetch_comments_info_text_view_comments_listing_fragment) TextView mFetchCommentInfoTextView;
private boolean mNullAccessToken = false;
private String mAccessToken;
private RequestManager mGlide;
private Activity activity;
private CommentsListingRecyclerViewAdapter mAdapter;
@BindView(R.id.coordinator_layout_comments_listing_fragment)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.recycler_view_comments_listing_fragment)
RecyclerView mCommentRecyclerView;
@BindView(R.id.progress_bar_comments_listing_fragment)
CircleProgressBar mProgressBar;
@BindView(R.id.fetch_comments_info_linear_layout_comments_listing_fragment)
LinearLayout mFetchCommentInfoLinearLayout;
@BindView(R.id.fetch_comments_info_image_view_comments_listing_fragment)
ImageView mFetchCommentInfoImageView;
@BindView(R.id.fetch_comments_info_text_view_comments_listing_fragment)
TextView mFetchCommentInfoTextView;
CommentViewModel mCommentViewModel;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject @Named("oauth")
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
private boolean mNullAccessToken = false;
private String mAccessToken;
private RequestManager mGlide;
private Activity activity;
private CommentsListingRecyclerViewAdapter mAdapter;
public CommentsListingFragment() {
// Required empty public constructor
@ -128,7 +127,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
private void getCurrentAccountAndBindView(Resources resources) {
new GetCurrentAccountAsyncTask(mRedditDataRoomDatabase.accountDao(), account -> {
if(account == null) {
if (account == null) {
mNullAccessToken = true;
} else {
mAccessToken = account.getAccessToken();
@ -150,7 +149,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
CommentViewModel.Factory factory;
if(mAccessToken == null) {
if (mAccessToken == null) {
factory = new CommentViewModel.Factory(mRetrofit,
resources.getConfiguration().locale, mAccessToken, username, PostDataSource.SORT_TYPE_NEW,
getArguments().getBoolean(EXTRA_ARE_SAVED_COMMENTS));
@ -165,7 +164,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
mCommentViewModel.hasComment().observe(this, hasComment -> {
mProgressBar.setVisibility(View.GONE);
if(hasComment) {
if (hasComment) {
mFetchCommentInfoLinearLayout.setVisibility(View.GONE);
} else {
mFetchCommentInfoLinearLayout.setOnClickListener(view -> {
@ -176,9 +175,9 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
});
mCommentViewModel.getInitialLoadingState().observe(this, networkState -> {
if(networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
if (networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
mProgressBar.setVisibility(View.GONE);
} else if(networkState.getStatus().equals(NetworkState.Status.FAILED)) {
} else if (networkState.getStatus().equals(NetworkState.Status.FAILED)) {
mProgressBar.setVisibility(View.GONE);
mFetchCommentInfoLinearLayout.setOnClickListener(view -> refresh());
showErrorView(R.string.load_comments_failed);
@ -215,7 +214,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
}
private void showErrorView(int stringResId) {
if(activity != null && isAdded()) {
if (activity != null && isAdded()) {
mProgressBar.setVisibility(View.GONE);
mFetchCommentInfoLinearLayout.setVisibility(View.VISIBLE);
mFetchCommentInfoTextView.setText(stringResId);

View File

@ -36,36 +36,29 @@ import retrofit2.Retrofit;
*/
public class FlairBottomSheetFragment extends BottomSheetDialogFragment {
public interface FlairSelectionCallback {
void flairSelected(Flair flair);
}
public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_SUBREDDIT_NAME = "ESN";
@BindView(R.id.progress_bar_flair_bottom_sheet_fragment) ProgressBar progressBar;
@BindView(R.id.error_text_view_flair_bottom_sheet_fragment) TextView errorTextView;
@BindView(R.id.recycler_view_bottom_sheet_fragment) RecyclerView recyclerView;
private String mAccessToken;
private String mSubredditName;
private Activity mActivity;
private FlairBottomSheetRecyclerViewAdapter mAdapter;
@BindView(R.id.progress_bar_flair_bottom_sheet_fragment)
ProgressBar progressBar;
@BindView(R.id.error_text_view_flair_bottom_sheet_fragment)
TextView errorTextView;
@BindView(R.id.recycler_view_bottom_sheet_fragment)
RecyclerView recyclerView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
private String mAccessToken;
private String mSubredditName;
private Activity mActivity;
private FlairBottomSheetRecyclerViewAdapter mAdapter;
public FlairBottomSheetFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@ -101,25 +94,29 @@ public class FlairBottomSheetFragment extends BottomSheetDialogFragment {
private void fetchFlairs() {
FetchFlairs.fetchFlairsInSubreddit(mOauthRetrofit, mAccessToken,
mSubredditName, new FetchFlairs.FetchFlairsInSubredditListener() {
@Override
public void fetchSuccessful(ArrayList<Flair> flairs) {
progressBar.setVisibility(View.GONE);
if(flairs == null || flairs.size() == 0) {
errorTextView.setVisibility(View.VISIBLE);
errorTextView.setText(R.string.no_flair);
} else {
errorTextView.setVisibility(View.GONE);
mAdapter.changeDataset(flairs);
}
}
@Override
public void fetchSuccessful(ArrayList<Flair> flairs) {
progressBar.setVisibility(View.GONE);
if (flairs == null || flairs.size() == 0) {
errorTextView.setVisibility(View.VISIBLE);
errorTextView.setText(R.string.no_flair);
} else {
errorTextView.setVisibility(View.GONE);
mAdapter.changeDataset(flairs);
}
}
@Override
public void fetchFailed() {
progressBar.setVisibility(View.GONE);
errorTextView.setVisibility(View.VISIBLE);
errorTextView.setText(R.string.error_loading_flairs);
errorTextView.setOnClickListener(view -> fetchFlairs());
}
});
@Override
public void fetchFailed() {
progressBar.setVisibility(View.GONE);
errorTextView.setVisibility(View.VISIBLE);
errorTextView.setText(R.string.error_loading_flairs);
errorTextView.setOnClickListener(view -> fetchFlairs());
}
});
}
public interface FlairSelectionCallback {
void flairSelected(Flair flair);
}
}

View File

@ -22,13 +22,13 @@ import com.bumptech.glide.RequestManager;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.Adapter.FollowedUsersRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.SubscribedUserDatabase.SubscribedUserViewModel;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
@ -38,23 +38,22 @@ public class FollowedUsersListingFragment extends Fragment {
public static final String EXTRA_ACCOUNT_NAME = "EAN";
@BindView(R.id.recycler_view_followed_users_listing_fragment) RecyclerView mRecyclerView;
@BindView(R.id.no_subscriptions_linear_layout_followed_users_listing_fragment) LinearLayout mLinearLayout;
@BindView(R.id.no_subscriptions_image_view_followed_users_listing_fragment) ImageView mImageView;
@BindView(R.id.recycler_view_followed_users_listing_fragment)
RecyclerView mRecyclerView;
@BindView(R.id.no_subscriptions_linear_layout_followed_users_listing_fragment)
LinearLayout mLinearLayout;
@BindView(R.id.no_subscriptions_image_view_followed_users_listing_fragment)
ImageView mImageView;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
private Activity mActivity;
private RequestManager mGlide;
private SubscribedUserViewModel mSubscribedUserViewModel;
public FollowedUsersListingFragment() {
// Required empty public constructor
}
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View File

@ -32,14 +32,14 @@ public class ModifyCommentBottomSheetFragment extends RoundedBottomSheetDialogFr
public static final String EXTRA_COMMENT_CONTENT = "ECC";
public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_POSITION = "EP";
@BindView(R.id.edit_text_view_modify_comment_bottom_sheet_fragment)
TextView editTextView;
@BindView(R.id.delete_text_view_modify_comment_bottom_sheet_fragment)
TextView deleteTextView;
public ModifyCommentBottomSheetFragment() {
// Required empty public constructor
}
@BindView(R.id.edit_text_view_modify_comment_bottom_sheet_fragment) TextView editTextView;
@BindView(R.id.delete_text_view_modify_comment_bottom_sheet_fragment) TextView deleteTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@ -48,7 +48,7 @@ public class ModifyCommentBottomSheetFragment extends RoundedBottomSheetDialogFr
Activity activity = getActivity();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
@ -64,7 +64,7 @@ public class ModifyCommentBottomSheetFragment extends RoundedBottomSheetDialogFr
intent.putExtra(EditCommentActivity.EXTRA_FULLNAME, fullName);
intent.putExtra(EditCommentActivity.EXTRA_CONTENT, content);
intent.putExtra(EditCommentActivity.EXTRA_POSITION, bundle.getInt(EXTRA_POSITION));
if(activity instanceof ViewPostDetailActivity) {
if (activity instanceof ViewPostDetailActivity) {
activity.startActivityForResult(intent, ViewPostDetailActivity.EDIT_COMMENT_REQUEST_CODE);
} else {
startActivity(intent);
@ -75,9 +75,9 @@ public class ModifyCommentBottomSheetFragment extends RoundedBottomSheetDialogFr
deleteTextView.setOnClickListener(view -> {
dismiss();
if(activity instanceof ViewPostDetailActivity) {
if (activity instanceof ViewPostDetailActivity) {
((ViewPostDetailActivity) activity).deleteComment(fullName, bundle.getInt(EXTRA_POSITION));
} else if(activity instanceof ViewUserDetailActivity) {
} else if (activity instanceof ViewUserDetailActivity) {
((ViewUserDetailActivity) activity).deleteComment(fullName);
}
});

View File

@ -82,46 +82,42 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private static final String IS_IN_LAZY_MODE_STATE = "IILMS";
private static final String RECYCLER_VIEW_POSITION_STATE = "RVPS";
@BindView(R.id.recycler_view_post_fragment) RecyclerView mPostRecyclerView;
@BindView(R.id.progress_bar_post_fragment) CircleProgressBar mProgressBar;
@BindView(R.id.fetch_post_info_linear_layout_post_fragment) LinearLayout mFetchPostInfoLinearLayout;
@BindView(R.id.fetch_post_info_image_view_post_fragment) ImageView mFetchPostInfoImageView;
@BindView(R.id.fetch_post_info_text_view_post_fragment) TextView mFetchPostInfoTextView;
@BindView(R.id.recycler_view_post_fragment)
RecyclerView mPostRecyclerView;
@BindView(R.id.progress_bar_post_fragment)
CircleProgressBar mProgressBar;
@BindView(R.id.fetch_post_info_linear_layout_post_fragment)
LinearLayout mFetchPostInfoLinearLayout;
@BindView(R.id.fetch_post_info_image_view_post_fragment)
ImageView mFetchPostInfoImageView;
@BindView(R.id.fetch_post_info_text_view_post_fragment)
TextView mFetchPostInfoTextView;
PostViewModel mPostViewModel;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private RequestManager mGlide;
private Activity activity;
private LinearLayoutManager mLinearLayoutManager;
private StaggeredGridLayoutManager mStaggeredGridLayoutManager;
private boolean isInLazyMode = false;
private boolean isLazyModePaused = false;
private boolean hasPost = false;
private PostRecyclerViewAdapter mAdapter;
private RecyclerView.SmoothScroller smoothScroller;
PostViewModel mPostViewModel;
private Window window;
private Handler lazyModeHandler;
private LazyModeRunnable lazyModeRunnable;
private CountDownTimer resumeLazyModeCountDownTimer;
private float lazyModeInterval;
@Inject @Named("no_oauth")
Retrofit mRetrofit;
@Inject @Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
public PostFragment() {
// Required empty public constructor
}
@ -129,7 +125,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override
public void onResume() {
super.onResume();
if(mPostRecyclerView.getAdapter() != null) {
if (mPostRecyclerView.getAdapter() != null) {
((PostRecyclerViewAdapter) mPostRecyclerView.getAdapter()).setCanStartActivity(true);
}
}
@ -187,10 +183,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override
public void run() {
if(isInLazyMode && !isLazyModePaused) {
if (isInLazyMode && !isLazyModePaused) {
int nPosts = mAdapter.getItemCount();
if(getCurrentPosition() == -1) {
if(mLinearLayoutManager != null) {
if (getCurrentPosition() == -1) {
if (mLinearLayoutManager != null) {
setCurrentPosition(mLinearLayoutManager.findFirstVisibleItemPosition());
} else {
int[] into = new int[2];
@ -198,10 +194,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
}
if(getCurrentPosition() != RecyclerView.NO_POSITION && nPosts > getCurrentPosition()) {
if (getCurrentPosition() != RecyclerView.NO_POSITION && nPosts > getCurrentPosition()) {
incrementCurrentPosition();
smoothScroller.setTargetPosition(getCurrentPosition());
if(mLinearLayoutManager != null) {
if (mLinearLayoutManager != null) {
mLinearLayoutManager.startSmoothScroll(smoothScroller);
} else {
mStaggeredGridLayoutManager.startSmoothScroll(smoothScroller);
@ -224,26 +220,26 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
};
if(savedInstanceState != null) {
if (savedInstanceState != null) {
int recyclerViewPosition = savedInstanceState.getInt(RECYCLER_VIEW_POSITION_STATE);
if(recyclerViewPosition > 0) {
if (recyclerViewPosition > 0) {
mPostRecyclerView.scrollToPosition(recyclerViewPosition);
}
isInLazyMode = savedInstanceState.getBoolean(IS_IN_LAZY_MODE_STATE);
if(isInLazyMode) {
if (isInLazyMode) {
resumeLazyMode(false);
}
}
mPostRecyclerView.setOnTouchListener((view, motionEvent) -> {
if(isInLazyMode) {
if (isInLazyMode) {
pauseLazyMode(true);
}
return false;
});
if(activity instanceof MainActivity) {
if (activity instanceof MainActivity) {
mPostRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
@ -255,7 +251,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
});
} else if(activity instanceof ViewSubredditDetailActivity) {
} else if (activity instanceof ViewSubredditDetailActivity) {
mPostRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
@ -280,31 +276,31 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
PostViewModel.Factory factory;
if(postType == PostDataSource.TYPE_SEARCH) {
if (postType == PostDataSource.TYPE_SEARCH) {
String subredditName = getArguments().getString(EXTRA_NAME);
String query = getArguments().getString(EXTRA_QUERY);
mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mRedditDataRoomDatabase,
accessToken, postType, true, needBlurNsfw, needBlurSpoiler,
new PostRecyclerViewAdapter.Callback() {
@Override
public void retryLoadingMore() {
mPostViewModel.retryLoadingMore();
}
@Override
public void retryLoadingMore() {
mPostViewModel.retryLoadingMore();
}
@Override
public void typeChipClicked(int filter) {
Intent intent = new Intent(activity, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, subredditName);
intent.putExtra(FilteredThingActivity.EXTRA_QUERY, query);
intent.putExtra(FilteredThingActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredThingActivity.EXTRA_SORT_TYPE, sortType);
intent.putExtra(FilteredThingActivity.EXTRA_FILTER, filter);
startActivity(intent);
}
});
@Override
public void typeChipClicked(int filter) {
Intent intent = new Intent(activity, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, subredditName);
intent.putExtra(FilteredThingActivity.EXTRA_QUERY, query);
intent.putExtra(FilteredThingActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredThingActivity.EXTRA_SORT_TYPE, sortType);
intent.putExtra(FilteredThingActivity.EXTRA_FILTER, filter);
startActivity(intent);
}
});
if(accessToken == null) {
if (accessToken == null) {
factory = new PostViewModel.Factory(mRetrofit, accessToken,
getResources().getConfiguration().locale, subredditName, query, postType,
sortType, filter, nsfw);
@ -313,30 +309,30 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
getResources().getConfiguration().locale, subredditName, query, postType,
sortType, filter, nsfw);
}
} else if(postType == PostDataSource.TYPE_SUBREDDIT) {
} else if (postType == PostDataSource.TYPE_SUBREDDIT) {
String subredditName = getArguments().getString(EXTRA_NAME);
boolean displaySubredditName = subredditName != null && (subredditName.equals("popular") || subredditName.equals("all"));
mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mRedditDataRoomDatabase,
accessToken, postType, displaySubredditName, needBlurNsfw, needBlurSpoiler,
new PostRecyclerViewAdapter.Callback() {
@Override
public void retryLoadingMore() {
mPostViewModel.retryLoadingMore();
}
@Override
public void retryLoadingMore() {
mPostViewModel.retryLoadingMore();
}
@Override
public void typeChipClicked(int filter) {
Intent intent = new Intent(activity, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, subredditName);
intent.putExtra(FilteredThingActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredThingActivity.EXTRA_SORT_TYPE, sortType);
intent.putExtra(FilteredThingActivity.EXTRA_FILTER, filter);
startActivity(intent);
}
});
@Override
public void typeChipClicked(int filter) {
Intent intent = new Intent(activity, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, subredditName);
intent.putExtra(FilteredThingActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredThingActivity.EXTRA_SORT_TYPE, sortType);
intent.putExtra(FilteredThingActivity.EXTRA_FILTER, filter);
startActivity(intent);
}
});
if(accessToken == null) {
if (accessToken == null) {
factory = new PostViewModel.Factory(mRetrofit, accessToken,
getResources().getConfiguration().locale, subredditName, postType, sortType,
filter, nsfw);
@ -345,10 +341,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
getResources().getConfiguration().locale, subredditName, postType, sortType,
filter, nsfw);
}
} else if(postType == PostDataSource.TYPE_USER) {
} else if (postType == PostDataSource.TYPE_USER) {
String username = getArguments().getString(EXTRA_USER_NAME);
String where = getArguments().getString(EXTRA_USER_WHERE);
if(where != null && where.equals(PostDataSource.USER_WHERE_SUBMITTED)) {
if (where != null && where.equals(PostDataSource.USER_WHERE_SUBMITTED)) {
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mFetchPostInfoLinearLayout.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
mFetchPostInfoLinearLayout.setLayoutParams(params);
@ -357,24 +353,24 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mRedditDataRoomDatabase,
accessToken, postType, true, needBlurNsfw, needBlurSpoiler,
new PostRecyclerViewAdapter.Callback() {
@Override
public void retryLoadingMore() {
mPostViewModel.retryLoadingMore();
}
@Override
public void retryLoadingMore() {
mPostViewModel.retryLoadingMore();
}
@Override
public void typeChipClicked(int filter) {
Intent intent = new Intent(activity, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, username);
intent.putExtra(FilteredThingActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredThingActivity.EXTRA_SORT_TYPE, sortType);
intent.putExtra(FilteredThingActivity.EXTRA_USER_WHERE, where);
intent.putExtra(FilteredThingActivity.EXTRA_FILTER, filter);
startActivity(intent);
}
});
@Override
public void typeChipClicked(int filter) {
Intent intent = new Intent(activity, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, username);
intent.putExtra(FilteredThingActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredThingActivity.EXTRA_SORT_TYPE, sortType);
intent.putExtra(FilteredThingActivity.EXTRA_USER_WHERE, where);
intent.putExtra(FilteredThingActivity.EXTRA_FILTER, filter);
startActivity(intent);
}
});
if(accessToken == null) {
if (accessToken == null) {
factory = new PostViewModel.Factory(mRetrofit, accessToken,
getResources().getConfiguration().locale, username, postType, sortType, where,
filter, nsfw);
@ -387,21 +383,21 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mAdapter = new PostRecyclerViewAdapter(activity, mOauthRetrofit, mRetrofit, mRedditDataRoomDatabase,
accessToken, postType, true, needBlurNsfw, needBlurSpoiler,
new PostRecyclerViewAdapter.Callback() {
@Override
public void retryLoadingMore() {
mPostViewModel.retryLoadingMore();
}
@Override
public void retryLoadingMore() {
mPostViewModel.retryLoadingMore();
}
@Override
public void typeChipClicked(int filter) {
Intent intent = new Intent(activity, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, activity.getString(R.string.best));
intent.putExtra(FilteredThingActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredThingActivity.EXTRA_SORT_TYPE, sortType);
intent.putExtra(FilteredThingActivity.EXTRA_FILTER, filter);
startActivity(intent);
}
});
@Override
public void typeChipClicked(int filter) {
Intent intent = new Intent(activity, FilteredThingActivity.class);
intent.putExtra(FilteredThingActivity.EXTRA_NAME, activity.getString(R.string.best));
intent.putExtra(FilteredThingActivity.EXTRA_POST_TYPE, postType);
intent.putExtra(FilteredThingActivity.EXTRA_SORT_TYPE, sortType);
intent.putExtra(FilteredThingActivity.EXTRA_FILTER, filter);
startActivity(intent);
}
});
factory = new PostViewModel.Factory(mOauthRetrofit, accessToken,
getResources().getConfiguration().locale, postType, sortType, filter, nsfw);
@ -415,22 +411,23 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mPostViewModel.hasPost().observe(this, hasPost -> {
this.hasPost = hasPost;
mProgressBar.setVisibility(View.GONE);
if(hasPost) {
if (hasPost) {
mFetchPostInfoLinearLayout.setVisibility(View.GONE);
} else {
if(isInLazyMode) {
if (isInLazyMode) {
stopLazyMode();
}
mFetchPostInfoLinearLayout.setOnClickListener(view -> {});
mFetchPostInfoLinearLayout.setOnClickListener(view -> {
});
showErrorView(R.string.no_posts);
}
});
mPostViewModel.getInitialLoadingState().observe(this, networkState -> {
if(networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
if (networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
mProgressBar.setVisibility(View.GONE);
} else if(networkState.getStatus().equals(NetworkState.Status.FAILED)) {
} else if (networkState.getStatus().equals(NetworkState.Status.FAILED)) {
mProgressBar.setVisibility(View.GONE);
mFetchPostInfoLinearLayout.setOnClickListener(view -> refresh());
showErrorView(R.string.load_posts_error);
@ -458,9 +455,9 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(IS_IN_LAZY_MODE_STATE, isInLazyMode);
if(mLinearLayoutManager != null) {
if (mLinearLayoutManager != null) {
outState.putInt(RECYCLER_VIEW_POSITION_STATE, mLinearLayoutManager.findFirstVisibleItemPosition());
} else if(mStaggeredGridLayoutManager != null) {
} else if (mStaggeredGridLayoutManager != null) {
int[] into = new int[2];
outState.putInt(RECYCLER_VIEW_POSITION_STATE,
mStaggeredGridLayoutManager.findFirstVisibleItemPositions(into)[0]);
@ -469,7 +466,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override
public void refresh() {
if(isInLazyMode) {
if (isInLazyMode) {
stopLazyMode();
}
@ -480,7 +477,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
}
private void showErrorView(int stringResId) {
if(activity != null && isAdded()) {
if (activity != null && isAdded()) {
mProgressBar.setVisibility(View.GONE);
mFetchPostInfoLinearLayout.setVisibility(View.VISIBLE);
mFetchPostInfoTextView.setText(stringResId);
@ -495,7 +492,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override
public boolean startLazyMode() {
if(!hasPost) {
if (!hasPost) {
Toast.makeText(activity, R.string.no_posts_no_lazy_mode, Toast.LENGTH_SHORT).show();
return false;
}
@ -525,13 +522,13 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override
public void resumeLazyMode(boolean resumeNow) {
if(isInLazyMode) {
if (isInLazyMode) {
isLazyModePaused = false;
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
lazyModeRunnable.resetOldPosition();
if(resumeNow) {
if (resumeNow) {
lazyModeHandler.post(lazyModeRunnable);
} else {
lazyModeHandler.postDelayed(lazyModeRunnable, (long) (lazyModeInterval * 1000));
@ -547,7 +544,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
lazyModeHandler.removeCallbacks(lazyModeRunnable);
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if(startTimer) {
if (startTimer) {
resumeLazyModeCountDownTimer.start();
}
}
@ -590,9 +587,9 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private void refreshAdapter() {
int previousPosition = -1;
if(mLinearLayoutManager != null) {
if (mLinearLayoutManager != null) {
previousPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
} else if(mStaggeredGridLayoutManager != null) {
} else if (mStaggeredGridLayoutManager != null) {
int[] into = new int[2];
previousPosition = mStaggeredGridLayoutManager.findFirstVisibleItemPositions(into)[0];
}
@ -603,7 +600,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mPostRecyclerView.setAdapter(mAdapter);
mPostRecyclerView.setLayoutManager(layoutManager);
if(previousPosition > 0) {
if (previousPosition > 0) {
mPostRecyclerView.scrollToPosition(previousPosition);
}
}
@ -611,7 +608,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override
public void onStart() {
super.onStart();
if(isInLazyMode && isLazyModePaused) {
if (isInLazyMode && isLazyModePaused) {
resumeLazyMode(false);
}
}
@ -619,7 +616,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
@Override
public void onStop() {
super.onStop();
if(isInLazyMode) {
if (isInLazyMode) {
pauseLazyMode(false);
}
}
@ -673,7 +670,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
int halfOffset = mItemOffset / 2;
if(spanIndex == 0) {
if (spanIndex == 0) {
outRect.set(0, 0, halfOffset, 0);
} else {
outRect.set(halfOffset, 0, 0, 0);

View File

@ -24,25 +24,22 @@ import ml.docilealligator.infinityforreddit.R;
*/
public class PostTypeBottomSheetFragment extends RoundedBottomSheetDialogFragment {
public interface PostTypeSelectionCallback {
void postTypeSelected(int postType);
}
public static final int TYPE_TEXT = 0;
public static final int TYPE_LINK = 1;
public static final int TYPE_IMAGE = 2;
public static final int TYPE_VIDEO = 3;
@BindView(R.id.text_type_linear_layout_post_type_bottom_sheet_fragment) LinearLayout textTypeLinearLayout;
@BindView(R.id.link_type_linear_layout_post_type_bottom_sheet_fragment) LinearLayout linkTypeLinearLayout;
@BindView(R.id.image_type_linear_layout_post_type_bottom_sheet_fragment) LinearLayout imageTypeLinearLayout;
@BindView(R.id.video_type_linear_layout_post_type_bottom_sheet_fragment) LinearLayout videoTypeLinearLayout;
@BindView(R.id.text_type_linear_layout_post_type_bottom_sheet_fragment)
LinearLayout textTypeLinearLayout;
@BindView(R.id.link_type_linear_layout_post_type_bottom_sheet_fragment)
LinearLayout linkTypeLinearLayout;
@BindView(R.id.image_type_linear_layout_post_type_bottom_sheet_fragment)
LinearLayout imageTypeLinearLayout;
@BindView(R.id.video_type_linear_layout_post_type_bottom_sheet_fragment)
LinearLayout videoTypeLinearLayout;
public PostTypeBottomSheetFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@ -51,7 +48,7 @@ public class PostTypeBottomSheetFragment extends RoundedBottomSheetDialogFragmen
Activity activity = getActivity();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
@ -79,4 +76,9 @@ public class PostTypeBottomSheetFragment extends RoundedBottomSheetDialogFragmen
return rootView;
}
public interface PostTypeSelectionCallback {
void postTypeSelected(int postType);
}
}

View File

@ -25,21 +25,20 @@ import ml.docilealligator.infinityforreddit.R;
*/
public class SearchPostSortTypeBottomSheetFragment extends RoundedBottomSheetDialogFragment {
public interface SearchSortTypeSelectionCallback {
void searchSortTypeSelected(String sortType);
}
@BindView(R.id.relevance_type_text_view_search_sort_type_bottom_sheet_fragment) TextView relevanceTypeTextView;
@BindView(R.id.hot_type_text_view_search_sort_type_bottom_sheet_fragment) TextView hotTypeTextView;
@BindView(R.id.top_type_text_view_search_sort_type_bottom_sheet_fragment) TextView topTypeTextView;
@BindView(R.id.new_type_text_view_search_sort_type_bottom_sheet_fragment) TextView newTypeTextView;
@BindView(R.id.comments_type_text_view_search_sort_type_bottom_sheet_fragment) TextView commentsTypeTextView;
@BindView(R.id.relevance_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView relevanceTypeTextView;
@BindView(R.id.hot_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView hotTypeTextView;
@BindView(R.id.top_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView topTypeTextView;
@BindView(R.id.new_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView newTypeTextView;
@BindView(R.id.comments_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView commentsTypeTextView;
public SearchPostSortTypeBottomSheetFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@ -48,7 +47,7 @@ public class SearchPostSortTypeBottomSheetFragment extends RoundedBottomSheetDia
Activity activity = getActivity();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
@ -81,4 +80,9 @@ public class SearchPostSortTypeBottomSheetFragment extends RoundedBottomSheetDia
return rootView;
}
public interface SearchSortTypeSelectionCallback {
void searchSortTypeSelected(String sortType);
}
}

View File

@ -25,20 +25,15 @@ import ml.docilealligator.infinityforreddit.R;
*/
public class SearchUserAndSubredditSortTypeBottomSheetFragment extends RoundedBottomSheetDialogFragment {
public interface SearchUserAndSubredditSortTypeSelectionCallback {
void searchUserAndSubredditSortTypeSelected(String sortType, int fragmentPosition);
}
public static final String EXTRA_FRAGMENT_POSITION = "EFP";
@BindView(R.id.relevance_type_text_view_search_user_and_subreddit_sort_type_bottom_sheet_fragment) TextView relevanceTypeTextView;
@BindView(R.id.activity_type_text_view_search_user_and_subreddit_sort_type_bottom_sheet_fragment) TextView activityTypeTextView;
@BindView(R.id.relevance_type_text_view_search_user_and_subreddit_sort_type_bottom_sheet_fragment)
TextView relevanceTypeTextView;
@BindView(R.id.activity_type_text_view_search_user_and_subreddit_sort_type_bottom_sheet_fragment)
TextView activityTypeTextView;
public SearchUserAndSubredditSortTypeBottomSheetFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@ -47,7 +42,7 @@ public class SearchUserAndSubredditSortTypeBottomSheetFragment extends RoundedBo
Activity activity = getActivity();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
@ -67,4 +62,9 @@ public class SearchUserAndSubredditSortTypeBottomSheetFragment extends RoundedBo
return rootView;
}
public interface SearchUserAndSubredditSortTypeSelectionCallback {
void searchUserAndSubredditSortTypeSelected(String sortType, int fragmentPosition);
}
}

View File

@ -26,25 +26,25 @@ import ml.docilealligator.infinityforreddit.R;
*/
public class SortTypeBottomSheetFragment extends RoundedBottomSheetDialogFragment {
public interface SortTypeSelectionCallback {
void sortTypeSelected(String sortType);
}
public static final String EXTRA_NO_BEST_TYPE = "ENBT";
@BindView(R.id.best_type_text_view_sort_type_bottom_sheet_fragment) TextView bestTypeTextView;
@BindView(R.id.hot_type_text_view_sort_type_bottom_sheet_fragment) TextView hotTypeTextView;
@BindView(R.id.new_type_text_view_sort_type_bottom_sheet_fragment) TextView newTypeTextView;
@BindView(R.id.random_type_text_view_sort_type_bottom_sheet_fragment) TextView randomTypeTextView;
@BindView(R.id.rising_type_text_view_sort_type_bottom_sheet_fragment) TextView risingTypeTextView;
@BindView(R.id.top_type_text_view_sort_type_bottom_sheet_fragment) TextView topTypeTextView;
@BindView(R.id.controversial_type_text_view_sort_type_bottom_sheet_fragment) TextView controversialTypeTextView;
@BindView(R.id.best_type_text_view_sort_type_bottom_sheet_fragment)
TextView bestTypeTextView;
@BindView(R.id.hot_type_text_view_sort_type_bottom_sheet_fragment)
TextView hotTypeTextView;
@BindView(R.id.new_type_text_view_sort_type_bottom_sheet_fragment)
TextView newTypeTextView;
@BindView(R.id.random_type_text_view_sort_type_bottom_sheet_fragment)
TextView randomTypeTextView;
@BindView(R.id.rising_type_text_view_sort_type_bottom_sheet_fragment)
TextView risingTypeTextView;
@BindView(R.id.top_type_text_view_sort_type_bottom_sheet_fragment)
TextView topTypeTextView;
@BindView(R.id.controversial_type_text_view_sort_type_bottom_sheet_fragment)
TextView controversialTypeTextView;
public SortTypeBottomSheetFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@ -53,12 +53,12 @@ public class SortTypeBottomSheetFragment extends RoundedBottomSheetDialogFragmen
Activity activity = getActivity();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
if(getArguments().getBoolean(EXTRA_NO_BEST_TYPE)) {
if (getArguments().getBoolean(EXTRA_NO_BEST_TYPE)) {
bestTypeTextView.setVisibility(View.GONE);
} else {
bestTypeTextView.setOnClickListener(view -> {
@ -100,4 +100,9 @@ public class SortTypeBottomSheetFragment extends RoundedBottomSheetDialogFragmen
return rootView;
}
public interface SortTypeSelectionCallback {
void sortTypeSelected(String sortType);
}
}

View File

@ -31,13 +31,13 @@ import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.Activity.SearchSubredditsResultActivity;
import ml.docilealligator.infinityforreddit.Activity.ViewSubredditDetailActivity;
import ml.docilealligator.infinityforreddit.Adapter.SubredditListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.NetworkState;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.Adapter.SubredditListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.SubredditListingViewModel;
import retrofit2.Retrofit;
@ -52,27 +52,29 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_ACCOUNT_NAME = "EAN";
@BindView(R.id.coordinator_layout_subreddit_listing_fragment) CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.recycler_view_subreddit_listing_fragment) RecyclerView mSubredditListingRecyclerView;
@BindView(R.id.progress_bar_subreddit_listing_fragment) CircleProgressBar mProgressBar;
@BindView(R.id.fetch_subreddit_listing_info_linear_layout_subreddit_listing_fragment) LinearLayout mFetchSubredditListingInfoLinearLayout;
@BindView(R.id.fetch_subreddit_listing_info_image_view_subreddit_listing_fragment) ImageView mFetchSubredditListingInfoImageView;
@BindView(R.id.fetch_subreddit_listing_info_text_view_subreddit_listing_fragment) TextView mFetchSubredditListingInfoTextView;
private LinearLayoutManager mLinearLayoutManager;
private SubredditListingRecyclerViewAdapter mAdapter;
@BindView(R.id.coordinator_layout_subreddit_listing_fragment)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.recycler_view_subreddit_listing_fragment)
RecyclerView mSubredditListingRecyclerView;
@BindView(R.id.progress_bar_subreddit_listing_fragment)
CircleProgressBar mProgressBar;
@BindView(R.id.fetch_subreddit_listing_info_linear_layout_subreddit_listing_fragment)
LinearLayout mFetchSubredditListingInfoLinearLayout;
@BindView(R.id.fetch_subreddit_listing_info_image_view_subreddit_listing_fragment)
ImageView mFetchSubredditListingInfoImageView;
@BindView(R.id.fetch_subreddit_listing_info_text_view_subreddit_listing_fragment)
TextView mFetchSubredditListingInfoTextView;
SubredditListingViewModel mSubredditListingViewModel;
@Inject @Named("no_oauth")
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject @Named("oauth")
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase redditDataRoomDatabase;
private LinearLayoutManager mLinearLayoutManager;
private SubredditListingRecyclerViewAdapter mAdapter;
public SubredditListingFragment() {
// Required empty public constructor
@ -120,7 +122,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
@Override
public void subredditSelected(String subredditName, String iconUrl) {
if(isPosting) {
if (isPosting) {
((SearchSubredditsResultActivity) activity).getSelectedSubreddit(subredditName, iconUrl);
} else {
Intent intent = new Intent(activity, ViewSubredditDetailActivity.class);
@ -139,7 +141,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
mSubredditListingViewModel.hasSubredditLiveData().observe(this, hasSubreddit -> {
mProgressBar.setVisibility(View.GONE);
if(hasSubreddit) {
if (hasSubreddit) {
mFetchSubredditListingInfoLinearLayout.setVisibility(View.GONE);
} else {
mFetchSubredditListingInfoLinearLayout.setOnClickListener(view -> {
@ -150,9 +152,9 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
});
mSubredditListingViewModel.getInitialLoadingState().observe(this, networkState -> {
if(networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
if (networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
mProgressBar.setVisibility(View.GONE);
} else if(networkState.getStatus().equals(NetworkState.Status.FAILED)) {
} else if (networkState.getStatus().equals(NetworkState.Status.FAILED)) {
mProgressBar.setVisibility(View.GONE);
mFetchSubredditListingInfoLinearLayout.setOnClickListener(view -> refresh());
showErrorView(R.string.search_subreddits_error);
@ -169,7 +171,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
}
private void showErrorView(int stringResId) {
if(getActivity() != null && isAdded()) {
if (getActivity() != null && isAdded()) {
mProgressBar.setVisibility(View.GONE);
mFetchSubredditListingInfoLinearLayout.setVisibility(View.VISIBLE);
mFetchSubredditListingInfoTextView.setText(stringResId);

View File

@ -43,18 +43,17 @@ public class SubscribedSubredditsListingFragment extends Fragment {
public static final String EXTRA_IS_SUBREDDIT_SELECTION = "EISS";
public static final String EXTRA_EXTRA_CLEAR_SELECTION = "EECS";
@BindView(R.id.recycler_view_subscribed_subreddits_listing_fragment) RecyclerView mRecyclerView;
@BindView(R.id.no_subscriptions_linear_layout_subreddits_listing_fragment) LinearLayout mLinearLayout;
@BindView(R.id.no_subscriptions_image_view_subreddits_listing_fragment) ImageView mImageView;
private Activity mActivity;
private RequestManager mGlide;
private SubscribedSubredditViewModel mSubscribedSubredditViewModel;
@BindView(R.id.recycler_view_subscribed_subreddits_listing_fragment)
RecyclerView mRecyclerView;
@BindView(R.id.no_subscriptions_linear_layout_subreddits_listing_fragment)
LinearLayout mLinearLayout;
@BindView(R.id.no_subscriptions_image_view_subreddits_listing_fragment)
ImageView mImageView;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
private Activity mActivity;
private RequestManager mGlide;
private SubscribedSubredditViewModel mSubscribedSubredditViewModel;
public SubscribedSubredditsListingFragment() {
// Required empty public constructor
@ -89,7 +88,7 @@ public class SubscribedSubredditsListingFragment extends Fragment {
mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
SubscribedSubredditsRecyclerViewAdapter adapter;
if(getArguments().getBoolean(EXTRA_IS_SUBREDDIT_SELECTION)) {
if (getArguments().getBoolean(EXTRA_IS_SUBREDDIT_SELECTION)) {
adapter = new SubscribedSubredditsRecyclerViewAdapter(mActivity, getArguments().getBoolean(EXTRA_EXTRA_CLEAR_SELECTION),
(name, iconUrl, subredditIsUser) -> ((SubredditSelectionActivity) mActivity).getSelectedSubreddit(name, iconUrl, subredditIsUser));
} else {

View File

@ -26,13 +26,13 @@ import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import ml.docilealligator.infinityforreddit.Adapter.UserListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.FragmentCommunicator;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.NetworkState;
import ml.docilealligator.infinityforreddit.PostDataSource;
import ml.docilealligator.infinityforreddit.R;
import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.Adapter.UserListingRecyclerViewAdapter;
import ml.docilealligator.infinityforreddit.UserListingViewModel;
import retrofit2.Retrofit;
@ -46,29 +46,30 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_ACCOUNT_NAME = "EAN";
@BindView(R.id.coordinator_layout_user_listing_fragment) CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.recycler_view_user_listing_fragment) RecyclerView mUserListingRecyclerView;
@BindView(R.id.progress_bar_user_listing_fragment) CircleProgressBar mProgressBar;
@BindView(R.id.fetch_user_listing_info_linear_layout_user_listing_fragment) LinearLayout mFetchUserListingInfoLinearLayout;
@BindView(R.id.fetch_user_listing_info_image_view_user_listing_fragment) ImageView mFetchUserListingInfoImageView;
@BindView(R.id.fetch_user_listing_info_text_view_user_listing_fragment) TextView mFetchUserListingInfoTextView;
private LinearLayoutManager mLinearLayoutManager;
private String mQuery;
private UserListingRecyclerViewAdapter mAdapter;
@BindView(R.id.coordinator_layout_user_listing_fragment)
CoordinatorLayout mCoordinatorLayout;
@BindView(R.id.recycler_view_user_listing_fragment)
RecyclerView mUserListingRecyclerView;
@BindView(R.id.progress_bar_user_listing_fragment)
CircleProgressBar mProgressBar;
@BindView(R.id.fetch_user_listing_info_linear_layout_user_listing_fragment)
LinearLayout mFetchUserListingInfoLinearLayout;
@BindView(R.id.fetch_user_listing_info_image_view_user_listing_fragment)
ImageView mFetchUserListingInfoImageView;
@BindView(R.id.fetch_user_listing_info_text_view_user_listing_fragment)
TextView mFetchUserListingInfoTextView;
UserListingViewModel mUserListingViewModel;
@Inject @Named("no_oauth")
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject @Named("oauth")
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
RedditDataRoomDatabase redditDataRoomDatabase;
private LinearLayoutManager mLinearLayoutManager;
private String mQuery;
private UserListingRecyclerViewAdapter mAdapter;
public UserListingFragment() {
// Required empty public constructor
@ -116,7 +117,7 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
mUserListingViewModel.hasUser().observe(this, hasUser -> {
mProgressBar.setVisibility(View.GONE);
if(hasUser) {
if (hasUser) {
mFetchUserListingInfoLinearLayout.setVisibility(View.GONE);
} else {
mFetchUserListingInfoLinearLayout.setOnClickListener(view -> {
@ -127,9 +128,9 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
});
mUserListingViewModel.getInitialLoadingState().observe(this, networkState -> {
if(networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
if (networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
mProgressBar.setVisibility(View.GONE);
} else if(networkState.getStatus().equals(NetworkState.Status.FAILED)) {
} else if (networkState.getStatus().equals(NetworkState.Status.FAILED)) {
mProgressBar.setVisibility(View.GONE);
mFetchUserListingInfoLinearLayout.setOnClickListener(view -> refresh());
showErrorView(R.string.search_users_error);
@ -146,7 +147,7 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
}
private void showErrorView(int stringResId) {
if(getActivity() != null && isAdded()) {
if (getActivity() != null && isAdded()) {
mProgressBar.setVisibility(View.GONE);
mFetchUserListingInfoLinearLayout.setVisibility(View.VISIBLE);
mFetchUserListingInfoTextView.setText(stringResId);

View File

@ -26,22 +26,19 @@ import ml.docilealligator.infinityforreddit.R;
*/
public class UserThingSortTypeBottomSheetFragment extends RoundedBottomSheetDialogFragment {
public interface UserThingSortTypeSelectionCallback {
void userThingSortTypeSelected(String sortType);
}
static final String EXTRA_NO_BEST_TYPE = "ENBT";
@BindView(R.id.new_type_text_view_user_thing_sort_type_bottom_sheet_fragment) TextView newTypeTextView;
@BindView(R.id.hot_type_text_view_user_thing_sort_type_bottom_sheet_fragment) TextView hotTypeTextView;
@BindView(R.id.top_type_text_view_user_thing_sort_type_bottom_sheet_fragment) TextView topTypeTextView;
@BindView(R.id.controversial_type_text_view_user_thing_sort_type_bottom_sheet_fragment) TextView controversialTypeTextView;
@BindView(R.id.new_type_text_view_user_thing_sort_type_bottom_sheet_fragment)
TextView newTypeTextView;
@BindView(R.id.hot_type_text_view_user_thing_sort_type_bottom_sheet_fragment)
TextView hotTypeTextView;
@BindView(R.id.top_type_text_view_user_thing_sort_type_bottom_sheet_fragment)
TextView topTypeTextView;
@BindView(R.id.controversial_type_text_view_user_thing_sort_type_bottom_sheet_fragment)
TextView controversialTypeTextView;
public UserThingSortTypeBottomSheetFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
@ -51,34 +48,34 @@ public class UserThingSortTypeBottomSheetFragment extends RoundedBottomSheetDial
Activity activity = getActivity();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES) {
rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
newTypeTextView.setOnClickListener(view -> {
if(activity != null) {
if (activity != null) {
((UserThingSortTypeSelectionCallback) activity).userThingSortTypeSelected(PostDataSource.SORT_TYPE_NEW);
}
dismiss();
});
hotTypeTextView.setOnClickListener(view -> {
if(activity != null) {
if (activity != null) {
((UserThingSortTypeSelectionCallback) activity).userThingSortTypeSelected(PostDataSource.SORT_TYPE_HOT);
}
dismiss();
});
topTypeTextView.setOnClickListener(view -> {
if(activity != null) {
if (activity != null) {
((UserThingSortTypeSelectionCallback) activity).userThingSortTypeSelected(PostDataSource.SORT_TYPE_TOP);
}
dismiss();
});
controversialTypeTextView.setOnClickListener(view -> {
if(activity != null) {
if (activity != null) {
((UserThingSortTypeSelectionCallback) activity).userThingSortTypeSelected(PostDataSource.SORT_TYPE_CONTROVERSIAL);
}
dismiss();
@ -87,4 +84,9 @@ public class UserThingSortTypeBottomSheetFragment extends RoundedBottomSheetDial
return rootView;
}
public interface UserThingSortTypeSelectionCallback {
void userThingSortTypeSelected(String sortType);
}
}

View File

@ -2,13 +2,23 @@ package ml.docilealligator.infinityforreddit;
public interface FragmentCommunicator {
void refresh();
default void changeNSFW(boolean nsfw) {};
default void changeNSFW(boolean nsfw) {
}
default boolean startLazyMode() {
return false;
}
default void stopLazyMode() {}
default void resumeLazyMode(boolean resumeNow) {}
default void pauseLazyMode(boolean startTimer) {}
default void stopLazyMode() {
}
default void resumeLazyMode(boolean resumeNow) {
}
default void pauseLazyMode(boolean startTimer) {
}
default boolean isInLazyMode() {
return false;
}

View File

@ -11,11 +11,6 @@ import retrofit2.Response;
import retrofit2.Retrofit;
public class HidePost {
public interface HidePostListener {
void success();
void failed();
}
public static void hidePost(Retrofit oauthRetrofit, String accessToken, String fullname,
HidePostListener hidePostListener) {
Map<String, String> params = new HashMap<>();
@ -23,7 +18,7 @@ public class HidePost {
oauthRetrofit.create(RedditAPI.class).hide(RedditUtils.getOAuthHeader(accessToken), params).enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
hidePostListener.success();
} else {
hidePostListener.failed();
@ -44,7 +39,7 @@ public class HidePost {
oauthRetrofit.create(RedditAPI.class).unhide(RedditUtils.getOAuthHeader(accessToken), params).enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
hidePostListener.success();
} else {
hidePostListener.failed();
@ -57,4 +52,10 @@ public class HidePost {
}
});
}
public interface HidePostListener {
void success();
void failed();
}
}

View File

@ -1,7 +1,5 @@
package ml.docilealligator.infinityforreddit;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
@ -58,13 +56,13 @@ class MessageDataSource extends PageKeyedDataSource<String, Message> {
FetchMessages.fetchMessagesAsync(oauthRetrofit, locale, accessToken, where, null, new FetchMessages.FetchMessagesListener() {
@Override
public void fetchSuccess(ArrayList<Message> messages, @Nullable String after) {
if(messages.size() == 0) {
if (messages.size() == 0) {
hasPostLiveData.postValue(false);
} else {
hasPostLiveData.postValue(true);
}
if(after == null || after.equals("") || after.equals("null")) {
if (after == null || after.equals("") || after.equals("null")) {
callback.onResult(messages, null, null);
} else {
callback.onResult(messages, null, after);
@ -94,7 +92,7 @@ class MessageDataSource extends PageKeyedDataSource<String, Message> {
FetchMessages.fetchMessagesAsync(oauthRetrofit, locale, accessToken, where, params.key, new FetchMessages.FetchMessagesListener() {
@Override
public void fetchSuccess(ArrayList<Message> messages, @Nullable String after) {
if(after == null || after.equals("") || after.equals("null")) {
if (after == null || after.equals("") || after.equals("null")) {
callback.onResult(messages, null);
} else {
callback.onResult(messages, after);

View File

@ -1,29 +1,22 @@
package ml.docilealligator.infinityforreddit;
public class NetworkState {
public enum Status{
LOADING,
SUCCESS,
FAILED
}
static final NetworkState LOADED;
static final NetworkState LOADING;
static {
LOADED = new NetworkState(Status.SUCCESS, "Success");
LOADING = new NetworkState(Status.LOADING, "Loading");
}
private final Status status;
private final String msg;
static final NetworkState LOADED;
static final NetworkState LOADING;
NetworkState(Status status, String msg) {
this.status = status;
this.msg = msg;
}
static {
LOADED=new NetworkState(Status.SUCCESS,"Success");
LOADING=new NetworkState(Status.LOADING,"Loading");
}
public Status getStatus() {
return status;
}
@ -31,4 +24,10 @@ public class NetworkState {
public String getMsg() {
return msg;
}
public enum Status {
LOADING,
SUCCESS,
FAILED
}
}

View File

@ -7,16 +7,17 @@ import org.json.JSONException;
import org.json.JSONObject;
public class ParseAndSaveAccountInfo {
public interface ParseAndSaveAccountInfoListener {
void onParseMyInfoSuccess(String name, String profileImageUrl, String bannerImageUrl, int karma);
void onParseMyInfoFail();
}
public static void parseAndSaveAccountInfo(String response, RedditDataRoomDatabase redditDataRoomDatabase,
ParseAndSaveAccountInfoListener parseAndSaveAccountInfoListener) {
new ParseAndSaveAccountInfoAsyncTask(response, redditDataRoomDatabase, parseAndSaveAccountInfoListener).execute();
}
public interface ParseAndSaveAccountInfoListener {
void onParseMyInfoSuccess(String name, String profileImageUrl, String bannerImageUrl, int karma);
void onParseMyInfoFail();
}
private static class ParseAndSaveAccountInfoAsyncTask extends AsyncTask<Void, Void, Void> {
private JSONObject jsonResponse;
private RedditDataRoomDatabase redditDataRoomDatabase;
@ -29,7 +30,7 @@ public class ParseAndSaveAccountInfo {
private int karma;
ParseAndSaveAccountInfoAsyncTask(String response, RedditDataRoomDatabase redditDataRoomDatabase,
ParseAndSaveAccountInfoListener parseAndSaveAccountInfoListener){
ParseAndSaveAccountInfoListener parseAndSaveAccountInfoListener) {
try {
jsonResponse = new JSONObject(response);
this.redditDataRoomDatabase = redditDataRoomDatabase;
@ -45,7 +46,7 @@ public class ParseAndSaveAccountInfo {
try {
name = jsonResponse.getString(JSONUtils.NAME_KEY);
profileImageUrl = Html.fromHtml(jsonResponse.getString(JSONUtils.ICON_IMG_KEY)).toString();
if(!jsonResponse.isNull(JSONUtils.SUBREDDIT_KEY)) {
if (!jsonResponse.isNull(JSONUtils.SUBREDDIT_KEY)) {
bannerImageUrl = Html.fromHtml(jsonResponse.getJSONObject(JSONUtils.SUBREDDIT_KEY).getString(JSONUtils.BANNER_IMG_KEY)).toString();
}
int linkKarma = jsonResponse.getInt(JSONUtils.LINK_KARMA_KEY);
@ -61,7 +62,7 @@ public class ParseAndSaveAccountInfo {
@Override
protected void onPostExecute(Void aVoid) {
if(!parseFailed) {
if (!parseFailed) {
parseAndSaveAccountInfoListener.onParseMyInfoSuccess(name, profileImageUrl, bannerImageUrl, karma);
} else {
parseAndSaveAccountInfoListener.onParseMyInfoFail();

View File

@ -19,17 +19,6 @@ import static ml.docilealligator.infinityforreddit.CommentData.VOTE_TYPE_NO_VOTE
import static ml.docilealligator.infinityforreddit.CommentData.VOTE_TYPE_UPVOTE;
public class ParseComment {
public interface ParseCommentListener {
void onParseCommentSuccess(ArrayList<CommentData> expandedComments, String parentId,
ArrayList<String> moreChildrenFullnames);
void onParseCommentFailed();
}
interface ParseSentCommentListener {
void onParseSentCommentSuccess(CommentData commentData);
void onParseSentCommentFailed(@Nullable String errorMessage);
}
public static void parseComment(String response, ArrayList<CommentData> commentData, Locale locale,
ParseCommentListener parseCommentListener) {
try {
@ -61,6 +50,150 @@ public class ParseComment {
new ParseSentCommentAsyncTask(response, depth, locale, parseSentCommentListener).execute();
}
private static void parseCommentRecursion(JSONArray comments, ArrayList<CommentData> newCommentData,
ArrayList<String> moreChildrenFullnames, int depth, Locale locale) throws JSONException {
int actualCommentLength;
if (comments.length() == 0) {
return;
}
JSONObject more = comments.getJSONObject(comments.length() - 1).getJSONObject(JSONUtils.DATA_KEY);
//Maybe moreChildrenFullnames contain only commentsJSONArray and no more info
if (more.has(JSONUtils.COUNT_KEY)) {
JSONArray childrenArray = more.getJSONArray(JSONUtils.CHILDREN_KEY);
for (int i = 0; i < childrenArray.length(); i++) {
moreChildrenFullnames.add("t1_" + childrenArray.getString(i));
}
actualCommentLength = comments.length() - 1;
} else {
actualCommentLength = comments.length();
}
for (int i = 0; i < actualCommentLength; i++) {
JSONObject data = comments.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
CommentData singleComment = parseSingleComment(data, depth, locale);
if (data.get(JSONUtils.REPLIES_KEY) instanceof JSONObject) {
JSONArray childrenArray = data.getJSONObject(JSONUtils.REPLIES_KEY)
.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
ArrayList<CommentData> children = new ArrayList<>();
ArrayList<String> nextMoreChildrenFullnames = new ArrayList<>();
parseCommentRecursion(childrenArray, children, nextMoreChildrenFullnames, singleComment.getDepth(),
locale);
singleComment.addChildren(children);
singleComment.setMoreChildrenFullnames(nextMoreChildrenFullnames);
}
newCommentData.add(singleComment);
}
}
private static void expandChildren(ArrayList<CommentData> comments, ArrayList<CommentData> visibleComments) {
for (CommentData c : comments) {
visibleComments.add(c);
if (c.hasReply()) {
c.setExpanded(true);
expandChildren(c.getChildren(), visibleComments);
}
if (c.hasMoreChildrenFullnames() && c.getMoreChildrenFullnames().size() > c.getMoreChildrenStartingIndex()) {
//Add a load more placeholder
CommentData placeholder = new CommentData(c.getFullName(), c.getDepth() + 1);
visibleComments.add(placeholder);
c.addChild(placeholder, c.getChildren().size());
}
}
}
static CommentData parseSingleComment(JSONObject singleCommentData, int depth, Locale locale) throws JSONException {
String id = singleCommentData.getString(JSONUtils.ID_KEY);
String fullName = singleCommentData.getString(JSONUtils.NAME_KEY);
String author = singleCommentData.getString(JSONUtils.AUTHOR_KEY);
String linkAuthor = singleCommentData.has(JSONUtils.LINK_AUTHOR_KEY) ? singleCommentData.getString(JSONUtils.LINK_AUTHOR_KEY) : null;
String linkId = singleCommentData.getString(JSONUtils.LINK_ID_KEY).substring(3);
String subredditName = singleCommentData.getString(JSONUtils.SUBREDDIT_KEY);
String parentId = singleCommentData.getString(JSONUtils.PARENT_ID_KEY);
boolean isSubmitter = singleCommentData.getBoolean(JSONUtils.IS_SUBMITTER_KEY);
String distinguished = singleCommentData.getString(JSONUtils.DISTINGUISHED_KEY);
String commentContent = "";
if (!singleCommentData.isNull(JSONUtils.BODY_KEY)) {
commentContent = Utils.addSubredditAndUserLink(singleCommentData.getString(JSONUtils.BODY_KEY).trim());
}
String permalink = Html.fromHtml(singleCommentData.getString(JSONUtils.PERMALINK_KEY)).toString();
int score = singleCommentData.getInt(JSONUtils.SCORE_KEY);
int voteType;
if (singleCommentData.isNull(JSONUtils.LIKES_KEY)) {
voteType = VOTE_TYPE_NO_VOTE;
} else {
voteType = singleCommentData.getBoolean(JSONUtils.LIKES_KEY) ? VOTE_TYPE_UPVOTE : VOTE_TYPE_DOWNVOTE;
score -= voteType;
}
long submitTime = singleCommentData.getLong(JSONUtils.CREATED_UTC_KEY) * 1000;
boolean scoreHidden = singleCommentData.getBoolean(JSONUtils.SCORE_HIDDEN_KEY);
boolean saved = singleCommentData.getBoolean(JSONUtils.SAVED_KEY);
Calendar submitTimeCalendar = Calendar.getInstance();
submitTimeCalendar.setTimeInMillis(submitTime);
String formattedSubmitTime = new SimpleDateFormat("MMM d, yyyy, HH:mm",
locale).format(submitTimeCalendar.getTime());
if (singleCommentData.has(JSONUtils.DEPTH_KEY)) {
depth = singleCommentData.getInt(JSONUtils.DEPTH_KEY);
}
boolean collapsed = singleCommentData.getBoolean(JSONUtils.COLLAPSED_KEY);
boolean hasReply = !(singleCommentData.get(JSONUtils.REPLIES_KEY) instanceof String);
return new CommentData(id, fullName, author, linkAuthor, formattedSubmitTime, commentContent,
linkId, subredditName, parentId, score, voteType, isSubmitter, distinguished,
permalink, depth, collapsed, hasReply, scoreHidden, saved);
}
@Nullable
private static String parseSentCommentErrorMessage(String response) {
try {
JSONObject responseObject = new JSONObject(response).getJSONObject(JSONUtils.JSON_KEY);
if (responseObject.getJSONArray(JSONUtils.ERRORS_KEY).length() != 0) {
JSONArray error = responseObject.getJSONArray(JSONUtils.ERRORS_KEY)
.getJSONArray(responseObject.getJSONArray(JSONUtils.ERRORS_KEY).length() - 1);
if (error.length() != 0) {
String errorString;
if (error.length() >= 2) {
errorString = error.getString(1);
} else {
errorString = error.getString(0);
}
return errorString.substring(0, 1).toUpperCase() + errorString.substring(1);
} else {
return null;
}
} else {
return null;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public interface ParseCommentListener {
void onParseCommentSuccess(ArrayList<CommentData> expandedComments, String parentId,
ArrayList<String> moreChildrenFullnames);
void onParseCommentFailed();
}
interface ParseSentCommentListener {
void onParseSentCommentSuccess(CommentData commentData);
void onParseSentCommentFailed(@Nullable String errorMessage);
}
private static class ParseCommentAsyncTask extends AsyncTask<Void, Void, Void> {
private JSONArray commentsJSONArray;
private ArrayList<CommentData> comments;
@ -74,7 +207,7 @@ public class ParseComment {
private boolean parseFailed;
ParseCommentAsyncTask(JSONArray commentsJSONArray, ArrayList<CommentData> comments, Locale locale,
@Nullable String parentId, int depth, ParseCommentListener parseCommentListener){
@Nullable String parentId, int depth, ParseCommentListener parseCommentListener) {
this.commentsJSONArray = commentsJSONArray;
this.comments = comments;
newComments = new ArrayList<>();
@ -100,7 +233,7 @@ public class ParseComment {
@Override
protected void onPostExecute(Void aVoid) {
if(!parseFailed) {
if (!parseFailed) {
comments.addAll(expandedNewComments);
parseCommentListener.onParseCommentSuccess(comments, parentId, moreChildrenFullnames);
} else {
@ -109,64 +242,6 @@ public class ParseComment {
}
}
private static void parseCommentRecursion(JSONArray comments, ArrayList<CommentData> newCommentData,
ArrayList<String> moreChildrenFullnames, int depth, Locale locale) throws JSONException {
int actualCommentLength;
if(comments.length() == 0) {
return;
}
JSONObject more = comments.getJSONObject(comments.length() - 1).getJSONObject(JSONUtils.DATA_KEY);
//Maybe moreChildrenFullnames contain only commentsJSONArray and no more info
if(more.has(JSONUtils.COUNT_KEY)) {
JSONArray childrenArray = more.getJSONArray(JSONUtils.CHILDREN_KEY);
for(int i = 0; i < childrenArray.length(); i++) {
moreChildrenFullnames.add("t1_" + childrenArray.getString(i));
}
actualCommentLength = comments.length() - 1;
} else {
actualCommentLength = comments.length();
}
for (int i = 0; i < actualCommentLength; i++) {
JSONObject data = comments.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
CommentData singleComment = parseSingleComment(data, depth, locale);
if(data.get(JSONUtils.REPLIES_KEY) instanceof JSONObject) {
JSONArray childrenArray = data.getJSONObject(JSONUtils.REPLIES_KEY)
.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
ArrayList<CommentData> children = new ArrayList<>();
ArrayList<String> nextMoreChildrenFullnames = new ArrayList<>();
parseCommentRecursion(childrenArray, children, nextMoreChildrenFullnames, singleComment.getDepth(),
locale);
singleComment.addChildren(children);
singleComment.setMoreChildrenFullnames(nextMoreChildrenFullnames);
}
newCommentData.add(singleComment);
}
}
private static void expandChildren(ArrayList<CommentData> comments, ArrayList<CommentData> visibleComments) {
for(CommentData c : comments) {
visibleComments.add(c);
if(c.hasReply()) {
c.setExpanded(true);
expandChildren(c.getChildren(), visibleComments);
}
if(c.hasMoreChildrenFullnames() && c.getMoreChildrenFullnames().size() > c.getMoreChildrenStartingIndex()) {
//Add a load more placeholder
CommentData placeholder = new CommentData(c.getFullName(), c.getDepth() + 1);
visibleComments.add(placeholder);
c.addChild(placeholder, c.getChildren().size());
}
}
}
private static class ParseSentCommentAsyncTask extends AsyncTask<Void, Void, Void> {
private String response;
private int depth;
@ -200,84 +275,11 @@ public class ParseComment {
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(parseFailed) {
if (parseFailed) {
parseSentCommentListener.onParseSentCommentFailed(errorMessage);
} else {
parseSentCommentListener.onParseSentCommentSuccess(commentData);
}
}
}
static CommentData parseSingleComment(JSONObject singleCommentData, int depth, Locale locale) throws JSONException {
String id = singleCommentData.getString(JSONUtils.ID_KEY);
String fullName = singleCommentData.getString(JSONUtils.NAME_KEY);
String author = singleCommentData.getString(JSONUtils.AUTHOR_KEY);
String linkAuthor = singleCommentData.has(JSONUtils.LINK_AUTHOR_KEY) ? singleCommentData.getString(JSONUtils.LINK_AUTHOR_KEY) : null;
String linkId = singleCommentData.getString(JSONUtils.LINK_ID_KEY).substring(3);
String subredditName = singleCommentData.getString(JSONUtils.SUBREDDIT_KEY);
String parentId = singleCommentData.getString(JSONUtils.PARENT_ID_KEY);
boolean isSubmitter = singleCommentData.getBoolean(JSONUtils.IS_SUBMITTER_KEY);
String distinguished = singleCommentData.getString(JSONUtils.DISTINGUISHED_KEY);
String commentContent = "";
if(!singleCommentData.isNull(JSONUtils.BODY_KEY)) {
commentContent = Utils.addSubredditAndUserLink(singleCommentData.getString(JSONUtils.BODY_KEY).trim());
}
String permalink = Html.fromHtml(singleCommentData.getString(JSONUtils.PERMALINK_KEY)).toString();
int score = singleCommentData.getInt(JSONUtils.SCORE_KEY);
int voteType;
if(singleCommentData.isNull(JSONUtils.LIKES_KEY)) {
voteType = VOTE_TYPE_NO_VOTE;
} else {
voteType = singleCommentData.getBoolean(JSONUtils.LIKES_KEY) ? VOTE_TYPE_UPVOTE : VOTE_TYPE_DOWNVOTE;
score -= voteType;
}
long submitTime = singleCommentData.getLong(JSONUtils.CREATED_UTC_KEY) * 1000;
boolean scoreHidden = singleCommentData.getBoolean(JSONUtils.SCORE_HIDDEN_KEY);
boolean saved = singleCommentData.getBoolean(JSONUtils.SAVED_KEY);
Calendar submitTimeCalendar = Calendar.getInstance();
submitTimeCalendar.setTimeInMillis(submitTime);
String formattedSubmitTime = new SimpleDateFormat("MMM d, yyyy, HH:mm",
locale).format(submitTimeCalendar.getTime());
if(singleCommentData.has(JSONUtils.DEPTH_KEY)) {
depth = singleCommentData.getInt(JSONUtils.DEPTH_KEY);
}
boolean collapsed = singleCommentData.getBoolean(JSONUtils.COLLAPSED_KEY);
boolean hasReply = !(singleCommentData.get(JSONUtils.REPLIES_KEY) instanceof String);
return new CommentData(id, fullName, author, linkAuthor, formattedSubmitTime, commentContent,
linkId, subredditName, parentId, score, voteType, isSubmitter, distinguished,
permalink, depth, collapsed, hasReply, scoreHidden, saved);
}
@Nullable
private static String parseSentCommentErrorMessage(String response) {
try {
JSONObject responseObject = new JSONObject(response).getJSONObject(JSONUtils.JSON_KEY);
if(responseObject.getJSONArray(JSONUtils.ERRORS_KEY).length() != 0) {
JSONArray error = responseObject.getJSONArray(JSONUtils.ERRORS_KEY)
.getJSONArray(responseObject.getJSONArray(JSONUtils.ERRORS_KEY).length() - 1);
if(error.length() != 0) {
String errorString;
if(error.length() >= 2) {
errorString = error.getString(1);
} else {
errorString = error.getString(0);
}
return errorString.substring(0, 1).toUpperCase() + errorString.substring(1);
} else {
return null;
}
} else {
return null;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -19,16 +19,6 @@ import ml.docilealligator.infinityforreddit.Fragment.PostFragment;
*/
public class ParsePost {
interface ParsePostsListingListener {
void onParsePostsListingSuccess(ArrayList<Post> newPostData, String lastItem);
void onParsePostsListingFail();
}
public interface ParsePostListener {
void onParsePostSuccess(Post post);
void onParsePostFail();
}
static void parsePosts(String response, Locale locale, int nPosts, int filter, boolean nsfw,
ParsePostsListingListener parsePostsListingListener) {
new ParsePostDataAsyncTask(response, locale, nPosts, filter, nsfw, parsePostsListingListener).execute();
@ -38,6 +28,227 @@ public class ParsePost {
new ParsePostDataAsyncTask(response, locale, true, parsePostListener).execute();
}
private static Post parseBasicData(JSONObject data, Locale locale) throws JSONException {
String id = data.getString(JSONUtils.ID_KEY);
String fullName = data.getString(JSONUtils.NAME_KEY);
String subredditName = data.getString(JSONUtils.SUBREDDIT_KEY);
String subredditNamePrefixed = data.getString(JSONUtils.SUBREDDIT_NAME_PREFIX_KEY);
String author = data.getString(JSONUtils.AUTHOR_KEY);
long postTime = data.getLong(JSONUtils.CREATED_UTC_KEY) * 1000;
String title = data.getString(JSONUtils.TITLE_KEY);
int score = data.getInt(JSONUtils.SCORE_KEY);
int voteType;
int gilded = data.getInt(JSONUtils.GILDED_KEY);
int nComments = data.getInt(JSONUtils.NUM_COMMENTS_KEY);
boolean hidden = data.getBoolean(JSONUtils.HIDDEN_KEY);
boolean spoiler = data.getBoolean(JSONUtils.SPOILER_KEY);
boolean nsfw = data.getBoolean(JSONUtils.NSFW_KEY);
boolean stickied = data.getBoolean(JSONUtils.STICKIED_KEY);
boolean archived = data.getBoolean(JSONUtils.ARCHIVED_KEY);
boolean locked = data.getBoolean(JSONUtils.LOCKEC_KEY);
boolean saved = data.getBoolean(JSONUtils.SAVED_KEY);
String flair = null;
if (!data.isNull(JSONUtils.LINK_FLAIR_TEXT_KEY)) {
flair = data.getString(JSONUtils.LINK_FLAIR_TEXT_KEY);
}
if (data.isNull(JSONUtils.LIKES_KEY)) {
voteType = 0;
} else {
voteType = data.getBoolean(JSONUtils.LIKES_KEY) ? 1 : -1;
score -= voteType;
}
Calendar postTimeCalendar = Calendar.getInstance();
postTimeCalendar.setTimeInMillis(postTime);
String formattedPostTime = new SimpleDateFormat("MMM d, yyyy, HH:mm",
locale).format(postTimeCalendar.getTime());
String permalink = Html.fromHtml(data.getString(JSONUtils.PERMALINK_KEY)).toString();
String previewUrl = "";
int previewWidth = -1;
int previewHeight = -1;
if (data.has(JSONUtils.PREVIEW_KEY)) {
previewUrl = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY);
previewWidth = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getInt(JSONUtils.WIDTH_KEY);
previewHeight = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getInt(JSONUtils.HEIGHT_KEY);
}
if (data.has(JSONUtils.CROSSPOST_PARENT_LIST)) {
//Cross post
data = data.getJSONArray(JSONUtils.CROSSPOST_PARENT_LIST).getJSONObject(0);
Post crosspostParent = parseBasicData(data, locale);
Post post = parseData(data, permalink, id, fullName, subredditName, subredditNamePrefixed,
author, formattedPostTime, title, previewUrl, previewWidth, previewHeight,
score, voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, true);
post.setCrosspostParentId(crosspostParent.getId());
return post;
} else {
return parseData(data, permalink, id, fullName, subredditName, subredditNamePrefixed,
author, formattedPostTime, title, previewUrl, previewWidth, previewHeight,
score, voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, false);
}
}
private static Post parseData(JSONObject data, String permalink, String id, String fullName,
String subredditName, String subredditNamePrefixed, String author,
String formattedPostTime, String title, String previewUrl, int previewWidth,
int previewHeight, int score, int voteType, int gilded, int nComments,
String flair, boolean hidden, boolean spoiler, boolean nsfw, boolean stickied,
boolean archived, boolean locked, boolean saved, boolean isCrosspost) throws JSONException {
Post post;
boolean isVideo = data.getBoolean(JSONUtils.IS_VIDEO_KEY);
String url = Html.fromHtml(data.getString(JSONUtils.URL_KEY)).toString();
if (!data.has(JSONUtils.PREVIEW_KEY) && previewUrl.equals("")) {
if (url.contains(permalink)) {
//Text post
int postType = Post.TEXT_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, formattedPostTime,
title, permalink, score, postType, voteType, gilded, nComments, flair, hidden,
spoiler, nsfw, stickied, archived, locked, saved, isCrosspost);
if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
} else {
post.setSelfText(Utils.addSubredditAndUserLink(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
}
} else {
//No preview link post
int postType = Post.NO_PREVIEW_LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, formattedPostTime,
title, previewUrl, url, permalink, score, postType, voteType, gilded, nComments,
flair, hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost);
if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
} else {
post.setSelfText(Utils.addSubredditAndUserLink(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
}
}
} else {
if (previewUrl.equals("")) {
previewUrl = Html.fromHtml(data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY)).toString();
}
if (isVideo) {
//Video post
JSONObject redditVideoObject = data.getJSONObject(JSONUtils.MEDIA_KEY).getJSONObject(JSONUtils.REDDIT_VIDEO_KEY);
int postType = Post.VIDEO_TYPE;
String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString();
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, formattedPostTime,
title, previewUrl, permalink, score, postType, voteType, gilded, nComments,
flair, hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
post.setVideoUrl(videoUrl);
} else if (data.has(JSONUtils.PREVIEW_KEY)) {
if (data.getJSONObject(JSONUtils.PREVIEW_KEY).has(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY)) {
//Gif video post (HLS)
int postType = Post.GIF_VIDEO_TYPE;
String videoUrl = Html.fromHtml(data.getJSONObject(JSONUtils.PREVIEW_KEY)
.getJSONObject(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY).getString(JSONUtils.HLS_URL_KEY)).toString();
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, previewUrl, permalink, score, postType, voteType,
gilded, nComments, flair, hidden, spoiler, nsfw, stickied, archived,
locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
post.setVideoUrl(videoUrl);
} else {
if (url.endsWith("jpg") || url.endsWith("png")) {
//Image post
int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, url, url, permalink, score, postType,
voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
} else {
if (url.contains(permalink)) {
//Text post but with a preview
int postType = Post.TEXT_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, permalink, score, postType, voteType,
gilded, nComments, flair, hidden, spoiler, nsfw, stickied, archived,
locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
} else {
post.setSelfText(Utils.addSubredditAndUserLink(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
}
} else {
//Link post
int postType = Post.LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, previewUrl, url, permalink, score, postType,
voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost);
if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
} else {
post.setSelfText(Utils.addSubredditAndUserLink(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
}
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
}
}
}
} else {
if (url.endsWith("jpg") || url.endsWith("png")) {
//Image post
int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, previewUrl, url, permalink, score, postType,
voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
} else {
//CP No Preview Link post
int postType = Post.NO_PREVIEW_LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, url, url, permalink, score, postType, voteType,
gilded, nComments, flair, hidden, spoiler, nsfw, stickied, archived, locked,
saved, isCrosspost);
}
}
}
return post;
}
interface ParsePostsListingListener {
void onParsePostsListingSuccess(ArrayList<Post> newPostData, String lastItem);
void onParsePostsListingFail();
}
public interface ParsePostListener {
void onParsePostSuccess(Post post);
void onParsePostFail();
}
private static class ParsePostDataAsyncTask extends AsyncTask<Void, Void, Void> {
private JSONArray allData;
private Locale locale;
@ -86,7 +297,7 @@ public class ParsePost {
@Override
protected Void doInBackground(Void... voids) {
if(parseFailed) {
if (parseFailed) {
return null;
}
@ -115,17 +326,17 @@ public class ParsePost {
for (int i = 0; i < size; i++) {
try {
if(allData.getJSONObject(i).getString(JSONUtils.KIND_KEY).equals("t3")) {
if (allData.getJSONObject(i).getString(JSONUtils.KIND_KEY).equals("t3")) {
JSONObject data = allData.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
Post post = parseBasicData(data, locale);
if(post != null && !(!nsfw && post.isNSFW())) {
if (post != null && !(!nsfw && post.isNSFW())) {
if (filter == PostFragment.EXTRA_NO_FILTER) {
newPosts.add(post);
} else if (filter == post.getPostType()) {
newPosts.add(post);
} else if (filter == Post.LINK_TYPE && post.getPostType() == Post.NO_PREVIEW_LINK_TYPE) {
newPosts.add(post);
} else if(filter == Post.NSFW_TYPE && post.isNSFW()) {
} else if (filter == Post.NSFW_TYPE && post.isNSFW()) {
newPosts.add(post);
}
}
@ -140,14 +351,14 @@ public class ParsePost {
@Override
protected void onPostExecute(Void aVoid) {
if(!parseFailed) {
if(newPosts != null) {
if (!parseFailed) {
if (newPosts != null) {
parsePostsListingListener.onParsePostsListingSuccess(newPosts, lastItem);
} else {
parsePostListener.onParsePostSuccess(post);
}
} else {
if(parsePostsListingListener != null) {
if (parsePostsListingListener != null) {
parsePostsListingListener.onParsePostsListingFail();
} else {
parsePostListener.onParsePostFail();
@ -155,213 +366,4 @@ public class ParsePost {
}
}
}
private static Post parseBasicData(JSONObject data, Locale locale) throws JSONException {
String id = data.getString(JSONUtils.ID_KEY);
String fullName = data.getString(JSONUtils.NAME_KEY);
String subredditName = data.getString(JSONUtils.SUBREDDIT_KEY);
String subredditNamePrefixed = data.getString(JSONUtils.SUBREDDIT_NAME_PREFIX_KEY);
String author = data.getString(JSONUtils.AUTHOR_KEY);
long postTime = data.getLong(JSONUtils.CREATED_UTC_KEY) * 1000;
String title = data.getString(JSONUtils.TITLE_KEY);
int score = data.getInt(JSONUtils.SCORE_KEY);
int voteType;
int gilded = data.getInt(JSONUtils.GILDED_KEY);
int nComments = data.getInt(JSONUtils.NUM_COMMENTS_KEY);
boolean hidden = data.getBoolean(JSONUtils.HIDDEN_KEY);
boolean spoiler = data.getBoolean(JSONUtils.SPOILER_KEY);
boolean nsfw = data.getBoolean(JSONUtils.NSFW_KEY);
boolean stickied = data.getBoolean(JSONUtils.STICKIED_KEY);
boolean archived = data.getBoolean(JSONUtils.ARCHIVED_KEY);
boolean locked = data.getBoolean(JSONUtils.LOCKEC_KEY);
boolean saved = data.getBoolean(JSONUtils.SAVED_KEY);
String flair = null;
if(!data.isNull(JSONUtils.LINK_FLAIR_TEXT_KEY)) {
flair = data.getString(JSONUtils.LINK_FLAIR_TEXT_KEY);
}
if(data.isNull(JSONUtils.LIKES_KEY)) {
voteType = 0;
} else {
voteType = data.getBoolean(JSONUtils.LIKES_KEY) ? 1 : -1;
score -= voteType;
}
Calendar postTimeCalendar = Calendar.getInstance();
postTimeCalendar.setTimeInMillis(postTime);
String formattedPostTime = new SimpleDateFormat("MMM d, yyyy, HH:mm",
locale).format(postTimeCalendar.getTime());
String permalink = Html.fromHtml(data.getString(JSONUtils.PERMALINK_KEY)).toString();
String previewUrl = "";
int previewWidth = -1;
int previewHeight = -1;
if(data.has(JSONUtils.PREVIEW_KEY)) {
previewUrl = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY);
previewWidth = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getInt(JSONUtils.WIDTH_KEY);
previewHeight = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getInt(JSONUtils.HEIGHT_KEY);
}
if(data.has(JSONUtils.CROSSPOST_PARENT_LIST)) {
//Cross post
data = data.getJSONArray(JSONUtils.CROSSPOST_PARENT_LIST).getJSONObject(0);
Post crosspostParent = parseBasicData(data, locale);
Post post = parseData(data, permalink, id, fullName, subredditName, subredditNamePrefixed,
author, formattedPostTime, title, previewUrl, previewWidth, previewHeight,
score, voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, true);
post.setCrosspostParentId(crosspostParent.getId());
return post;
} else {
return parseData(data, permalink, id, fullName, subredditName, subredditNamePrefixed,
author, formattedPostTime, title, previewUrl, previewWidth, previewHeight,
score, voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, false);
}
}
private static Post parseData(JSONObject data, String permalink, String id, String fullName,
String subredditName, String subredditNamePrefixed, String author,
String formattedPostTime, String title, String previewUrl, int previewWidth,
int previewHeight, int score, int voteType, int gilded, int nComments,
String flair, boolean hidden, boolean spoiler, boolean nsfw, boolean stickied,
boolean archived, boolean locked, boolean saved, boolean isCrosspost) throws JSONException {
Post post;
boolean isVideo = data.getBoolean(JSONUtils.IS_VIDEO_KEY);
String url = Html.fromHtml(data.getString(JSONUtils.URL_KEY)).toString();
if(!data.has(JSONUtils.PREVIEW_KEY) && previewUrl.equals("")) {
if(url.contains(permalink)) {
//Text post
int postType = Post.TEXT_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, formattedPostTime,
title, permalink, score, postType, voteType, gilded, nComments, flair, hidden,
spoiler, nsfw, stickied, archived, locked, saved, isCrosspost);
if(data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
} else {
post.setSelfText(Utils.addSubredditAndUserLink(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
}
} else {
//No preview link post
int postType = Post.NO_PREVIEW_LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, formattedPostTime,
title, previewUrl, url, permalink, score, postType, voteType, gilded, nComments,
flair, hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost);
if(data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
} else {
post.setSelfText(Utils.addSubredditAndUserLink(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
}
}
} else {
if(previewUrl.equals("")) {
previewUrl = Html.fromHtml(data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0)
.getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY)).toString();
}
if(isVideo) {
//Video post
JSONObject redditVideoObject = data.getJSONObject(JSONUtils.MEDIA_KEY).getJSONObject(JSONUtils.REDDIT_VIDEO_KEY);
int postType = Post.VIDEO_TYPE;
String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString();
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, formattedPostTime,
title, previewUrl, permalink, score, postType, voteType, gilded, nComments,
flair, hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
post.setVideoUrl(videoUrl);
} else if(data.has(JSONUtils.PREVIEW_KEY)){
if(data.getJSONObject(JSONUtils.PREVIEW_KEY).has(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY)) {
//Gif video post (HLS)
int postType = Post.GIF_VIDEO_TYPE;
String videoUrl = Html.fromHtml(data.getJSONObject(JSONUtils.PREVIEW_KEY)
.getJSONObject(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY).getString(JSONUtils.HLS_URL_KEY)).toString();
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, previewUrl, permalink, score, postType, voteType,
gilded, nComments, flair, hidden, spoiler, nsfw, stickied, archived,
locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
post.setVideoUrl(videoUrl);
} else {
if (url.endsWith("jpg") || url.endsWith("png")) {
//Image post
int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, url, url, permalink, score, postType,
voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
} else {
if (url.contains(permalink)) {
//Text post but with a preview
int postType = Post.TEXT_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, permalink, score, postType, voteType,
gilded, nComments, flair, hidden, spoiler, nsfw, stickied, archived,
locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
if(data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
} else {
post.setSelfText(Utils.addSubredditAndUserLink(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
}
} else {
//Link post
int postType = Post.LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, previewUrl, url, permalink, score, postType,
voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost);
if(data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
} else {
post.setSelfText(Utils.addSubredditAndUserLink(data.getString(JSONUtils.SELFTEXT_KEY).trim()));
}
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
}
}
}
} else {
if (url.endsWith("jpg") || url.endsWith("png")) {
//Image post
int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, previewUrl, url, permalink, score, postType,
voteType, gilded, nComments, flair, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost);
post.setPreviewWidth(previewWidth);
post.setPreviewHeight(previewHeight);
} else {
//CP No Preview Link post
int postType = Post.NO_PREVIEW_LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
formattedPostTime, title, url, url, permalink, score, postType, voteType,
gilded, nComments, flair, hidden, spoiler, nsfw, stickied, archived, locked,
saved, isCrosspost);
}
}
}
return post;
}
}

View File

@ -11,16 +11,6 @@ import java.util.ArrayList;
import ml.docilealligator.infinityforreddit.SubredditDatabase.SubredditData;
class ParseSubredditData {
interface ParseSubredditDataListener {
void onParseSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers);
void onParseSubredditDataFail();
}
interface ParseSubredditListingDataListener {
void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after);
void onParseSubredditListingDataFail();
}
static void parseSubredditData(String response, ParseSubredditDataListener parseSubredditDataListener) {
new ParseSubredditDataAsyncTask(response, parseSubredditDataListener).execute();
}
@ -29,6 +19,51 @@ class ParseSubredditData {
new ParseSubredditListingDataAsyncTask(response, parseSubredditListingDataListener).execute();
}
private static SubredditData parseSubredditData(JSONObject subredditDataJsonObject) throws JSONException {
String id = subredditDataJsonObject.getString(JSONUtils.NAME_KEY);
String subredditFullName = subredditDataJsonObject.getString(JSONUtils.DISPLAY_NAME);
String description = subredditDataJsonObject.getString(JSONUtils.PUBLIC_DESCRIPTION_KEY).trim();
String bannerImageUrl;
if (subredditDataJsonObject.isNull(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY)) {
bannerImageUrl = "";
} else {
bannerImageUrl = subredditDataJsonObject.getString(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY);
}
if (bannerImageUrl.equals("") && !subredditDataJsonObject.isNull(JSONUtils.BANNER_IMG_KEY)) {
bannerImageUrl = subredditDataJsonObject.getString(JSONUtils.BANNER_IMG_KEY);
}
String iconUrl;
if (subredditDataJsonObject.isNull(JSONUtils.COMMUNITY_ICON_KEY)) {
iconUrl = "";
} else {
iconUrl = subredditDataJsonObject.getString(JSONUtils.COMMUNITY_ICON_KEY);
}
if (iconUrl.equals("") && !subredditDataJsonObject.isNull(JSONUtils.ICON_IMG_KEY)) {
iconUrl = subredditDataJsonObject.getString(JSONUtils.ICON_IMG_KEY);
}
int nSubscribers = 0;
if (!subredditDataJsonObject.isNull(JSONUtils.SUBSCRIBERS_KEY)) {
nSubscribers = subredditDataJsonObject.getInt(JSONUtils.SUBSCRIBERS_KEY);
}
return new SubredditData(id, subredditFullName, iconUrl, bannerImageUrl, description, nSubscribers);
}
interface ParseSubredditDataListener {
void onParseSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers);
void onParseSubredditDataFail();
}
interface ParseSubredditListingDataListener {
void onParseSubredditListingDataSuccess(ArrayList<SubredditData> subredditData, String after);
void onParseSubredditListingDataFail();
}
private static class ParseSubredditDataAsyncTask extends AsyncTask<Void, Void, Void> {
private JSONObject jsonResponse;
private boolean parseFailed;
@ -36,7 +71,7 @@ class ParseSubredditData {
private SubredditData subredditData;
private int mNCurrentOnlineSubscribers;
ParseSubredditDataAsyncTask(String response, ParseSubredditDataListener parseSubredditDataListener){
ParseSubredditDataAsyncTask(String response, ParseSubredditDataListener parseSubredditDataListener) {
this.parseSubredditDataListener = parseSubredditDataListener;
try {
jsonResponse = new JSONObject(response);
@ -62,7 +97,7 @@ class ParseSubredditData {
@Override
protected void onPostExecute(Void aVoid) {
if(!parseFailed) {
if (!parseFailed) {
parseSubredditDataListener.onParseSubredditDataSuccess(subredditData, mNCurrentOnlineSubscribers);
} else {
parseSubredditDataListener.onParseSubredditDataFail();
@ -77,7 +112,7 @@ class ParseSubredditData {
private ArrayList<SubredditData> subredditListingData;
private String after;
ParseSubredditListingDataAsyncTask(String response, ParseSubredditListingDataListener parseSubredditListingDataListener){
ParseSubredditListingDataAsyncTask(String response, ParseSubredditListingDataListener parseSubredditListingDataListener) {
this.parseSubredditListingDataListener = parseSubredditListingDataListener;
try {
jsonResponse = new JSONObject(response);
@ -92,10 +127,10 @@ class ParseSubredditData {
@Override
protected Void doInBackground(Void... voids) {
try {
if(!parseFailed) {
if (!parseFailed) {
JSONArray children = jsonResponse.getJSONObject(JSONUtils.DATA_KEY)
.getJSONArray(JSONUtils.CHILDREN_KEY);
for(int i = 0; i < children.length(); i++) {
for (int i = 0; i < children.length(); i++) {
JSONObject data = children.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
SubredditData subredditData = parseSubredditData(data);
subredditListingData.add(subredditData);
@ -112,44 +147,11 @@ class ParseSubredditData {
@Override
protected void onPostExecute(Void aVoid) {
if(!parseFailed) {
if (!parseFailed) {
parseSubredditListingDataListener.onParseSubredditListingDataSuccess(subredditListingData, after);
} else {
parseSubredditListingDataListener.onParseSubredditListingDataFail();
}
}
}
private static SubredditData parseSubredditData(JSONObject subredditDataJsonObject) throws JSONException {
String id = subredditDataJsonObject.getString(JSONUtils.NAME_KEY);
String subredditFullName = subredditDataJsonObject.getString(JSONUtils.DISPLAY_NAME);
String description = subredditDataJsonObject.getString(JSONUtils.PUBLIC_DESCRIPTION_KEY).trim();
String bannerImageUrl;
if(subredditDataJsonObject.isNull(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY)) {
bannerImageUrl = "";
} else {
bannerImageUrl = subredditDataJsonObject.getString(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY);
}
if(bannerImageUrl.equals("") && !subredditDataJsonObject.isNull(JSONUtils.BANNER_IMG_KEY)) {
bannerImageUrl= subredditDataJsonObject.getString(JSONUtils.BANNER_IMG_KEY);
}
String iconUrl;
if(subredditDataJsonObject.isNull(JSONUtils.COMMUNITY_ICON_KEY)) {
iconUrl = "";
} else {
iconUrl = subredditDataJsonObject.getString(JSONUtils.COMMUNITY_ICON_KEY);
}
if(iconUrl.equals("") && !subredditDataJsonObject.isNull(JSONUtils.ICON_IMG_KEY)) {
iconUrl = subredditDataJsonObject.getString(JSONUtils.ICON_IMG_KEY);
}
int nSubscribers = 0;
if(!subredditDataJsonObject.isNull(JSONUtils.SUBSCRIBERS_KEY)) {
nSubscribers = subredditDataJsonObject.getInt(JSONUtils.SUBSCRIBERS_KEY);
}
return new SubredditData(id, subredditFullName, iconUrl, bannerImageUrl, description, nSubscribers);
}
}

View File

@ -13,14 +13,6 @@ import ml.docilealligator.infinityforreddit.SubscribedSubredditDatabase.Subscrib
import ml.docilealligator.infinityforreddit.SubscribedUserDatabase.SubscribedUserData;
class ParseSubscribedThing {
interface ParseSubscribedSubredditsListener {
void onParseSubscribedSubredditsSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData,
ArrayList<SubredditData> subredditData,
String lastItem);
void onParseSubscribedSubredditsFail();
}
static void parseSubscribedSubreddits(String response, String accountName,
ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData,
@ -30,6 +22,15 @@ class ParseSubscribedThing {
parseSubscribedSubredditsListener).execute();
}
interface ParseSubscribedSubredditsListener {
void onParseSubscribedSubredditsSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData,
ArrayList<SubredditData> subredditData,
String lastItem);
void onParseSubscribedSubredditsFail();
}
private static class ParseSubscribedSubredditsAsyncTask extends AsyncTask<Void, Void, Void> {
private JSONObject jsonResponse;
private String accountName;
@ -46,7 +47,7 @@ class ParseSubscribedThing {
ParseSubscribedSubredditsAsyncTask(String response, String accountName, ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData,
ArrayList<SubredditData> subredditData,
ParseSubscribedSubredditsListener parseSubscribedSubredditsListener){
ParseSubscribedSubredditsListener parseSubscribedSubredditsListener) {
try {
jsonResponse = new JSONObject(response);
this.accountName = accountName;
@ -68,32 +69,32 @@ class ParseSubscribedThing {
protected Void doInBackground(Void... voids) {
try {
JSONArray children = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
for(int i = 0; i < children.length(); i++) {
for (int i = 0; i < children.length(); i++) {
JSONObject data = children.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY);
String name = data.getString(JSONUtils.DISPLAY_NAME);
String bannerImageUrl = data.getString(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY);
if(bannerImageUrl.equals("") || bannerImageUrl.equals("null")) {
bannerImageUrl= data.getString(JSONUtils.BANNER_IMG_KEY);
if(bannerImageUrl.equals("null")) {
if (bannerImageUrl.equals("") || bannerImageUrl.equals("null")) {
bannerImageUrl = data.getString(JSONUtils.BANNER_IMG_KEY);
if (bannerImageUrl.equals("null")) {
bannerImageUrl = "";
}
}
String iconUrl = data.getString(JSONUtils.COMMUNITY_ICON_KEY);
if(iconUrl.equals("") || iconUrl.equals("null")) {
if (iconUrl.equals("") || iconUrl.equals("null")) {
iconUrl = data.getString(JSONUtils.ICON_IMG_KEY);
if(iconUrl.equals("null")) {
if (iconUrl.equals("null")) {
iconUrl = "";
}
}
String id = data.getString(JSONUtils.NAME_KEY);
if(iconUrl.equals("") || iconUrl.equals("null")) {
if (iconUrl.equals("") || iconUrl.equals("null")) {
iconUrl = data.getString(JSONUtils.COMMUNITY_ICON_KEY);
if(iconUrl.equals("null")) {
if (iconUrl.equals("null")) {
iconUrl = "";
}
}
if(data.getString(JSONUtils.SUBREDDIT_TYPE_KEY)
if (data.getString(JSONUtils.SUBREDDIT_TYPE_KEY)
.equals(JSONUtils.SUBREDDIT_TYPE_VALUE_USER)) {
//It's a user
newSubscribedUserData.add(new SubscribedUserData(name.substring(2), iconUrl, accountName));
@ -115,7 +116,7 @@ class ParseSubscribedThing {
@Override
protected void onPostExecute(Void aVoid) {
if(!parseFailed) {
if (!parseFailed) {
subscribedSubredditData.addAll(newSubscribedSubredditData);
subscribedUserData.addAll(newSubscribedUserData);
subredditData.addAll(newSubredditData);

View File

@ -11,16 +11,6 @@ import java.util.ArrayList;
import ml.docilealligator.infinityforreddit.User.UserData;
public class ParseUserData {
interface ParseUserDataListener {
void onParseUserDataSuccess(UserData userData);
void onParseUserDataFailed();
}
interface ParseUserListingDataListener {
void onParseUserListingDataSuccess(ArrayList<UserData> userData, String after);
void onParseUserListingDataFailed();
}
static void parseUserData(String response, ParseUserDataListener parseUserDataListener) {
new ParseUserDataAsyncTask(response, parseUserDataListener).execute();
}
@ -29,6 +19,39 @@ public class ParseUserData {
new ParseUserListingDataAsyncTask(response, parseUserListingDataListener).execute();
}
private static UserData parseUserDataBase(JSONObject userDataJson) throws JSONException {
userDataJson = userDataJson.getJSONObject(JSONUtils.DATA_KEY);
String userName = userDataJson.getString(JSONUtils.NAME_KEY);
String iconImageUrl = userDataJson.getString(JSONUtils.ICON_IMG_KEY);
String bannerImageUrl = "";
boolean canBeFollowed;
if (userDataJson.has(JSONUtils.SUBREDDIT_KEY) && !userDataJson.isNull(JSONUtils.SUBREDDIT_KEY)) {
bannerImageUrl = userDataJson.getJSONObject(JSONUtils.SUBREDDIT_KEY).getString(JSONUtils.BANNER_IMG_KEY);
canBeFollowed = true;
} else {
canBeFollowed = false;
}
int linkKarma = userDataJson.getInt(JSONUtils.LINK_KARMA_KEY);
int commentKarma = userDataJson.getInt(JSONUtils.COMMENT_KARMA_KEY);
int karma = linkKarma + commentKarma;
boolean isGold = userDataJson.getBoolean(JSONUtils.IS_GOLD_KEY);
boolean isFriend = userDataJson.getBoolean(JSONUtils.IS_FRIEND_KEY);
return new UserData(userName, iconImageUrl, bannerImageUrl, karma, isGold, isFriend, canBeFollowed);
}
interface ParseUserDataListener {
void onParseUserDataSuccess(UserData userData);
void onParseUserDataFailed();
}
interface ParseUserListingDataListener {
void onParseUserListingDataSuccess(ArrayList<UserData> userData, String after);
void onParseUserListingDataFailed();
}
private static class ParseUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
private JSONObject jsonResponse;
private ParseUserDataListener parseUserDataListener;
@ -36,7 +59,7 @@ public class ParseUserData {
private UserData userData;
ParseUserDataAsyncTask(String response, ParseUserDataListener parseUserDataListener){
ParseUserDataAsyncTask(String response, ParseUserDataListener parseUserDataListener) {
try {
jsonResponse = new JSONObject(response);
this.parseUserDataListener = parseUserDataListener;
@ -60,7 +83,7 @@ public class ParseUserData {
@Override
protected void onPostExecute(Void aVoid) {
if(!parseFailed) {
if (!parseFailed) {
parseUserDataListener.onParseUserDataSuccess(userData);
} else {
parseUserDataListener.onParseUserDataFailed();
@ -77,7 +100,7 @@ public class ParseUserData {
private ArrayList<UserData> userDataArrayList;
ParseUserListingDataAsyncTask(String response, ParseUserListingDataListener parseUserListingDataListener){
ParseUserListingDataAsyncTask(String response, ParseUserListingDataListener parseUserListingDataListener) {
this.parseUserListingDataListener = parseUserListingDataListener;
this.response = response;
try {
@ -93,10 +116,10 @@ public class ParseUserData {
@Override
protected Void doInBackground(Void... voids) {
try {
if(!parseFailed) {
if (!parseFailed) {
after = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.AFTER_KEY);
JSONArray children = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY);
for(int i = 0; i < children.length(); i++) {
for (int i = 0; i < children.length(); i++) {
userDataArrayList.add(parseUserDataBase(children.getJSONObject(i)));
}
}
@ -109,10 +132,10 @@ public class ParseUserData {
@Override
protected void onPostExecute(Void aVoid) {
if(!parseFailed) {
if (!parseFailed) {
parseUserListingDataListener.onParseUserListingDataSuccess(userDataArrayList, after);
} else {
if(response.equals("\"{}\"")) {
if (response.equals("\"{}\"")) {
parseUserListingDataListener.onParseUserListingDataSuccess(new ArrayList<>(), null);
} else {
parseUserListingDataListener.onParseUserListingDataFailed();
@ -120,25 +143,4 @@ public class ParseUserData {
}
}
}
private static UserData parseUserDataBase(JSONObject userDataJson) throws JSONException {
userDataJson = userDataJson.getJSONObject(JSONUtils.DATA_KEY);
String userName = userDataJson.getString(JSONUtils.NAME_KEY);
String iconImageUrl = userDataJson.getString(JSONUtils.ICON_IMG_KEY);
String bannerImageUrl = "";
boolean canBeFollowed;
if(userDataJson.has(JSONUtils.SUBREDDIT_KEY) && !userDataJson.isNull(JSONUtils.SUBREDDIT_KEY)) {
bannerImageUrl = userDataJson.getJSONObject(JSONUtils.SUBREDDIT_KEY).getString(JSONUtils.BANNER_IMG_KEY);
canBeFollowed = true;
} else {
canBeFollowed = false;
}
int linkKarma = userDataJson.getInt(JSONUtils.LINK_KARMA_KEY);
int commentKarma = userDataJson.getInt(JSONUtils.COMMENT_KARMA_KEY);
int karma = linkKarma + commentKarma;
boolean isGold = userDataJson.getBoolean(JSONUtils.IS_GOLD_KEY);
boolean isFriend = userDataJson.getBoolean(JSONUtils.IS_FRIEND_KEY);
return new UserData(userName, iconImageUrl, bannerImageUrl, karma, isGold, isFriend, canBeFollowed);
}
}

View File

@ -15,7 +15,17 @@ public class Post implements Parcelable {
public static final int VIDEO_TYPE = 3;
public static final int GIF_VIDEO_TYPE = 4;
public static final int NO_PREVIEW_LINK_TYPE = 5;
public static final Creator<Post> CREATOR = new Creator<Post>() {
@Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
@Override
public Post[] newArray(int size) {
return new Post[size];
}
};
private String id;
private String fullName;
private String subredditName;
@ -50,9 +60,9 @@ public class Post implements Parcelable {
private String crosspostParentId;
public Post(String id, String fullName, String subredditName, String subredditNamePrefixed, String author,
String postTime, String title, String previewUrl, String permalink, int score, int postType,
int voteType, int gilded, int nComments, String flair, boolean hidden, boolean spoiler,
boolean nsfw, boolean stickied, boolean archived, boolean locked, boolean saved, boolean isCrosspost) {
String postTime, String title, String previewUrl, String permalink, int score, int postType,
int voteType, int gilded, int nComments, String flair, boolean hidden, boolean spoiler,
boolean nsfw, boolean stickied, boolean archived, boolean locked, boolean saved, boolean isCrosspost) {
this.id = id;
this.fullName = fullName;
this.subredditName = subredditName;
@ -80,10 +90,10 @@ public class Post implements Parcelable {
}
public Post(String id, String fullName, String subredditName, String subredditNamePrefixed, String author,
String postTime, String title, String previewUrl, String url, String permalink, int score,
int postType, int voteType, int gilded, int nComments, String flair, boolean hidden,
boolean spoiler, boolean nsfw, boolean stickied, boolean archived, boolean locked,
boolean saved, boolean isCrosspost) {
String postTime, String title, String previewUrl, String url, String permalink, int score,
int postType, int voteType, int gilded, int nComments, String flair, boolean hidden,
boolean spoiler, boolean nsfw, boolean stickied, boolean archived, boolean locked,
boolean saved, boolean isCrosspost) {
this.id = id;
this.fullName = fullName;
this.subredditName = subredditName;
@ -112,9 +122,9 @@ public class Post implements Parcelable {
}
public Post(String id, String fullName, String subredditName, String subredditNamePrefixed, String author,
String postTime, String title, String permalink, int score, int postType, int voteType, int gilded,
int nComments, String flair, boolean hidden, boolean spoiler, boolean nsfw, boolean stickied,
boolean archived, boolean locked, boolean saved, boolean isCrosspost) {
String postTime, String title, String permalink, int score, int postType, int voteType, int gilded,
int nComments, String flair, boolean hidden, boolean spoiler, boolean nsfw, boolean stickied,
boolean archived, boolean locked, boolean saved, boolean isCrosspost) {
this.id = id;
this.fullName = fullName;
this.subredditName = subredditName;
@ -137,7 +147,7 @@ public class Post implements Parcelable {
this.archived = archived;
this.locked = locked;
this.saved = saved;
this.isCrosspost= isCrosspost;
this.isCrosspost = isCrosspost;
}
protected Post(Parcel in) {
@ -175,18 +185,6 @@ public class Post implements Parcelable {
crosspostParentId = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
@Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
@Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public String getId() {
return id;
}
@ -231,22 +229,22 @@ public class Post implements Parcelable {
return postTime;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setSelfText(String selfText) {
this.selfText = selfText;
public void setTitle(String title) {
this.title = title;
}
public String getSelfText() {
return selfText;
}
public void setSelfText(String selfText) {
this.selfText = selfText;
}
public String getPreviewUrl() {
return previewUrl;
}
@ -255,14 +253,14 @@ public class Post implements Parcelable {
return url;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
public String getPermalink() {
return permalink;
}
@ -275,46 +273,46 @@ public class Post implements Parcelable {
this.flair = flair;
}
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getPostType() {
return postType;
}
public void setVoteType(int voteType) {
this.voteType = voteType;
}
public int getVoteType() {
return voteType;
}
public void setVoteType(int voteType) {
this.voteType = voteType;
}
public int getGilded() {
return gilded;
}
public void setPreviewWidth(int previewWidth) {
this.previewWidth = previewWidth;
}
public int getPreviewWidth() {
return previewWidth;
}
public void setPreviewHeight(int previewHeight) {
this.previewHeight = previewHeight;
public void setPreviewWidth(int previewWidth) {
this.previewWidth = previewWidth;
}
public int getPreviewHeight() {
return previewHeight;
}
public void setPreviewHeight(int previewHeight) {
this.previewHeight = previewHeight;
}
public int getnComments() {
return nComments;
}

View File

@ -77,8 +77,8 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
initialLoadStateLiveData = new MutableLiveData<>();
hasPostLiveData = new MutableLiveData<>();
this.postType = postType;
if(sortType == null) {
if(subredditOrUserName.equals("popular") || subredditOrUserName.equals("all")) {
if (sortType == null) {
if (subredditOrUserName.equals("popular") || subredditOrUserName.equals("all")) {
this.sortType = PostDataSource.SORT_TYPE_HOT;
} else {
this.sortType = PostDataSource.SORT_TYPE_BEST;
@ -164,7 +164,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
this.params = params;
this.callback = callback;
if(params.key.equals("") || params.key.equals("null")) {
if (params.key.equals("") || params.key.equals("null")) {
return;
}
@ -194,7 +194,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if (response.isSuccessful()) {
if(sortType.equals(SORT_TYPE_RANDOM)) {
if (sortType.equals(SORT_TYPE_RANDOM)) {
ParsePost.parsePost(response.body(), locale, new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(Post post) {
@ -216,15 +216,15 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
String nextPageKey;
if(lastItem == null || lastItem.equals("") || lastItem.equals("null")) {
if (lastItem == null || lastItem.equals("") || lastItem.equals("null")) {
nextPageKey = null;
} else {
nextPageKey = lastItem;
}
if(newPosts.size() != 0) {
if (newPosts.size() != 0) {
hasPostLiveData.postValue(true);
} else if(nextPageKey != null) {
} else if (nextPageKey != null) {
loadBestPostsInitial(callback, nextPageKey);
return;
} else {
@ -265,24 +265,24 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
bestPost.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParsePost.parsePosts(response.body(), locale, -1, filter, nsfw,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
if(newPosts.size() == 0 && lastItem != null && !lastItem.equals("") && !lastItem.equals("null")) {
loadBestPostsAfter(params, callback, lastItem);
} else {
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
callback.onResult(newPosts, lastItem);
}
}
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
if (newPosts.size() == 0 && lastItem != null && !lastItem.equals("") && !lastItem.equals("null")) {
loadBestPostsAfter(params, callback, lastItem);
} else {
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
callback.onResult(newPosts, lastItem);
}
}
@Override
public void onParsePostsListingFail() {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing more posts"));
}
});
@Override
public void onParsePostsListingFail() {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing more posts"));
}
});
} else {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
}
@ -300,7 +300,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost;
if(accessToken == null) {
if (accessToken == null) {
getPost = api.getSubredditBestPosts(subredditOrUserName, sortType, lastItem);
} else {
getPost = api.getSubredditBestPostsOauth(subredditOrUserName, sortType, lastItem, RedditUtils.getOAuthHeader(accessToken));
@ -308,8 +308,8 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if(sortType.equals(SORT_TYPE_RANDOM)) {
if (response.isSuccessful()) {
if (sortType.equals(SORT_TYPE_RANDOM)) {
ParsePost.parsePost(response.body(), locale, new ParsePost.ParsePostListener() {
@Override
public void onParsePostSuccess(Post post) {
@ -331,15 +331,15 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
String nextPageKey;
if(lastItem == null || lastItem.equals("") || lastItem.equals("null")) {
if (lastItem == null || lastItem.equals("") || lastItem.equals("null")) {
nextPageKey = null;
} else {
nextPageKey = lastItem;
}
if(newPosts.size() != 0) {
if (newPosts.size() != 0) {
hasPostLiveData.postValue(true);
} else if(nextPageKey != null) {
} else if (nextPageKey != null) {
loadSubredditPostsInitial(callback, nextPageKey);
return;
} else {
@ -377,7 +377,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost;
if(accessToken == null) {
if (accessToken == null) {
getPost = api.getSubredditBestPosts(subredditOrUserName, sortType, after);
} else {
getPost = api.getSubredditBestPostsOauth(subredditOrUserName, sortType, after, RedditUtils.getOAuthHeader(accessToken));
@ -386,24 +386,24 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParsePost.parsePosts(response.body(), locale, -1, filter, nsfw,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
if(newPosts.size() == 0 && lastItem != null && !lastItem.equals("") && !lastItem.equals("null")) {
loadSubredditPostsAfter(params, callback, lastItem);
} else {
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
callback.onResult(newPosts, lastItem);
}
}
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
if (newPosts.size() == 0 && lastItem != null && !lastItem.equals("") && !lastItem.equals("null")) {
loadSubredditPostsAfter(params, callback, lastItem);
} else {
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
callback.onResult(newPosts, lastItem);
}
}
@Override
public void onParsePostsListingFail() {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
@Override
public void onParsePostsListingFail() {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
} else {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
}
@ -421,7 +421,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost;
if(accessToken == null) {
if (accessToken == null) {
getPost = api.getUserPosts(subredditOrUserName, lastItem, sortType);
} else {
getPost = api.getUserPostsOauth(subredditOrUserName, userWhere, lastItem, sortType,
@ -430,21 +430,21 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParsePost.parsePosts(response.body(), locale, -1, filter, nsfw,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
String nextPageKey;
if(lastItem == null || lastItem.equals("") || lastItem.equals("null")) {
if (lastItem == null || lastItem.equals("") || lastItem.equals("null")) {
nextPageKey = null;
} else {
nextPageKey = lastItem;
}
if(newPosts.size() != 0) {
if (newPosts.size() != 0) {
hasPostLiveData.postValue(true);
} else if(nextPageKey != null) {
} else if (nextPageKey != null) {
loadUserPostsInitial(callback, nextPageKey);
return;
} else {
@ -479,7 +479,7 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost;
if(accessToken == null) {
if (accessToken == null) {
getPost = api.getUserPosts(subredditOrUserName, after, sortType);
} else {
getPost = api.getUserPostsOauth(subredditOrUserName, userWhere, after, sortType,
@ -488,24 +488,24 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParsePost.parsePosts(response.body(), locale, -1, filter, nsfw,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
if(newPosts.size() == 0 && lastItem != null && !lastItem.equals("") && !lastItem.equals("null")) {
loadUserPostsAfter(params, callback, lastItem);
} else {
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
callback.onResult(newPosts, lastItem);
}
}
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
if (newPosts.size() == 0 && lastItem != null && !lastItem.equals("") && !lastItem.equals("null")) {
loadUserPostsAfter(params, callback, lastItem);
} else {
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
callback.onResult(newPosts, lastItem);
}
}
@Override
public void onParsePostsListingFail() {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
@Override
public void onParsePostsListingFail() {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
} else {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
}
@ -523,14 +523,14 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost;
if(subredditOrUserName == null) {
if(accessToken == null) {
if (subredditOrUserName == null) {
if (accessToken == null) {
getPost = api.searchPosts(query, lastItem, sortType);
} else {
getPost = api.searchPostsOauth(query, lastItem, sortType, RedditUtils.getOAuthHeader(accessToken));
}
} else {
if(accessToken == null) {
if (accessToken == null) {
getPost = api.searchPostsInSpecificSubreddit(subredditOrUserName, query, lastItem);
} else {
getPost = api.searchPostsInSpecificSubredditOauth(subredditOrUserName, query, lastItem,
@ -541,21 +541,21 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParsePost.parsePosts(response.body(), locale, -1, filter, nsfw,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
String nextPageKey;
if(lastItem == null || lastItem.equals("") || lastItem.equals("null")) {
if (lastItem == null || lastItem.equals("") || lastItem.equals("null")) {
nextPageKey = null;
} else {
nextPageKey = lastItem;
}
if(newPosts.size() != 0) {
if (newPosts.size() != 0) {
hasPostLiveData.postValue(true);
} else if(nextPageKey != null) {
} else if (nextPageKey != null) {
loadSearchPostsInitial(callback, nextPageKey);
return;
} else {
@ -590,14 +590,14 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
RedditAPI api = retrofit.create(RedditAPI.class);
Call<String> getPost;
if(subredditOrUserName == null) {
if(accessToken == null) {
if (subredditOrUserName == null) {
if (accessToken == null) {
getPost = api.searchPosts(query, after, sortType);
} else {
getPost = api.searchPostsOauth(query, after, sortType, RedditUtils.getOAuthHeader(accessToken));
}
} else {
if(accessToken == null) {
if (accessToken == null) {
getPost = api.searchPostsInSpecificSubreddit(subredditOrUserName, query, after);
} else {
getPost = api.searchPostsInSpecificSubredditOauth(subredditOrUserName, query, after,
@ -608,24 +608,24 @@ public class PostDataSource extends PageKeyedDataSource<String, Post> {
getPost.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
if(response.isSuccessful()) {
if (response.isSuccessful()) {
ParsePost.parsePosts(response.body(), locale, -1, filter, nsfw,
new ParsePost.ParsePostsListingListener() {
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
if(newPosts.size() == 0 && lastItem != null && !lastItem.equals("") && !lastItem.equals("null")) {
loadSearchPostsAfter(params, callback, lastItem);
} else {
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
callback.onResult(newPosts, lastItem);
}
}
@Override
public void onParsePostsListingSuccess(ArrayList<Post> newPosts, String lastItem) {
if (newPosts.size() == 0 && lastItem != null && !lastItem.equals("") && !lastItem.equals("null")) {
loadSearchPostsAfter(params, callback, lastItem);
} else {
paginationNetworkStateLiveData.postValue(NetworkState.LOADED);
callback.onResult(newPosts, lastItem);
}
}
@Override
public void onParsePostsListingFail() {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
@Override
public void onParsePostsListingFail() {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
}
});
} else {
paginationNetworkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
}

View File

@ -79,13 +79,13 @@ class PostDataSourceFactory extends DataSource.Factory {
@NonNull
@Override
public DataSource<String, Post> create() {
if(postType == PostDataSource.TYPE_FRONT_PAGE) {
if (postType == PostDataSource.TYPE_FRONT_PAGE) {
postDataSource = new PostDataSource(retrofit, accessToken, locale, postType, sortType,
filter, nsfw);
} else if(postType == PostDataSource.TYPE_SEARCH) {
} else if (postType == PostDataSource.TYPE_SEARCH) {
postDataSource = new PostDataSource(retrofit, accessToken, locale, subredditName, query,
postType, sortType, filter, nsfw);
} else if(postType == PostDataSource.TYPE_SUBREDDIT) {
} else if (postType == PostDataSource.TYPE_SUBREDDIT) {
postDataSource = new PostDataSource(retrofit, accessToken, locale, subredditName, postType,
sortType, filter, nsfw);
} else {

View File

@ -245,13 +245,13 @@ public class PostViewModel extends ViewModel {
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if(postType == PostDataSource.TYPE_FRONT_PAGE) {
if (postType == PostDataSource.TYPE_FRONT_PAGE) {
return (T) new PostViewModel(retrofit, accessToken, locale, postType, sortType, filter,
nsfw);
} else if(postType == PostDataSource.TYPE_SEARCH){
} else if (postType == PostDataSource.TYPE_SEARCH) {
return (T) new PostViewModel(retrofit, accessToken, locale, subredditName, query,
postType, sortType, filter, nsfw);
} else if(postType == PostDataSource.TYPE_SUBREDDIT) {
} else if (postType == PostDataSource.TYPE_SUBREDDIT) {
return (T) new PostViewModel(retrofit, accessToken, locale, subredditName, postType,
sortType, filter, nsfw);
} else {

View File

@ -34,22 +34,17 @@ import retrofit2.Retrofit;
public class PullNotificationWorker extends Worker {
public static final String WORKER_TAG = "PNWT";
private Context context;
@Inject
@Named("oauth_without_authenticator")
Retrofit mOauthWithoutAuthenticatorRetrofit;
@Inject
@Named("no_oauth")
Retrofit mRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
SharedPreferences mSharedPreferences;
private Context context;
public PullNotificationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
@ -62,18 +57,18 @@ public class PullNotificationWorker extends Worker {
public Result doWork() {
try {
List<Account> accounts = mRedditDataRoomDatabase.accountDao().getAllAccounts();
for(int accountIndex = 0; accountIndex < accounts.size(); accountIndex++) {
for (int accountIndex = 0; accountIndex < accounts.size(); accountIndex++) {
Account account = accounts.get(accountIndex);
String accountName = account.getUsername();
Response<String> response = fetchMessages(account, 1);
if(response != null && response.isSuccessful()) {
if (response != null && response.isSuccessful()) {
String responseBody = response.body();
ArrayList<Message> messages = FetchMessages.parseMessage(responseBody, context.getResources().getConfiguration().locale);
if(messages != null && !messages.isEmpty()) {
if (messages != null && !messages.isEmpty()) {
NotificationManagerCompat notificationManager = NotificationUtils.getNotificationManager(context);
NotificationCompat.Builder summaryBuilder = NotificationUtils.buildSummaryNotification(context,
@ -91,9 +86,9 @@ public class PullNotificationWorker extends Worker {
* 1000 * 60 * 60;
boolean hasValidMessage = false;
for(int messageIndex = messageSize - 1; messageIndex >= 0; messageIndex--) {
for (int messageIndex = messageSize - 1; messageIndex >= 0; messageIndex--) {
Message message = messages.get(messageIndex);
if(currentTime - message.getTimeUTC() > notificationInterval) {
if (currentTime - message.getTimeUTC() > notificationInterval) {
continue;
}
@ -104,16 +99,16 @@ public class PullNotificationWorker extends Worker {
String kind = message.getKind();
String title;
String summary;
if(kind.equals(Message.TYPE_COMMENT) || kind.equals(Message.TYPE_LINK)) {
if (kind.equals(Message.TYPE_COMMENT) || kind.equals(Message.TYPE_LINK)) {
title = message.getAuthor();
summary = message.getSubject().substring(0, 1).toUpperCase() + message.getSubject().substring(1);
} else {
title = message.getTitle() == null || message.getTitle().equals("") ? message.getSubject() : message.getTitle();
if(kind.equals(Message.TYPE_ACCOUNT)) {
if (kind.equals(Message.TYPE_ACCOUNT)) {
summary = context.getString(R.string.notification_summary_account);
} else if(kind.equals(Message.TYPE_MESSAGE)) {
} else if (kind.equals(Message.TYPE_MESSAGE)) {
summary = context.getString(R.string.notification_summary_message);
} else if(kind.equals(Message.TYPE_SUBREDDIT)) {
} else if (kind.equals(Message.TYPE_SUBREDDIT)) {
summary = context.getString(R.string.notification_summary_subreddit);
} else {
summary = context.getString(R.string.notification_summary_award);
@ -126,7 +121,7 @@ public class PullNotificationWorker extends Worker {
NotificationUtils.CHANNEL_NEW_MESSAGES,
NotificationUtils.getAccountGroupName(accountName));
if(kind.equals(Message.TYPE_COMMENT)) {
if (kind.equals(Message.TYPE_COMMENT)) {
Intent intent = new Intent(context, LinkResolverActivity.class);
Uri uri = LinkResolverActivity.getRedditUriByPath(message.getContext());
intent.setData(uri);
@ -134,12 +129,12 @@ public class PullNotificationWorker extends Worker {
intent.putExtra(LinkResolverActivity.EXTRA_MESSAGE_FULLNAME, message.getFullname());
PendingIntent pendingIntent = PendingIntent.getActivity(context, accountIndex * 6, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
} else if(kind.equals(Message.TYPE_ACCOUNT)) {
} else if (kind.equals(Message.TYPE_ACCOUNT)) {
Intent intent = new Intent(context, ViewMessageActivity.class);
intent.putExtra(ViewMessageActivity.EXTRA_NEW_ACCOUNT_NAME, accountName);
PendingIntent summaryPendingIntent = PendingIntent.getActivity(context, accountIndex * 6 + 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(summaryPendingIntent);
} else if(kind.equals(Message.TYPE_LINK)) {
} else if (kind.equals(Message.TYPE_LINK)) {
Intent intent = new Intent(context, LinkResolverActivity.class);
Uri uri = LinkResolverActivity.getRedditUriByPath(message.getContext());
intent.setData(uri);
@ -147,12 +142,12 @@ public class PullNotificationWorker extends Worker {
intent.putExtra(LinkResolverActivity.EXTRA_MESSAGE_FULLNAME, message.getFullname());
PendingIntent pendingIntent = PendingIntent.getActivity(context, accountIndex * 6 + 2, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
} else if(kind.equals(Message.TYPE_MESSAGE)) {
} else if (kind.equals(Message.TYPE_MESSAGE)) {
Intent intent = new Intent(context, ViewMessageActivity.class);
intent.putExtra(ViewMessageActivity.EXTRA_NEW_ACCOUNT_NAME, accountName);
PendingIntent summaryPendingIntent = PendingIntent.getActivity(context, accountIndex * 6 + 3, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(summaryPendingIntent);
} else if(kind.equals(Message.TYPE_SUBREDDIT)) {
} else if (kind.equals(Message.TYPE_SUBREDDIT)) {
Intent intent = new Intent(context, ViewMessageActivity.class);
intent.putExtra(ViewMessageActivity.EXTRA_NEW_ACCOUNT_NAME, accountName);
PendingIntent summaryPendingIntent = PendingIntent.getActivity(context, accountIndex * 6 + 4, intent, PendingIntent.FLAG_UPDATE_CURRENT);
@ -166,7 +161,7 @@ public class PullNotificationWorker extends Worker {
notificationManager.notify(NotificationUtils.getNotificationIdUnreadMessage(accountIndex, messageIndex), builder.build());
}
if(hasValidMessage) {
if (hasValidMessage) {
inboxStyle.setBigContentTitle(context.getString(R.string.notification_new_messages, messages.size()))
.setSummaryText(accountName);
@ -197,7 +192,7 @@ public class PullNotificationWorker extends Worker {
}
private Response<String> fetchMessages(Account account, int retryCount) throws IOException, JSONException {
if(retryCount < 0) {
if (retryCount < 0) {
return null;
}
@ -206,12 +201,12 @@ public class PullNotificationWorker extends Worker {
FetchMessages.WHERE_UNREAD, null);
Response<String> response = call.execute();
if(response.isSuccessful()) {
if (response.isSuccessful()) {
return response;
} else {
if(response.code() == 401) {
if (response.code() == 401) {
String accessToken = refreshAccessToken(account);
if(!accessToken.equals("")) {
if (!accessToken.equals("")) {
return fetchMessages(account, retryCount - 1);
}
@ -234,7 +229,7 @@ public class PullNotificationWorker extends Worker {
Call<String> accessTokenCall = api.getAccessToken(RedditUtils.getHttpBasicAuthHeader(), params);
try {
Response response = accessTokenCall.execute();
if(response.isSuccessful() && response.body() != null) {
if (response.isSuccessful() && response.body() != null) {
JSONObject jsonObject = new JSONObject(response.body().toString());
String newAccessToken = jsonObject.getString(RedditUtils.ACCESS_TOKEN_KEY);
mRedditDataRoomDatabase.accountDao().changeAccessToken(account.getUsername(), newAccessToken);

Some files were not shown because too many files have changed in this diff Show More