From d30651331922db62cd13371e79a42bfb39102fea Mon Sep 17 00:00:00 2001 From: Xiang Rong Lin <41164160+XiangRongLin@users.noreply.github.com> Date: Sun, 16 Aug 2020 08:42:56 +0200 Subject: [PATCH 1/2] Add checkstyle rule to show final local variable violations as warning --- checkstyle.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/checkstyle.xml b/checkstyle.xml index c61b92247..af8c5480f 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -154,6 +154,10 @@ + + + + From 87228673b45225a57b53937ab2c9715d7bf205ca Mon Sep 17 00:00:00 2001 From: wb9688 Date: Sun, 16 Aug 2020 10:24:58 +0200 Subject: [PATCH 2/2] Use final where possible --- .../schabi/newpipe/report/ErrorInfoTest.java | 6 +- ...agmentStatePagerAdapterMenuWorkaround.java | 28 +++--- .../material/appbar/FlingBehavior.java | 28 +++--- app/src/main/java/org/schabi/newpipe/App.java | 12 +-- .../newpipe/CheckForNewAppVersionTask.java | 10 +-- .../org/schabi/newpipe/DownloaderImpl.java | 38 ++++----- .../java/org/schabi/newpipe/ExitActivity.java | 2 +- .../java/org/schabi/newpipe/MainActivity.java | 72 ++++++++-------- .../org/schabi/newpipe/NewPipeDatabase.java | 2 +- .../newpipe/PanicResponderActivity.java | 2 +- .../org/schabi/newpipe/ReCaptchaActivity.java | 20 ++--- .../org/schabi/newpipe/RouterActivity.java | 32 +++---- .../schabi/newpipe/about/AboutActivity.java | 20 ++--- .../schabi/newpipe/about/LicenseFragment.java | 4 +- .../newpipe/about/LicenseFragmentHelper.java | 2 +- .../schabi/newpipe/database/Converters.java | 2 +- .../subscription/SubscriptionEntity.java | 4 +- .../newpipe/download/DownloadActivity.java | 10 +-- .../newpipe/download/DownloadDialog.java | 56 ++++++------ .../newpipe/fragments/BaseStateFragment.java | 2 +- .../newpipe/fragments/MainFragment.java | 8 +- .../fragments/OnScrollBelowItemsListener.java | 8 +- .../newpipe/fragments/detail/TabAdaptor.java | 2 +- .../fragments/detail/VideoDetailFragment.java | 52 ++++++------ .../fragments/list/BaseListFragment.java | 10 +-- .../list/channel/ChannelFragment.java | 32 +++---- .../list/comments/CommentsFragment.java | 2 +- .../list/kiosk/DefaultKioskFragment.java | 2 +- .../fragments/list/kiosk/KioskFragment.java | 10 +-- .../list/playlist/PlaylistFragment.java | 8 +- .../fragments/list/search/SearchFragment.java | 48 ++++++----- .../list/search/SuggestionListAdapter.java | 6 +- .../list/videos/RelatedVideosFragment.java | 8 +- .../newpipe/info_list/InfoItemBuilder.java | 3 +- .../newpipe/info_list/InfoItemDialog.java | 4 +- .../newpipe/info_list/InfoListAdapter.java | 14 +-- .../holder/ChannelInfoItemHolder.java | 4 +- .../holder/CommentsMiniInfoItemHolder.java | 15 ++-- .../holder/StreamMiniInfoItemHolder.java | 5 +- .../newpipe/local/LocalItemListAdapter.java | 8 +- .../local/bookmark/BookmarkFragment.java | 6 +- .../local/dialog/PlaylistAppendDialog.java | 10 +-- .../local/dialog/PlaylistCreationDialog.java | 6 +- .../local/history/HistoryRecordManager.java | 14 +-- .../history/StatisticsPlaylistFragment.java | 2 +- .../holder/LocalPlaylistStreamItemHolder.java | 4 +- .../LocalStatisticStreamItemHolder.java | 4 +- .../local/playlist/LocalPlaylistFragment.java | 14 +-- .../local/playlist/LocalPlaylistManager.java | 6 +- .../local/playlist/RemotePlaylistManager.java | 2 +- .../SubscriptionsImportFragment.java | 6 +- .../services/ImportExportJsonHelper.java | 16 ++-- .../services/SubscriptionsExportService.java | 4 +- .../services/SubscriptionsImportService.java | 8 +- .../org/schabi/newpipe/player/BasePlayer.java | 8 +- .../newpipe/player/ServicePlayerActivity.java | 4 +- .../schabi/newpipe/player/VideoPlayer.java | 24 +++--- .../newpipe/player/VideoPlayerImpl.java | 14 +-- .../player/event/PlayerGestureListener.java | 18 ++-- .../newpipe/player/helper/AudioReactor.java | 2 +- .../newpipe/player/helper/CacheFactory.java | 4 +- .../newpipe/player/helper/LoadController.java | 2 +- .../player/helper/MediaSessionManager.java | 4 +- .../helper/PlaybackParameterDialog.java | 20 ++--- .../newpipe/player/helper/PlayerHelper.java | 16 ++-- .../mediasession/PlayQueueNavigator.java | 10 +-- .../playback/BasePlayerMediaSession.java | 5 +- .../player/playback/CustomTrackSelector.java | 8 +- .../playqueue/AbstractInfoPlayQueue.java | 2 +- .../player/playqueue/SinglePlayQueue.java | 2 +- .../resolver/VideoPlaybackResolver.java | 2 +- .../schabi/newpipe/report/ErrorActivity.java | 52 ++++++------ .../settings/AppearanceSettingsFragment.java | 4 +- .../settings/BasePreferenceFragment.java | 2 +- .../settings/ContentSettingsFragment.java | 58 ++++++------- .../settings/DownloadSettingsFragment.java | 25 +++--- .../newpipe/settings/NewPipeSettings.java | 6 +- .../PeertubeInstanceListFragment.java | 30 +++---- .../settings/SelectChannelFragment.java | 12 +-- .../newpipe/settings/SelectKioskFragment.java | 12 +-- .../settings/SelectPlaylistFragment.java | 2 +- .../newpipe/settings/SettingsActivity.java | 8 +- .../settings/UpdateSettingsFragment.java | 2 +- .../settings/VideoAudioSettingsFragment.java | 8 +- .../settings/tabs/ChooseTabsFragment.java | 12 +-- .../org/schabi/newpipe/settings/tabs/Tab.java | 4 +- .../newpipe/settings/tabs/TabsJsonHelper.java | 6 +- .../newpipe/settings/tabs/TabsManager.java | 2 +- .../schabi/newpipe/streams/DataReader.java | 19 +++-- .../schabi/newpipe/streams/Mp4DashReader.java | 82 +++++++++--------- .../newpipe/streams/Mp4FromDashWriter.java | 85 ++++++++++--------- .../newpipe/streams/OggFromWebMWriter.java | 22 ++--- .../newpipe/streams/SrtFromTtmlWriter.java | 16 ++-- .../schabi/newpipe/streams/WebMReader.java | 38 ++++----- .../schabi/newpipe/streams/WebMWriter.java | 71 ++++++++-------- .../schabi/newpipe/util/AnimationUtils.java | 12 +-- .../org/schabi/newpipe/util/BitmapUtils.java | 25 +++--- .../util/CommentTextOnTouchListener.java | 36 ++++---- .../org/schabi/newpipe/util/CookieUtils.java | 4 +- .../org/schabi/newpipe/util/DeviceUtils.java | 5 +- .../schabi/newpipe/util/ExtractorHelper.java | 12 +-- .../schabi/newpipe/util/FilenameUtils.java | 4 +- .../org/schabi/newpipe/util/InfoCache.java | 2 +- .../util/LayoutManagerSmoothScroller.java | 2 +- .../org/schabi/newpipe/util/ListHelper.java | 77 +++++++++-------- .../org/schabi/newpipe/util/Localization.java | 30 +++---- .../schabi/newpipe/util/NavigationHelper.java | 44 +++++----- .../schabi/newpipe/util/PeertubeHelper.java | 27 +++--- .../schabi/newpipe/util/PermissionHelper.java | 9 +- .../newpipe/util/RelatedStreamInfo.java | 6 +- .../newpipe/util/SecondaryStreamHelper.java | 6 +- .../schabi/newpipe/util/ServiceHelper.java | 22 ++--- .../org/schabi/newpipe/util/ShareUtils.java | 2 +- .../org/schabi/newpipe/util/StateSaver.java | 32 +++---- .../newpipe/util/StreamDialogEntry.java | 4 +- .../newpipe/util/StreamItemAdapter.java | 11 +-- .../newpipe/util/TLSSocketFactoryCompat.java | 4 +- .../org/schabi/newpipe/util/ThemeHelper.java | 28 +++--- .../org/schabi/newpipe/util/ZipHelper.java | 16 ++-- .../newpipe/views/AnimatedProgressBar.java | 2 +- .../schabi/newpipe/views/CollapsibleView.java | 2 +- .../newpipe/views/FocusAwareDrawerLayout.java | 10 ++- .../newpipe/views/FocusOverlayView.java | 36 ++++---- .../views/LargeTextMovementMethod.java | 64 +++++++------- .../newpipe/views/NewPipeRecyclerView.java | 12 +-- .../newpipe/views/ScrollableTabLayout.java | 2 +- .../views/SuperScrollLayoutManager.java | 16 ++-- .../services/ImportExportJsonHelperTest.java | 18 ++-- .../schabi/newpipe/settings/tabs/TabTest.java | 2 +- .../settings/tabs/TabsJsonHelperTest.java | 9 +- .../schabi/newpipe/util/ListHelperTest.java | 8 +- checkstyle-suppressions.xml | 2 +- 132 files changed, 1024 insertions(+), 1005 deletions(-) diff --git a/app/src/androidTest/java/org/schabi/newpipe/report/ErrorInfoTest.java b/app/src/androidTest/java/org/schabi/newpipe/report/ErrorInfoTest.java index 55e747cd5..972737d25 100644 --- a/app/src/androidTest/java/org/schabi/newpipe/report/ErrorInfoTest.java +++ b/app/src/androidTest/java/org/schabi/newpipe/report/ErrorInfoTest.java @@ -21,13 +21,13 @@ public class ErrorInfoTest { @Test public void errorInfoTestParcelable() { - ErrorInfo info = ErrorInfo.make(UserAction.USER_REPORT, "youtube", "request", + final ErrorInfo info = ErrorInfo.make(UserAction.USER_REPORT, "youtube", "request", R.string.general_error); // Obtain a Parcel object and write the parcelable object to it: - Parcel parcel = Parcel.obtain(); + final Parcel parcel = Parcel.obtain(); info.writeToParcel(parcel, 0); parcel.setDataPosition(0); - ErrorInfo infoFromParcel = ErrorInfo.CREATOR.createFromParcel(parcel); + final ErrorInfo infoFromParcel = ErrorInfo.CREATOR.createFromParcel(parcel); assertEquals(UserAction.USER_REPORT, infoFromParcel.userAction); assertEquals("youtube", infoFromParcel.serviceName); diff --git a/app/src/main/java/androidx/fragment/app/FragmentStatePagerAdapterMenuWorkaround.java b/app/src/main/java/androidx/fragment/app/FragmentStatePagerAdapterMenuWorkaround.java index 11f457b6c..5840b0f7e 100644 --- a/app/src/main/java/androidx/fragment/app/FragmentStatePagerAdapterMenuWorkaround.java +++ b/app/src/main/java/androidx/fragment/app/FragmentStatePagerAdapterMenuWorkaround.java @@ -150,7 +150,7 @@ public abstract class FragmentStatePagerAdapterMenuWorkaround extends PagerAdapt // from its saved state, where the fragment manager has already // taken care of restoring the fragments we previously had instantiated. if (mFragments.size() > position) { - Fragment f = mFragments.get(position); + final Fragment f = mFragments.get(position); if (f != null) { return f; } @@ -160,12 +160,12 @@ public abstract class FragmentStatePagerAdapterMenuWorkaround extends PagerAdapt mCurTransaction = mFragmentManager.beginTransaction(); } - Fragment fragment = getItem(position); + final Fragment fragment = getItem(position); if (DEBUG) { Log.v(TAG, "Adding item #" + position + ": f=" + fragment); } if (mSavedState.size() > position) { - Fragment.SavedState fss = mSavedState.get(position); + final Fragment.SavedState fss = mSavedState.get(position); if (fss != null) { fragment.setInitialSavedState(fss); } @@ -191,7 +191,7 @@ public abstract class FragmentStatePagerAdapterMenuWorkaround extends PagerAdapt @Override public void destroyItem(@NonNull final ViewGroup container, final int position, @NonNull final Object object) { - Fragment fragment = (Fragment) object; + final Fragment fragment = (Fragment) object; if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); @@ -217,7 +217,7 @@ public abstract class FragmentStatePagerAdapterMenuWorkaround extends PagerAdapt @SuppressWarnings({"ReferenceEquality", "deprecation"}) public void setPrimaryItem(@NonNull final ViewGroup container, final int position, @NonNull final Object object) { - Fragment fragment = (Fragment) object; + final Fragment fragment = (Fragment) object; if (fragment != mCurrentPrimaryItem) { if (mCurrentPrimaryItem != null) { mCurrentPrimaryItem.setMenuVisibility(false); @@ -267,17 +267,17 @@ public abstract class FragmentStatePagerAdapterMenuWorkaround extends PagerAdapt Bundle state = null; if (mSavedState.size() > 0) { state = new Bundle(); - Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()]; + final Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()]; mSavedState.toArray(fss); state.putParcelableArray("states", fss); } for (int i = 0; i < mFragments.size(); i++) { - Fragment f = mFragments.get(i); + final Fragment f = mFragments.get(i); if (f != null && f.isAdded()) { if (state == null) { state = new Bundle(); } - String key = "f" + i; + final String key = "f" + i; mFragmentManager.putFragment(state, key, f); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@ -294,9 +294,9 @@ public abstract class FragmentStatePagerAdapterMenuWorkaround extends PagerAdapt @Override public void restoreState(@Nullable final Parcelable state, @Nullable final ClassLoader loader) { if (state != null) { - Bundle bundle = (Bundle) state; + final Bundle bundle = (Bundle) state; bundle.setClassLoader(loader); - Parcelable[] fss = bundle.getParcelableArray("states"); + final Parcelable[] fss = bundle.getParcelableArray("states"); mSavedState.clear(); mFragments.clear(); if (fss != null) { @@ -304,11 +304,11 @@ public abstract class FragmentStatePagerAdapterMenuWorkaround extends PagerAdapt mSavedState.add((Fragment.SavedState) fss[i]); } } - Iterable keys = bundle.keySet(); - for (String key: keys) { + final Iterable keys = bundle.keySet(); + for (final String key : keys) { if (key.startsWith("f")) { - int index = Integer.parseInt(key.substring(1)); - Fragment f = mFragmentManager.getFragment(bundle, key); + final int index = Integer.parseInt(key.substring(1)); + final Fragment f = mFragmentManager.getFragment(bundle, key); if (f != null) { while (mFragments.size() <= index) { mFragments.add(null); diff --git a/app/src/main/java/com/google/android/material/appbar/FlingBehavior.java b/app/src/main/java/com/google/android/material/appbar/FlingBehavior.java index 90e5edcd3..174631fde 100644 --- a/app/src/main/java/com/google/android/material/appbar/FlingBehavior.java +++ b/app/src/main/java/com/google/android/material/appbar/FlingBehavior.java @@ -30,19 +30,18 @@ public final class FlingBehavior extends AppBarLayout.Behavior { public boolean onRequestChildRectangleOnScreen( @NonNull final CoordinatorLayout coordinatorLayout, @NonNull final AppBarLayout child, @NonNull final Rect rectangle, final boolean immediate) { - focusScrollRect.set(rectangle); coordinatorLayout.offsetDescendantRectToMyCoords(child, focusScrollRect); - int height = coordinatorLayout.getHeight(); + final int height = coordinatorLayout.getHeight(); if (focusScrollRect.top <= 0 && focusScrollRect.bottom >= height) { // the child is too big to fit inside ourselves completely, ignore request return false; } - int dy; + final int dy; if (focusScrollRect.bottom > height) { dy = focusScrollRect.top; @@ -54,7 +53,7 @@ public final class FlingBehavior extends AppBarLayout.Behavior { return false; } - int consumed = scroll(coordinatorLayout, child, dy, getMaxDragOffset(child), 0); + final int consumed = scroll(coordinatorLayout, child, dy, getMaxDragOffset(child), 0); return consumed == dy; } @@ -106,14 +105,14 @@ public final class FlingBehavior extends AppBarLayout.Behavior { @Nullable private OverScroller getScrollerField() { try { - Class headerBehaviorType = this.getClass() + final Class headerBehaviorType = this.getClass() .getSuperclass().getSuperclass().getSuperclass(); if (headerBehaviorType != null) { - Field field = headerBehaviorType.getDeclaredField("scroller"); + final Field field = headerBehaviorType.getDeclaredField("scroller"); field.setAccessible(true); return ((OverScroller) field.get(this)); } - } catch (NoSuchFieldException | IllegalAccessException e) { + } catch (final NoSuchFieldException | IllegalAccessException e) { // ? } return null; @@ -122,34 +121,35 @@ public final class FlingBehavior extends AppBarLayout.Behavior { @Nullable private Field getLastNestedScrollingChildRefField() { try { - Class headerBehaviorType = this.getClass().getSuperclass().getSuperclass(); + final Class headerBehaviorType = this.getClass().getSuperclass().getSuperclass(); if (headerBehaviorType != null) { - Field field = headerBehaviorType.getDeclaredField("lastNestedScrollingChildRef"); + final Field field + = headerBehaviorType.getDeclaredField("lastNestedScrollingChildRef"); field.setAccessible(true); return field; } - } catch (NoSuchFieldException e) { + } catch (final NoSuchFieldException e) { // ? } return null; } private void resetNestedScrollingChild() { - Field field = getLastNestedScrollingChildRefField(); + final Field field = getLastNestedScrollingChildRefField(); if (field != null) { try { - Object value = field.get(this); + final Object value = field.get(this); if (value != null) { field.set(this, null); } - } catch (IllegalAccessException e) { + } catch (final IllegalAccessException e) { // ? } } } private void stopAppBarLayoutFling() { - OverScroller scroller = getScrollerField(); + final OverScroller scroller = getScrollerField(); if (scroller != null) { scroller.forceFinished(true); } diff --git a/app/src/main/java/org/schabi/newpipe/App.java b/app/src/main/java/org/schabi/newpipe/App.java index 0071d2efe..00842ec46 100644 --- a/app/src/main/java/org/schabi/newpipe/App.java +++ b/app/src/main/java/org/schabi/newpipe/App.java @@ -104,7 +104,7 @@ public class App extends Application { } protected Downloader getDownloader() { - DownloaderImpl downloader = DownloaderImpl.init(null); + final DownloaderImpl downloader = DownloaderImpl.init(null); setCookiesToDownloader(downloader); return downloader; } @@ -208,7 +208,7 @@ public class App extends Application { .setBuildConfigClass(BuildConfig.class) .build(); ACRA.init(this, acraConfig); - } catch (ACRAConfigurationException ace) { + } catch (final ACRAConfigurationException ace) { ace.printStackTrace(); ErrorActivity.reportError(this, ace, @@ -231,10 +231,10 @@ public class App extends Application { // Keep this below DEFAULT to avoid making noise on every notification update final int importance = NotificationManager.IMPORTANCE_LOW; - NotificationChannel mChannel = new NotificationChannel(id, name, importance); + final NotificationChannel mChannel = new NotificationChannel(id, name, importance); mChannel.setDescription(description); - NotificationManager mNotificationManager = + final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.createNotificationChannel(mChannel); @@ -255,11 +255,11 @@ public class App extends Application { final String appUpdateDescription = getString(R.string.app_update_notification_channel_description); - NotificationChannel appUpdateChannel + final NotificationChannel appUpdateChannel = new NotificationChannel(appUpdateId, appUpdateName, importance); appUpdateChannel.setDescription(appUpdateDescription); - NotificationManager appUpdateNotificationManager + final NotificationManager appUpdateNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); appUpdateNotificationManager.createNotificationChannel(appUpdateChannel); } diff --git a/app/src/main/java/org/schabi/newpipe/CheckForNewAppVersionTask.java b/app/src/main/java/org/schabi/newpipe/CheckForNewAppVersionTask.java index 625f514e9..0d211fdfd 100644 --- a/app/src/main/java/org/schabi/newpipe/CheckForNewAppVersionTask.java +++ b/app/src/main/java/org/schabi/newpipe/CheckForNewAppVersionTask.java @@ -62,7 +62,7 @@ public class CheckForNewAppVersionTask extends AsyncTask { try { packageInfo = pm.getPackageInfo(packageName, flags); - } catch (PackageManager.NameNotFoundException e) { + } catch (final PackageManager.NameNotFoundException e) { ErrorActivity.reportError(APP, e, null, null, ErrorActivity.ErrorInfo.make(UserAction.SOMETHING_ELSE, "none", "Could not find package info", R.string.app_ui_crash)); @@ -77,7 +77,7 @@ public class CheckForNewAppVersionTask extends AsyncTask { try { final CertificateFactory cf = CertificateFactory.getInstance("X509"); c = (X509Certificate) cf.generateCertificate(input); - } catch (CertificateException e) { + } catch (final CertificateException e) { ErrorActivity.reportError(APP, e, null, null, ErrorActivity.ErrorInfo.make(UserAction.SOMETHING_ELSE, "none", "Certificate error", R.string.app_ui_crash)); @@ -86,7 +86,7 @@ public class CheckForNewAppVersionTask extends AsyncTask { String hexString = null; try { - MessageDigest md = MessageDigest.getInstance("SHA1"); + final MessageDigest md = MessageDigest.getInstance("SHA1"); final byte[] publicKey = md.digest(c.getEncoded()); hexString = byte2HexFormatted(publicKey); } catch (NoSuchAlgorithmException | CertificateEncodingException e) { @@ -167,7 +167,7 @@ public class CheckForNewAppVersionTask extends AsyncTask { compareAppVersionAndShowNotification(versionName, apkLocationUrl, versionCode); - } catch (JsonParserException e) { + } catch (final JsonParserException e) { // connectivity problems, do not alarm user and fail silently if (DEBUG) { Log.w(TAG, Log.getStackTraceString(e)); @@ -187,7 +187,7 @@ public class CheckForNewAppVersionTask extends AsyncTask { private void compareAppVersionAndShowNotification(final String versionName, final String apkLocationUrl, final int versionCode) { - int notificationId = 2000; + final int notificationId = 2000; if (BuildConfig.VERSION_CODE < versionCode) { diff --git a/app/src/main/java/org/schabi/newpipe/DownloaderImpl.java b/app/src/main/java/org/schabi/newpipe/DownloaderImpl.java index 95d3c2b7c..9cba0667b 100644 --- a/app/src/main/java/org/schabi/newpipe/DownloaderImpl.java +++ b/app/src/main/java/org/schabi/newpipe/DownloaderImpl.java @@ -94,18 +94,18 @@ public final class DownloaderImpl extends Downloader { private static void enableModernTLS(final OkHttpClient.Builder builder) { try { // get the default TrustManager - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( + final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); - TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); + final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } - X509TrustManager trustManager = (X509TrustManager) trustManagers[0]; + final X509TrustManager trustManager = (X509TrustManager) trustManagers[0]; // insert our own TLSSocketFactory - SSLSocketFactory sslSocketFactory = TLSSocketFactoryCompat.getInstance(); + final SSLSocketFactory sslSocketFactory = TLSSocketFactoryCompat.getInstance(); builder.sslSocketFactory(sslSocketFactory, trustManager); @@ -114,16 +114,16 @@ public final class DownloaderImpl extends Downloader { // Necessary because some servers (e.g. Framatube.org) // don't support the old cipher suites. // https://github.com/square/okhttp/issues/4053#issuecomment-402579554 - List cipherSuites = new ArrayList<>(); + final List cipherSuites = new ArrayList<>(); cipherSuites.addAll(ConnectionSpec.MODERN_TLS.cipherSuites()); cipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA); cipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA); - ConnectionSpec legacyTLS = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) + final ConnectionSpec legacyTLS = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .cipherSuites(cipherSuites.toArray(new CipherSuite[0])) .build(); builder.connectionSpecs(Arrays.asList(legacyTLS, ConnectionSpec.CLEARTEXT)); - } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { + } catch (final KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { if (DEBUG) { e.printStackTrace(); } @@ -131,15 +131,15 @@ public final class DownloaderImpl extends Downloader { } public String getCookies(final String url) { - List resultCookies = new ArrayList<>(); + final List resultCookies = new ArrayList<>(); if (url.contains(YOUTUBE_DOMAIN)) { - String youtubeCookie = getCookie(YOUTUBE_RESTRICTED_MODE_COOKIE_KEY); + final String youtubeCookie = getCookie(YOUTUBE_RESTRICTED_MODE_COOKIE_KEY); if (youtubeCookie != null) { resultCookies.add(youtubeCookie); } } // Recaptcha cookie is always added TODO: not sure if this is necessary - String recaptchaCookie = getCookie(ReCaptchaActivity.RECAPTCHA_COOKIES_KEY); + final String recaptchaCookie = getCookie(ReCaptchaActivity.RECAPTCHA_COOKIES_KEY); if (recaptchaCookie != null) { resultCookies.add(recaptchaCookie); } @@ -159,9 +159,9 @@ public final class DownloaderImpl extends Downloader { } public void updateYoutubeRestrictedModeCookies(final Context context) { - String restrictedModeEnabledKey = + final String restrictedModeEnabledKey = context.getString(R.string.youtube_restricted_mode_enabled); - boolean restrictedModeEnabled = PreferenceManager.getDefaultSharedPreferences(context) + final boolean restrictedModeEnabled = PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(restrictedModeEnabledKey, false); updateYoutubeRestrictedModeCookies(restrictedModeEnabled); } @@ -186,9 +186,9 @@ public final class DownloaderImpl extends Downloader { try { final Response response = head(url); return Long.parseLong(response.getHeader("Content-Length")); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new IOException("Invalid content length", e); - } catch (ReCaptchaException e) { + } catch (final ReCaptchaException e) { throw new IOException(e); } } @@ -199,7 +199,7 @@ public final class DownloaderImpl extends Downloader { .method("GET", null).url(siteUrl) .addHeader("User-Agent", USER_AGENT); - String cookies = getCookies(siteUrl); + final String cookies = getCookies(siteUrl); if (!cookies.isEmpty()) { requestBuilder.addHeader("Cookie", cookies); } @@ -218,7 +218,7 @@ public final class DownloaderImpl extends Downloader { } return body.byteStream(); - } catch (ReCaptchaException e) { + } catch (final ReCaptchaException e) { throw new IOException(e.getMessage(), e.getCause()); } } @@ -240,18 +240,18 @@ public final class DownloaderImpl extends Downloader { .method(httpMethod, requestBody).url(url) .addHeader("User-Agent", USER_AGENT); - String cookies = getCookies(url); + final String cookies = getCookies(url); if (!cookies.isEmpty()) { requestBuilder.addHeader("Cookie", cookies); } - for (Map.Entry> pair : headers.entrySet()) { + for (final Map.Entry> pair : headers.entrySet()) { final String headerName = pair.getKey(); final List headerValueList = pair.getValue(); if (headerValueList.size() > 1) { requestBuilder.removeHeader(headerName); - for (String headerValue : headerValueList) { + for (final String headerValue : headerValueList) { requestBuilder.addHeader(headerName, headerValue); } } else if (headerValueList.size() == 1) { diff --git a/app/src/main/java/org/schabi/newpipe/ExitActivity.java b/app/src/main/java/org/schabi/newpipe/ExitActivity.java index 94eff9560..d4a4e3125 100644 --- a/app/src/main/java/org/schabi/newpipe/ExitActivity.java +++ b/app/src/main/java/org/schabi/newpipe/ExitActivity.java @@ -27,7 +27,7 @@ import android.os.Bundle; public class ExitActivity extends Activity { public static void exitAndRemoveFromRecentApps(final Activity activity) { - Intent intent = new Intent(activity, ExitActivity.class); + final Intent intent = new Intent(activity, ExitActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS diff --git a/app/src/main/java/org/schabi/newpipe/MainActivity.java b/app/src/main/java/org/schabi/newpipe/MainActivity.java index fb1ca2342..c3086d02c 100644 --- a/app/src/main/java/org/schabi/newpipe/MainActivity.java +++ b/app/src/main/java/org/schabi/newpipe/MainActivity.java @@ -140,7 +140,7 @@ public class MainActivity extends AppCompatActivity { setSupportActionBar(findViewById(R.id.toolbar)); try { setupDrawer(); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError(this, e); } @@ -155,8 +155,8 @@ public class MainActivity extends AppCompatActivity { drawerItems = findViewById(R.id.navigation); //Tabs - int currentServiceId = ServiceHelper.getSelectedServiceId(this); - StreamingService service = NewPipe.getService(currentServiceId); + final int currentServiceId = ServiceHelper.getSelectedServiceId(this); + final StreamingService service = NewPipe.getService(currentServiceId); int kioskId = 0; @@ -228,7 +228,7 @@ public class MainActivity extends AppCompatActivity { case R.id.menu_tabs_group: try { tabSelected(item); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError(this, e); } break; @@ -269,8 +269,8 @@ public class MainActivity extends AppCompatActivity { NavigationHelper.openStatisticFragment(getSupportFragmentManager()); break; default: - int currentServiceId = ServiceHelper.getSelectedServiceId(this); - StreamingService service = NewPipe.getService(currentServiceId); + final int currentServiceId = ServiceHelper.getSelectedServiceId(this); + final StreamingService service = NewPipe.getService(currentServiceId); String serviceName = ""; int kioskId = 0; @@ -299,8 +299,8 @@ public class MainActivity extends AppCompatActivity { } private void setupDrawerHeader() { - NavigationView navigationView = findViewById(R.id.navigation); - View hView = navigationView.getHeaderView(0); + final NavigationView navigationView = findViewById(R.id.navigation); + final View hView = navigationView.getHeaderView(0); serviceArrow = hView.findViewById(R.id.drawer_arrow); headerServiceIcon = hView.findViewById(R.id.drawer_header_service_icon); @@ -335,7 +335,7 @@ public class MainActivity extends AppCompatActivity { } else { try { showTabs(); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError(this, e); } } @@ -344,11 +344,11 @@ public class MainActivity extends AppCompatActivity { private void showServices() { serviceArrow.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp); - for (StreamingService s : NewPipe.getServices()) { + for (final StreamingService s : NewPipe.getServices()) { final String title = s.getServiceInfo().getName() + (ServiceHelper.isBeta(s) ? " (beta)" : ""); - MenuItem menuItem = drawerItems.getMenu() + final MenuItem menuItem = drawerItems.getMenu() .add(R.id.menu_services_group, s.getServiceId(), ORDER, title) .setIcon(ServiceHelper.getIcon(s.getServiceId())); @@ -362,20 +362,20 @@ public class MainActivity extends AppCompatActivity { } private void enhancePeertubeMenu(final StreamingService s, final MenuItem menuItem) { - PeertubeInstance currentInstace = PeertubeHelper.getCurrentInstance(); + final PeertubeInstance currentInstace = PeertubeHelper.getCurrentInstance(); menuItem.setTitle(currentInstace.getName() + (ServiceHelper.isBeta(s) ? " (beta)" : "")); - Spinner spinner = (Spinner) LayoutInflater.from(this) + final Spinner spinner = (Spinner) LayoutInflater.from(this) .inflate(R.layout.instance_spinner_layout, null); - List instances = PeertubeHelper.getInstanceList(this); - List items = new ArrayList<>(); + final List instances = PeertubeHelper.getInstanceList(this); + final List items = new ArrayList<>(); int defaultSelect = 0; - for (PeertubeInstance instance : instances) { + for (final PeertubeInstance instance : instances) { items.add(instance.getName()); if (instance.getUrl().equals(currentInstace.getUrl())) { defaultSelect = items.size() - 1; } } - ArrayAdapter adapter = new ArrayAdapter<>(this, + final ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.instance_spinner_item, items); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); @@ -384,7 +384,7 @@ public class MainActivity extends AppCompatActivity { @Override public void onItemSelected(final AdapterView parent, final View view, final int position, final long id) { - PeertubeInstance newInstance = instances.get(position); + final PeertubeInstance newInstance = instances.get(position); if (newInstance.getUrl().equals(PeertubeHelper.getCurrentInstance().getUrl())) { return; } @@ -410,8 +410,8 @@ public class MainActivity extends AppCompatActivity { serviceArrow.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp); //Tabs - int currentServiceId = ServiceHelper.getSelectedServiceId(this); - StreamingService service = NewPipe.getService(currentServiceId); + final int currentServiceId = ServiceHelper.getSelectedServiceId(this); + final StreamingService service = NewPipe.getService(currentServiceId); int kioskId = 0; @@ -476,11 +476,12 @@ public class MainActivity extends AppCompatActivity { headerServiceView.post(() -> headerServiceView.setSelected(true)); toggleServiceButton.setContentDescription( getString(R.string.drawer_header_description) + selectedServiceName); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError(this, e); } - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); + final SharedPreferences sharedPreferences + = PreferenceManager.getDefaultSharedPreferences(this); if (sharedPreferences.getBoolean(Constants.KEY_THEME_CHANGE, false)) { if (DEBUG) { Log.d(TAG, "Theme has changed, recreating activity..."); @@ -513,7 +514,7 @@ public class MainActivity extends AppCompatActivity { if (intent != null) { // Return if launched from a launcher (e.g. Nova Launcher, Pixel Launcher ...) // to not destroy the already created backstack - String action = intent.getAction(); + final String action = intent.getAction(); if ((action != null && action.equals(Intent.ACTION_MAIN)) && intent.hasCategory(Intent.CATEGORY_LAUNCHER)) { return; @@ -546,7 +547,7 @@ public class MainActivity extends AppCompatActivity { } if (DeviceUtils.isTv(this)) { - View drawerPanel = findViewById(R.id.navigation); + final View drawerPanel = findViewById(R.id.navigation); if (drawer.isDrawerOpen(drawerPanel)) { drawer.closeDrawers(); return; @@ -594,7 +595,7 @@ public class MainActivity extends AppCompatActivity { public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) { - for (int i : grantResults) { + for (final int i : grantResults) { if (i == PackageManager.PERMISSION_DENIED) { return; } @@ -604,7 +605,7 @@ public class MainActivity extends AppCompatActivity { NavigationHelper.openDownloads(this); break; case PermissionHelper.DOWNLOAD_DIALOG_REQUEST_CODE: - Fragment fragment = getSupportFragmentManager() + final Fragment fragment = getSupportFragmentManager() .findFragmentById(R.id.fragment_player_holder); if (fragment instanceof VideoDetailFragment) { ((VideoDetailFragment) fragment).openDownloadDialog(); @@ -656,13 +657,14 @@ public class MainActivity extends AppCompatActivity { } super.onCreateOptionsMenu(menu); - Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_holder); + final Fragment fragment + = getSupportFragmentManager().findFragmentById(R.id.fragment_holder); if (!(fragment instanceof SearchFragment)) { findViewById(R.id.toolbar).findViewById(R.id.toolbar_search_container) .setVisibility(View.GONE); } - ActionBar actionBar = getSupportActionBar(); + final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(false); } @@ -677,7 +679,7 @@ public class MainActivity extends AppCompatActivity { if (DEBUG) { Log.d(TAG, "onOptionsItemSelected() called with: item = [" + item + "]"); } - int id = item.getItemId(); + final int id = item.getItemId(); switch (id) { case android.R.id.home: @@ -745,13 +747,13 @@ public class MainActivity extends AppCompatActivity { } if (intent.hasExtra(Constants.KEY_LINK_TYPE)) { - String url = intent.getStringExtra(Constants.KEY_URL); - int serviceId = intent.getIntExtra(Constants.KEY_SERVICE_ID, 0); - String title = intent.getStringExtra(Constants.KEY_TITLE); + final String url = intent.getStringExtra(Constants.KEY_URL); + final int serviceId = intent.getIntExtra(Constants.KEY_SERVICE_ID, 0); + final String title = intent.getStringExtra(Constants.KEY_TITLE); switch (((StreamingService.LinkType) intent .getSerializableExtra(Constants.KEY_LINK_TYPE))) { case STREAM: - boolean autoPlay = intent + final boolean autoPlay = intent .getBooleanExtra(VideoDetailFragment.AUTO_PLAY, false); final String intentCacheKey = intent .getStringExtra(VideoPlayer.PLAY_QUEUE_KEY); @@ -780,7 +782,7 @@ public class MainActivity extends AppCompatActivity { if (searchString == null) { searchString = ""; } - int serviceId = intent.getIntExtra(Constants.KEY_SERVICE_ID, 0); + final int serviceId = intent.getIntExtra(Constants.KEY_SERVICE_ID, 0); NavigationHelper.openSearchFragment( getSupportFragmentManager(), serviceId, @@ -789,7 +791,7 @@ public class MainActivity extends AppCompatActivity { } else { NavigationHelper.gotoMainFragment(getSupportFragmentManager()); } - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError(this, e); } } diff --git a/app/src/main/java/org/schabi/newpipe/NewPipeDatabase.java b/app/src/main/java/org/schabi/newpipe/NewPipeDatabase.java index c59c48367..988a5ed98 100644 --- a/app/src/main/java/org/schabi/newpipe/NewPipeDatabase.java +++ b/app/src/main/java/org/schabi/newpipe/NewPipeDatabase.java @@ -46,7 +46,7 @@ public final class NewPipeDatabase { if (databaseInstance == null) { throw new IllegalStateException("database is not initialized"); } - Cursor c = databaseInstance.query("pragma wal_checkpoint(full)", null); + final Cursor c = databaseInstance.query("pragma wal_checkpoint(full)", null); if (c.moveToFirst() && c.getInt(0) == 1) { throw new RuntimeException("Checkpoint was blocked from completing"); } diff --git a/app/src/main/java/org/schabi/newpipe/PanicResponderActivity.java b/app/src/main/java/org/schabi/newpipe/PanicResponderActivity.java index 2e1abd598..75304a2b9 100644 --- a/app/src/main/java/org/schabi/newpipe/PanicResponderActivity.java +++ b/app/src/main/java/org/schabi/newpipe/PanicResponderActivity.java @@ -31,7 +31,7 @@ public class PanicResponderActivity extends Activity { @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Intent intent = getIntent(); + final Intent intent = getIntent(); if (intent != null && PANIC_TRIGGER_ACTION.equals(intent.getAction())) { // TODO: Explicitly clear the search results // once they are restored when the app restarts diff --git a/app/src/main/java/org/schabi/newpipe/ReCaptchaActivity.java b/app/src/main/java/org/schabi/newpipe/ReCaptchaActivity.java index 40ea4fd58..c962ed99d 100644 --- a/app/src/main/java/org/schabi/newpipe/ReCaptchaActivity.java +++ b/app/src/main/java/org/schabi/newpipe/ReCaptchaActivity.java @@ -61,7 +61,7 @@ public class ReCaptchaActivity extends AppCompatActivity { ThemeHelper.setTheme(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_recaptcha); - Toolbar toolbar = findViewById(R.id.toolbar); + final Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); String url = getIntent().getStringExtra(RECAPTCHA_URL_EXTRA); @@ -76,7 +76,7 @@ public class ReCaptchaActivity extends AppCompatActivity { webView = findViewById(R.id.reCaptchaWebView); // enable Javascript - WebSettings webSettings = webView.getSettings(); + final WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient() { @@ -84,7 +84,7 @@ public class ReCaptchaActivity extends AppCompatActivity { @Override public boolean shouldOverrideUrlLoading(final WebView view, final WebResourceRequest request) { - String url = request.getUrl().toString(); + final String url = request.getUrl().toString(); if (MainActivity.DEBUG) { Log.d(TAG, "shouldOverrideUrlLoading: request.url=" + url); } @@ -113,7 +113,7 @@ public class ReCaptchaActivity extends AppCompatActivity { // cleaning cache, history and cookies from webView webView.clearCache(true); webView.clearHistory(); - android.webkit.CookieManager cookieManager = CookieManager.getInstance(); + final android.webkit.CookieManager cookieManager = CookieManager.getInstance(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.removeAllCookies(aBoolean -> { }); @@ -128,7 +128,7 @@ public class ReCaptchaActivity extends AppCompatActivity { public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.menu_recaptcha, menu); - ActionBar actionBar = getSupportActionBar(); + final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setTitle(R.string.title_activity_recaptcha); @@ -145,7 +145,7 @@ public class ReCaptchaActivity extends AppCompatActivity { @Override public boolean onOptionsItemSelected(final MenuItem item) { - int id = item.getItemId(); + final int id = item.getItemId(); switch (id) { case R.id.menu_item_done: saveCookiesAndFinish(); @@ -173,7 +173,7 @@ public class ReCaptchaActivity extends AppCompatActivity { setResult(RESULT_OK); } - Intent intent = new Intent(this, org.schabi.newpipe.MainActivity.class); + final Intent intent = new Intent(this, org.schabi.newpipe.MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); NavUtils.navigateUpTo(this, intent); } @@ -188,13 +188,13 @@ public class ReCaptchaActivity extends AppCompatActivity { return; } - String cookies = CookieManager.getInstance().getCookie(url); + final String cookies = CookieManager.getInstance().getCookie(url); handleCookies(cookies); // sometimes cookies are inside the url - int abuseStart = url.indexOf("google_abuse="); + final int abuseStart = url.indexOf("google_abuse="); if (abuseStart != -1) { - int abuseEnd = url.indexOf("+path"); + final int abuseEnd = url.indexOf("+path"); try { String abuseCookie = url.substring(abuseStart + 13, abuseEnd); diff --git a/app/src/main/java/org/schabi/newpipe/RouterActivity.java b/app/src/main/java/org/schabi/newpipe/RouterActivity.java index e9e166c22..70fceaf07 100644 --- a/app/src/main/java/org/schabi/newpipe/RouterActivity.java +++ b/app/src/main/java/org/schabi/newpipe/RouterActivity.java @@ -310,7 +310,7 @@ public class RouterActivity extends AppCompatActivity { }; int id = 12345; - for (AdapterChoiceItem item : choices) { + for (final AdapterChoiceItem item : choices) { final RadioButton radioButton = (RadioButton) inflater.inflate(R.layout.list_radio_icon_item, null); radioButton.setText(item.description); @@ -330,7 +330,7 @@ public class RouterActivity extends AppCompatActivity { getString(R.string.preferred_open_action_last_selected_key), null); if (!TextUtils.isEmpty(lastSelectedPlayer)) { for (int i = 0; i < choices.size(); i++) { - AdapterChoiceItem c = choices.get(i); + final AdapterChoiceItem c = choices.get(i); if (lastSelectedPlayer.equals(c.key)) { selectedRadioPosition = i; break; @@ -362,9 +362,9 @@ public class RouterActivity extends AppCompatActivity { final SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this); - boolean isExtVideoEnabled = preferences.getBoolean( + final boolean isExtVideoEnabled = preferences.getBoolean( getString(R.string.use_external_video_player_key), false); - boolean isExtAudioEnabled = preferences.getBoolean( + final boolean isExtAudioEnabled = preferences.getBoolean( getString(R.string.use_external_audio_player_key), false); returnList.add(new AdapterChoiceItem(getString(R.string.show_info_key), @@ -410,9 +410,9 @@ public class RouterActivity extends AppCompatActivity { } private void handleText() { - String searchString = getIntent().getStringExtra(Intent.EXTRA_TEXT); - int serviceId = getIntent().getIntExtra(Constants.KEY_SERVICE_ID, 0); - Intent intent = new Intent(getThemeWrapperContext(), MainActivity.class); + final String searchString = getIntent().getStringExtra(Intent.EXTRA_TEXT); + final int serviceId = getIntent().getIntExtra(Constants.KEY_SERVICE_ID, 0); + final Intent intent = new Intent(getThemeWrapperContext(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); NavigationHelper.openSearch(getThemeWrapperContext(), serviceId, searchString); @@ -479,14 +479,14 @@ public class RouterActivity extends AppCompatActivity { .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((@NonNull StreamInfo result) -> { - List sortedVideoStreams = ListHelper + final List sortedVideoStreams = ListHelper .getSortedStreamVideosList(this, result.getVideoStreams(), result.getVideoOnlyStreams(), false); - int selectedVideoStreamIndex = ListHelper + final int selectedVideoStreamIndex = ListHelper .getDefaultResolutionIndex(this, sortedVideoStreams); - FragmentManager fm = getSupportFragmentManager(); - DownloadDialog downloadDialog = DownloadDialog.newInstance(result); + final FragmentManager fm = getSupportFragmentManager(); + final DownloadDialog downloadDialog = DownloadDialog.newInstance(result); downloadDialog.setVideoStreams(sortedVideoStreams); downloadDialog.setAudioStreams(result.getAudioStreams()); downloadDialog.setSelectedVideoStream(selectedVideoStreamIndex); @@ -504,7 +504,7 @@ public class RouterActivity extends AppCompatActivity { public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) { - for (int i : grantResults) { + for (final int i : grantResults) { if (i == PackageManager.PERMISSION_DENIED) { finish(); return; @@ -634,7 +634,7 @@ public class RouterActivity extends AppCompatActivity { if (!(serializable instanceof Choice)) { return; } - Choice playerChoice = (Choice) serializable; + final Choice playerChoice = (Choice) serializable; handleChoice(playerChoice); } @@ -682,13 +682,13 @@ public class RouterActivity extends AppCompatActivity { final SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this); - boolean isExtVideoEnabled = preferences.getBoolean( + final boolean isExtVideoEnabled = preferences.getBoolean( getString(R.string.use_external_video_player_key), false); - boolean isExtAudioEnabled = preferences.getBoolean( + final boolean isExtAudioEnabled = preferences.getBoolean( getString(R.string.use_external_audio_player_key), false); PlayQueue playQueue; - String playerChoice = choice.playerChoice; + final String playerChoice = choice.playerChoice; if (info instanceof StreamInfo) { if (playerChoice.equals(backgroundPlayerKey) && isExtAudioEnabled) { diff --git a/app/src/main/java/org/schabi/newpipe/about/AboutActivity.java b/app/src/main/java/org/schabi/newpipe/about/AboutActivity.java index b5be2dde6..3041c3d6c 100644 --- a/app/src/main/java/org/schabi/newpipe/about/AboutActivity.java +++ b/app/src/main/java/org/schabi/newpipe/about/AboutActivity.java @@ -88,7 +88,7 @@ public class AboutActivity extends AppCompatActivity { setContentView(R.layout.activity_about); - Toolbar toolbar = findViewById(R.id.toolbar); + final Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Create the adapter that will return a fragment for each of the three @@ -99,13 +99,13 @@ public class AboutActivity extends AppCompatActivity { mViewPager = findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); - TabLayout tabLayout = findViewById(R.id.tabs); + final TabLayout tabLayout = findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); } @Override public boolean onOptionsItemSelected(final MenuItem item) { - int id = item.getItemId(); + final int id = item.getItemId(); switch (id) { case android.R.id.home: @@ -134,25 +134,25 @@ public class AboutActivity extends AppCompatActivity { @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_about, container, false); - Context context = this.getContext(); + final View rootView = inflater.inflate(R.layout.fragment_about, container, false); + final Context context = this.getContext(); - TextView version = rootView.findViewById(R.id.app_version); + final TextView version = rootView.findViewById(R.id.app_version); version.setText(BuildConfig.VERSION_NAME); - View githubLink = rootView.findViewById(R.id.github_link); + final View githubLink = rootView.findViewById(R.id.github_link); githubLink.setOnClickListener(nv -> openUrlInBrowser(context, context.getString(R.string.github_url))); - View donationLink = rootView.findViewById(R.id.donation_link); + final View donationLink = rootView.findViewById(R.id.donation_link); donationLink.setOnClickListener(v -> openUrlInBrowser(context, context.getString(R.string.donation_url))); - View websiteLink = rootView.findViewById(R.id.website_link); + final View websiteLink = rootView.findViewById(R.id.website_link); websiteLink.setOnClickListener(nv -> openUrlInBrowser(context, context.getString(R.string.website_url))); - View privacyPolicyLink = rootView.findViewById(R.id.privacy_policy_link); + final View privacyPolicyLink = rootView.findViewById(R.id.privacy_policy_link); privacyPolicyLink.setOnClickListener(v -> openUrlInBrowser(context, context.getString(R.string.privacy_policy_url))); diff --git a/app/src/main/java/org/schabi/newpipe/about/LicenseFragment.java b/app/src/main/java/org/schabi/newpipe/about/LicenseFragment.java index bc6310601..404f12602 100644 --- a/app/src/main/java/org/schabi/newpipe/about/LicenseFragment.java +++ b/app/src/main/java/org/schabi/newpipe/about/LicenseFragment.java @@ -31,8 +31,8 @@ public class LicenseFragment extends Fragment { if (softwareComponents == null) { throw new NullPointerException("softwareComponents is null"); } - LicenseFragment fragment = new LicenseFragment(); - Bundle bundle = new Bundle(); + final LicenseFragment fragment = new LicenseFragment(); + final Bundle bundle = new Bundle(); bundle.putParcelableArray(ARG_COMPONENTS, softwareComponents); fragment.setArguments(bundle); return fragment; diff --git a/app/src/main/java/org/schabi/newpipe/about/LicenseFragmentHelper.java b/app/src/main/java/org/schabi/newpipe/about/LicenseFragmentHelper.java index 1c425567f..01a01bc88 100644 --- a/app/src/main/java/org/schabi/newpipe/about/LicenseFragmentHelper.java +++ b/app/src/main/java/org/schabi/newpipe/about/LicenseFragmentHelper.java @@ -51,7 +51,7 @@ public class LicenseFragmentHelper extends AsyncTask { // split the HTML file and insert the stylesheet into the HEAD of the file webViewData = licenseContent.toString().replace("", ""); - } catch (IOException e) { + } catch (final IOException e) { throw new IllegalArgumentException( "Could not get license file: " + license.getFilename(), e); } diff --git a/app/src/main/java/org/schabi/newpipe/database/Converters.java b/app/src/main/java/org/schabi/newpipe/database/Converters.java index e1a2fe2f3..ca2d8d875 100644 --- a/app/src/main/java/org/schabi/newpipe/database/Converters.java +++ b/app/src/main/java/org/schabi/newpipe/database/Converters.java @@ -49,7 +49,7 @@ public final class Converters { @TypeConverter public static FeedGroupIcon feedGroupIconOf(final Integer id) { - for (FeedGroupIcon icon : FeedGroupIcon.values()) { + for (final FeedGroupIcon icon : FeedGroupIcon.values()) { if (icon.getId() == id) { return icon; } diff --git a/app/src/main/java/org/schabi/newpipe/database/subscription/SubscriptionEntity.java b/app/src/main/java/org/schabi/newpipe/database/subscription/SubscriptionEntity.java index a47f17d13..1cf38dbca 100644 --- a/app/src/main/java/org/schabi/newpipe/database/subscription/SubscriptionEntity.java +++ b/app/src/main/java/org/schabi/newpipe/database/subscription/SubscriptionEntity.java @@ -50,7 +50,7 @@ public class SubscriptionEntity { @Ignore public static SubscriptionEntity from(@NonNull final ChannelInfo info) { - SubscriptionEntity result = new SubscriptionEntity(); + final SubscriptionEntity result = new SubscriptionEntity(); result.setServiceId(info.getServiceId()); result.setUrl(info.getUrl()); result.setData(info.getName(), info.getAvatarUrl(), info.getDescription(), @@ -124,7 +124,7 @@ public class SubscriptionEntity { @Ignore public ChannelInfoItem toChannelInfoItem() { - ChannelInfoItem item = new ChannelInfoItem(getServiceId(), getUrl(), getName()); + final ChannelInfoItem item = new ChannelInfoItem(getServiceId(), getUrl(), getName()); item.setThumbnailUrl(getAvatarUrl()); item.setSubscriberCount(getSubscriberCount()); item.setDescription(getDescription()); diff --git a/app/src/main/java/org/schabi/newpipe/download/DownloadActivity.java b/app/src/main/java/org/schabi/newpipe/download/DownloadActivity.java index 5415c4ff8..bc160d873 100644 --- a/app/src/main/java/org/schabi/newpipe/download/DownloadActivity.java +++ b/app/src/main/java/org/schabi/newpipe/download/DownloadActivity.java @@ -29,7 +29,7 @@ public class DownloadActivity extends AppCompatActivity { @Override protected void onCreate(final Bundle savedInstanceState) { // Service - Intent i = new Intent(); + final Intent i = new Intent(); i.setClass(this, DownloadManagerService.class); startService(i); @@ -38,10 +38,10 @@ public class DownloadActivity extends AppCompatActivity { super.onCreate(savedInstanceState); setContentView(R.layout.activity_downloader); - Toolbar toolbar = findViewById(R.id.toolbar); + final Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); - ActionBar actionBar = getSupportActionBar(); + final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(R.string.downloads_title); @@ -63,7 +63,7 @@ public class DownloadActivity extends AppCompatActivity { } private void updateFragments() { - MissionsFragment fragment = new MissionsFragment(); + final MissionsFragment fragment = new MissionsFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.frame, fragment, MISSIONS_FRAGMENT_TAG) @@ -74,7 +74,7 @@ public class DownloadActivity extends AppCompatActivity { @Override public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); - MenuInflater inflater = getMenuInflater(); + final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.download_menu, menu); diff --git a/app/src/main/java/org/schabi/newpipe/download/DownloadDialog.java b/app/src/main/java/org/schabi/newpipe/download/DownloadDialog.java index cad0258da..15ddaa865 100644 --- a/app/src/main/java/org/schabi/newpipe/download/DownloadDialog.java +++ b/app/src/main/java/org/schabi/newpipe/download/DownloadDialog.java @@ -124,7 +124,7 @@ public class DownloadDialog extends DialogFragment private SharedPreferences prefs; public static DownloadDialog newInstance(final StreamInfo info) { - DownloadDialog dialog = new DownloadDialog(); + final DownloadDialog dialog = new DownloadDialog(); dialog.setInfo(info); return dialog; } @@ -208,14 +208,15 @@ public class DownloadDialog extends DialogFragment setStyle(STYLE_NO_TITLE, ThemeHelper.getDialogTheme(context)); Icepick.restoreInstanceState(this, savedInstanceState); - SparseArray> secondaryStreams = new SparseArray<>(4); - List videoStreams = wrappedVideoStreams.getStreamsList(); + final SparseArray> secondaryStreams + = new SparseArray<>(4); + final List videoStreams = wrappedVideoStreams.getStreamsList(); for (int i = 0; i < videoStreams.size(); i++) { if (!videoStreams.get(i).isVideoOnly()) { continue; } - AudioStream audioStream = SecondaryStreamHelper + final AudioStream audioStream = SecondaryStreamHelper .getAudioStreamFor(wrappedAudioStreams.getStreamsList(), videoStreams.get(i)); if (audioStream != null) { @@ -232,13 +233,13 @@ public class DownloadDialog extends DialogFragment this.audioStreamsAdapter = new StreamItemAdapter<>(context, wrappedAudioStreams); this.subtitleStreamsAdapter = new StreamItemAdapter<>(context, wrappedSubtitleStreams); - Intent intent = new Intent(context, DownloadManagerService.class); + final Intent intent = new Intent(context, DownloadManagerService.class); context.startService(intent); context.bindService(intent, new ServiceConnection() { @Override public void onServiceConnected(final ComponentName cname, final IBinder service) { - DownloadManagerBinder mgr = (DownloadManagerBinder) service; + final DownloadManagerBinder mgr = (DownloadManagerBinder) service; mainStorageAudio = mgr.getMainStorageAudio(); mainStorageVideo = mgr.getMainStorageVideo(); @@ -296,7 +297,7 @@ public class DownloadDialog extends DialogFragment prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); - int threads = prefs.getInt(getString(R.string.default_download_threads), 3); + final int threads = prefs.getInt(getString(R.string.default_download_threads), 3); threadsCountTextView.setText(String.valueOf(threads)); threadsSeekBar.setProgress(threads - 1); threadsSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @@ -373,13 +374,13 @@ public class DownloadDialog extends DialogFragment } if (FilePickerActivityHelper.isOwnFileUri(context, data.getData())) { - File file = Utils.getFileForUri(data.getData()); + final File file = Utils.getFileForUri(data.getData()); checkSelectedDownload(null, Uri.fromFile(file), file.getName(), StoredFileHelper.DEFAULT_MIME); return; } - DocumentFile docFile = DocumentFile.fromSingleUri(context, data.getData()); + final DocumentFile docFile = DocumentFile.fromSingleUri(context, data.getData()); if (docFile == null) { showFailedDialog(R.string.general_error); return; @@ -564,7 +565,7 @@ public class DownloadDialog extends DialogFragment } private String getNameEditText() { - String str = nameEditText.getText().toString().trim(); + final String str = nameEditText.getText().toString().trim(); return FilenameUtils.createFilename(context, str.isEmpty() ? currentInfo.getName() : str); } @@ -591,9 +592,9 @@ public class DownloadDialog extends DialogFragment } private void prepareSelectedDownload() { - StoredDirectoryHelper mainStorage; - MediaFormat format; - String mime; + final StoredDirectoryHelper mainStorage; + final MediaFormat format; + final String mime; // first, build the filename and get the output folder (if possible) // later, run a very very very large file checking logic @@ -683,15 +684,17 @@ public class DownloadDialog extends DialogFragment storage = new StoredFileHelper(context, mainStorage.getUri(), targetFile, mainStorage.getTag()); } - } catch (Exception e) { + } catch (final Exception e) { showErrorActivity(e); return; } // check if is our file - MissionState state = downloadManager.checkForExistingMission(storage); - @StringRes int msgBtn; - @StringRes int msgBody; + final MissionState state = downloadManager.checkForExistingMission(storage); + @StringRes + final int msgBtn; + @StringRes + final int msgBody; switch (state) { case Finished: @@ -744,8 +747,7 @@ public class DownloadDialog extends DialogFragment return; } - - AlertDialog.Builder askDialog = new AlertDialog.Builder(context) + final AlertDialog.Builder askDialog = new AlertDialog.Builder(context) .setTitle(R.string.download_dialog_title) .setMessage(msgBody) .setNegativeButton(android.R.string.cancel, null); @@ -787,7 +789,7 @@ public class DownloadDialog extends DialogFragment // try take (or steal) the file storageNew = new StoredFileHelper(context, mainStorage.getUri(), targetFile, mainStorage.getTag()); - } catch (IOException e) { + } catch (final IOException e) { Log.e(TAG, "Failed to take (or steal) the file in " + targetFile.toString()); storageNew = null; @@ -825,18 +827,18 @@ public class DownloadDialog extends DialogFragment if (storage.length() > 0) { storage.truncate(); } - } catch (IOException e) { + } catch (final IOException e) { Log.e(TAG, "failed to truncate the file: " + storage.getUri().toString(), e); showFailedDialog(R.string.overwrite_failed); return; } - Stream selectedStream; + final Stream selectedStream; Stream secondaryStream = null; - char kind; + final char kind; int threads = threadsSeekBar.getProgress() + 1; - String[] urls; - MissionRecoveryInfo[] recoveryInfo; + final String[] urls; + final MissionRecoveryInfo[] recoveryInfo; String psName = null; String[] psArgs = null; long nearLength = 0; @@ -857,7 +859,7 @@ public class DownloadDialog extends DialogFragment kind = 'v'; selectedStream = videoStreamsAdapter.getItem(selectedVideoIndex); - SecondaryStreamHelper secondary = videoStreamsAdapter + final SecondaryStreamHelper secondary = videoStreamsAdapter .getAllSecondary() .get(wrappedVideoStreams.getStreamsList().indexOf(selectedStream)); @@ -871,7 +873,7 @@ public class DownloadDialog extends DialogFragment } psArgs = null; - long videoSize = wrappedVideoStreams + final long videoSize = wrappedVideoStreams .getSizeInBytes((VideoStream) selectedStream); // set nearLength, only, if both sizes are fetched or known. This probably diff --git a/app/src/main/java/org/schabi/newpipe/fragments/BaseStateFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/BaseStateFragment.java index 255841857..c687c4a6a 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/BaseStateFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/BaseStateFragment.java @@ -230,7 +230,7 @@ public abstract class BaseStateFragment extends BaseFragment implements ViewC } Toast.makeText(activity, R.string.recaptcha_request_toast, Toast.LENGTH_LONG).show(); // Starting ReCaptcha Challenge Activity - Intent intent = new Intent(activity, ReCaptchaActivity.class); + final Intent intent = new Intent(activity, ReCaptchaActivity.class); intent.putExtra(ReCaptchaActivity.RECAPTCHA_URL_EXTRA, exception.getUrl()); startActivityForResult(intent, ReCaptchaActivity.RECAPTCHA_REQUEST); diff --git a/app/src/main/java/org/schabi/newpipe/fragments/MainFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/MainFragment.java index 4a0fb4270..472dc3409 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/MainFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/MainFragment.java @@ -104,7 +104,7 @@ public class MainFragment extends BaseFragment implements TabLayout.OnTabSelecte public void onResume() { super.onResume(); - boolean youtubeRestrictedModeEnabled = + final boolean youtubeRestrictedModeEnabled = PreferenceManager.getDefaultSharedPreferences(getContext()) .getBoolean(youtubeRestrictedModeEnabledKey, false); if (previousYoutubeRestrictedModeEnabled != youtubeRestrictedModeEnabled) { @@ -137,7 +137,7 @@ public class MainFragment extends BaseFragment implements TabLayout.OnTabSelecte } inflater.inflate(R.menu.main_fragment_menu, menu); - ActionBar supportActionBar = activity.getSupportActionBar(); + final ActionBar supportActionBar = activity.getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(false); } @@ -150,7 +150,7 @@ public class MainFragment extends BaseFragment implements TabLayout.OnTabSelecte try { NavigationHelper.openSearchFragment(getFM(), ServiceHelper.getSelectedServiceId(activity), ""); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError((AppCompatActivity) getActivity(), e); } return true; @@ -237,7 +237,7 @@ public class MainFragment extends BaseFragment implements TabLayout.OnTabSelecte Fragment fragment = null; try { fragment = tab.getFragment(context); - } catch (ExtractionException e) { + } catch (final ExtractionException e) { throwable = e; } diff --git a/app/src/main/java/org/schabi/newpipe/fragments/OnScrollBelowItemsListener.java b/app/src/main/java/org/schabi/newpipe/fragments/OnScrollBelowItemsListener.java index 28ce91f55..e93c333cb 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/OnScrollBelowItemsListener.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/OnScrollBelowItemsListener.java @@ -14,9 +14,9 @@ public abstract class OnScrollBelowItemsListener extends RecyclerView.OnScrollLi super.onScrolled(recyclerView, dx, dy); if (dy > 0) { int pastVisibleItems = 0; - int visibleItemCount; - int totalItemCount; - RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); + final int visibleItemCount; + final int totalItemCount; + final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); @@ -26,7 +26,7 @@ public abstract class OnScrollBelowItemsListener extends RecyclerView.OnScrollLi pastVisibleItems = ((LinearLayoutManager) layoutManager) .findFirstVisibleItemPosition(); } else if (layoutManager instanceof StaggeredGridLayoutManager) { - int[] positions = ((StaggeredGridLayoutManager) layoutManager) + final int[] positions = ((StaggeredGridLayoutManager) layoutManager) .findFirstVisibleItemPositions(null); if (positions != null && positions.length > 0) { pastVisibleItems = positions[0]; diff --git a/app/src/main/java/org/schabi/newpipe/fragments/detail/TabAdaptor.java b/app/src/main/java/org/schabi/newpipe/fragments/detail/TabAdaptor.java index 38f013200..74609777c 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/detail/TabAdaptor.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/detail/TabAdaptor.java @@ -50,7 +50,7 @@ public class TabAdaptor extends FragmentPagerAdapter { } public void updateItem(final String title, final Fragment fragment) { - int index = mFragmentTitleList.indexOf(title); + final int index = mFragmentTitleList.indexOf(title); if (index != -1) { updateItem(index, fragment); } diff --git a/app/src/main/java/org/schabi/newpipe/fragments/detail/VideoDetailFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/detail/VideoDetailFragment.java index 66077f3ee..b6f8dd080 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/detail/VideoDetailFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/detail/VideoDetailFragment.java @@ -18,6 +18,12 @@ import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.provider.Settings; +import android.text.Html; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.util.Linkify; +import android.util.DisplayMetrics; +import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; @@ -30,31 +36,25 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; + import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; +import androidx.core.content.ContextCompat; +import androidx.fragment.app.Fragment; +import androidx.viewpager.widget.ViewPager; + import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.exoplayer2.Player; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.tabs.TabLayout; -import androidx.fragment.app.Fragment; -import androidx.core.content.ContextCompat; -import androidx.viewpager.widget.ViewPager; -import android.text.Html; -import android.text.Spanned; -import android.text.TextUtils; -import android.text.util.Linkify; -import android.util.DisplayMetrics; -import android.util.Log; - -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.content.res.AppCompatResources; - import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; @@ -93,8 +93,8 @@ import org.schabi.newpipe.player.playqueue.PlayQueueItem; import org.schabi.newpipe.player.playqueue.SinglePlayQueue; import org.schabi.newpipe.report.ErrorActivity; import org.schabi.newpipe.report.UserAction; -import org.schabi.newpipe.util.DeviceUtils; import org.schabi.newpipe.util.Constants; +import org.schabi.newpipe.util.DeviceUtils; import org.schabi.newpipe.util.ExtractorHelper; import org.schabi.newpipe.util.ImageDisplayConstants; import org.schabi.newpipe.util.InfoCache; @@ -124,9 +124,9 @@ import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import static org.schabi.newpipe.extractor.StreamingService.ServiceInfo.MediaCapability.COMMENTS; +import static org.schabi.newpipe.extractor.stream.StreamExtractor.NO_AGE_LIMIT; import static org.schabi.newpipe.player.helper.PlayerHelper.isClearingQueueConfirmationRequired; import static org.schabi.newpipe.player.playqueue.PlayQueueItem.RECOVERY_UNSET; -import static org.schabi.newpipe.extractor.stream.StreamExtractor.NO_AGE_LIMIT; import static org.schabi.newpipe.util.AnimationUtils.animateView; public class VideoDetailFragment @@ -371,7 +371,7 @@ public class VideoDetailFragment public static VideoDetailFragment getInstance(final int serviceId, final String videoUrl, final String name, final PlayQueue playQueue) { - VideoDetailFragment instance = new VideoDetailFragment(); + final VideoDetailFragment instance = new VideoDetailFragment(); instance.setInitialData(serviceId, videoUrl, name, playQueue); return instance; } @@ -635,7 +635,7 @@ public class VideoDetailFragment try { NavigationHelper.openChannelFragment(getFM(), currentInfo.getServiceId(), subChannelUrl, subChannelName); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError((AppCompatActivity) getActivity(), e); } } @@ -1062,7 +1062,7 @@ public class VideoDetailFragment if (pageAdapter.getCount() < 2) { tabLayout.setVisibility(View.GONE); } else { - int position = pageAdapter.getItemPositionByTitle(selectedTabTag); + final int position = pageAdapter.getItemPositionByTitle(selectedTabTag); if (position != -1) { viewPager.setCurrentItem(position); } @@ -1076,7 +1076,7 @@ public class VideoDetailFragment .getServiceInfo() .getMediaCapabilities() .contains(COMMENTS); - } catch (ExtractionException e) { + } catch (final ExtractionException e) { return false; } } @@ -1304,7 +1304,7 @@ public class VideoDetailFragment if (description.getType() == Description.HTML) { disposables.add(Single.just(description.getContent()) .map((@NonNull String descriptionText) -> { - Spanned parsedDescription; + final Spanned parsedDescription; if (Build.VERSION.SDK_INT >= 24) { parsedDescription = Html.fromHtml(descriptionText, 0); } else { @@ -1409,7 +1409,7 @@ public class VideoDetailFragment } } }; - IntentFilter intentFilter = new IntentFilter(); + final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION_SHOW_MAIN_PLAYER); intentFilter.addAction(ACTION_HIDE_MAIN_PLAYER); activity.registerReceiver(broadcastReceiver, intentFilter); @@ -1512,7 +1512,7 @@ public class VideoDetailFragment uploaderThumb.setVisibility(View.GONE); } - Drawable buddyDrawable = AppCompatResources.getDrawable(activity, R.drawable.buddy); + final Drawable buddyDrawable = AppCompatResources.getDrawable(activity, R.drawable.buddy); subChannelThumb.setImageDrawable(buddyDrawable); uploaderThumb.setImageDrawable(buddyDrawable); @@ -1676,7 +1676,7 @@ public class VideoDetailFragment downloadDialog.setSubtitleStreams(currentInfo.getSubtitles()); downloadDialog.show(activity.getSupportFragmentManager(), "downloadDialog"); - } catch (Exception e) { + } catch (final Exception e) { final ErrorActivity.ErrorInfo info = ErrorActivity.ErrorInfo.make(UserAction.UI_ERROR, ServiceList.all() .get(currentInfo @@ -1702,7 +1702,7 @@ public class VideoDetailFragment return true; } - int errorId = exception instanceof YoutubeStreamExtractor.DecryptException + final int errorId = exception instanceof YoutubeStreamExtractor.DecryptException ? R.string.youtube_signature_decryption_error : exception instanceof ExtractionException ? R.string.parsing_error @@ -2112,11 +2112,11 @@ public class VideoDetailFragment if (sortedVideoStreams == null) { return; } - CharSequence[] resolutions = new CharSequence[sortedVideoStreams.size()]; + final CharSequence[] resolutions = new CharSequence[sortedVideoStreams.size()]; for (int i = 0; i < sortedVideoStreams.size(); i++) { resolutions[i] = sortedVideoStreams.get(i).getResolution(); } - AlertDialog.Builder builder = new AlertDialog.Builder(activity) + final AlertDialog.Builder builder = new AlertDialog.Builder(activity) .setNegativeButton(android.R.string.cancel, null) .setNeutralButton(R.string.open_in_browser, (dialog, i) -> ShareUtils.openUrlInBrowser(requireActivity(), url) diff --git a/app/src/main/java/org/schabi/newpipe/fragments/list/BaseListFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/list/BaseListFragment.java index 9ce62a0df..152221c4c 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/list/BaseListFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/list/BaseListFragment.java @@ -136,7 +136,7 @@ public abstract class BaseListFragment extends BaseStateFragment final RecyclerView.ViewHolder itemHolder = itemsList.findContainingViewHolder(focusedItem); return itemHolder.getAdapterPosition(); - } catch (NullPointerException e) { + } catch (final NullPointerException e) { return -1; } } @@ -169,7 +169,7 @@ public abstract class BaseListFragment extends BaseStateFragment } itemsList.post(() -> { - RecyclerView.ViewHolder focusedHolder = + final RecyclerView.ViewHolder focusedHolder = itemsList.findViewHolderForAdapterPosition(position); if (focusedHolder != null) { @@ -279,7 +279,7 @@ public abstract class BaseListFragment extends BaseStateFragment selectedItem.getServiceId(), selectedItem.getUrl(), selectedItem.getName()); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError((AppCompatActivity) getActivity(), e); } } @@ -294,7 +294,7 @@ public abstract class BaseListFragment extends BaseStateFragment selectedItem.getServiceId(), selectedItem.getUrl(), selectedItem.getName()); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError((AppCompatActivity) getActivity(), e); } } @@ -367,7 +367,7 @@ public abstract class BaseListFragment extends BaseStateFragment + "menu = [" + menu + "], inflater = [" + inflater + "]"); } super.onCreateOptionsMenu(menu, inflater); - ActionBar supportActionBar = activity.getSupportActionBar(); + final ActionBar supportActionBar = activity.getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayShowTitleEnabled(true); if (useAsFrontPage) { diff --git a/app/src/main/java/org/schabi/newpipe/fragments/list/channel/ChannelFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/list/channel/ChannelFragment.java index abcf164f9..8902834e4 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/list/channel/ChannelFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/list/channel/ChannelFragment.java @@ -98,7 +98,7 @@ public class ChannelFragment extends BaseListInfoFragment public static ChannelFragment getInstance(final int serviceId, final String url, final String name) { - ChannelFragment instance = new ChannelFragment(); + final ChannelFragment instance = new ChannelFragment(); instance.setInitialData(serviceId, url, name); return instance; } @@ -189,7 +189,7 @@ public class ChannelFragment extends BaseListInfoFragment @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); - ActionBar supportActionBar = activity.getSupportActionBar(); + final ActionBar supportActionBar = activity.getSupportActionBar(); if (useAsFrontPage && supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(false); } else { @@ -206,7 +206,7 @@ public class ChannelFragment extends BaseListInfoFragment private void openRssFeed() { final ChannelInfo info = currentInfo; if (info != null) { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(info.getFeedUrl())); + final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(info.getFeedUrl())); startActivity(intent); } } @@ -345,7 +345,7 @@ public class ChannelFragment extends BaseListInfoFragment if (DEBUG) { Log.d(TAG, "No subscription to this channel!"); } - SubscriptionEntity channel = new SubscriptionEntity(); + final SubscriptionEntity channel = new SubscriptionEntity(); channel.setServiceId(info.getServiceId()); channel.setUrl(info.getUrl()); channel.setData(info.getName(), @@ -371,16 +371,16 @@ public class ChannelFragment extends BaseListInfoFragment + "isSubscribed = [" + isSubscribed + "]"); } - boolean isButtonVisible = headerSubscribeButton.getVisibility() == View.VISIBLE; - int backgroundDuration = isButtonVisible ? 300 : 0; - int textDuration = isButtonVisible ? 200 : 0; + final boolean isButtonVisible = headerSubscribeButton.getVisibility() == View.VISIBLE; + final int backgroundDuration = isButtonVisible ? 300 : 0; + final int textDuration = isButtonVisible ? 200 : 0; - int subscribeBackground = ThemeHelper + final int subscribeBackground = ThemeHelper .resolveColorFromAttr(activity, R.attr.colorPrimary); - int subscribeText = ContextCompat.getColor(activity, R.color.subscribe_text_color); - int subscribedBackground = ContextCompat + final int subscribeText = ContextCompat.getColor(activity, R.color.subscribe_text_color); + final int subscribedBackground = ContextCompat .getColor(activity, R.color.subscribed_background_color); - int subscribedText = ContextCompat.getColor(activity, R.color.subscribed_text_color); + final int subscribedText = ContextCompat.getColor(activity, R.color.subscribed_text_color); if (!isSubscribed) { headerSubscribeButton.setText(R.string.subscribe_button_title); @@ -429,7 +429,7 @@ public class ChannelFragment extends BaseListInfoFragment NavigationHelper.openChannelFragment(getFM(), currentInfo.getServiceId(), currentInfo.getParentChannelUrl(), currentInfo.getParentChannelName()); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError((AppCompatActivity) getActivity(), e); } } else if (DEBUG) { @@ -490,13 +490,13 @@ public class ChannelFragment extends BaseListInfoFragment playlistCtrl.setVisibility(View.VISIBLE); - List errors = new ArrayList<>(result.getErrors()); + final List errors = new ArrayList<>(result.getErrors()); if (!errors.isEmpty()) { // handling ContentNotSupportedException not to show the error but an appropriate string // so that crashes won't be sent uselessly and the user will understand what happened for (Iterator it = errors.iterator(); it.hasNext();) { - Throwable throwable = it.next(); + final Throwable throwable = it.next(); if (throwable instanceof ContentNotSupportedException) { showContentNotSupported(); it.remove(); @@ -549,7 +549,7 @@ public class ChannelFragment extends BaseListInfoFragment private PlayQueue getPlayQueue(final int index) { final List streamItems = new ArrayList<>(); - for (InfoItem i : infoListAdapter.getItemsList()) { + for (final InfoItem i : infoListAdapter.getItemsList()) { if (i instanceof StreamInfoItem) { streamItems.add((StreamInfoItem) i); } @@ -581,7 +581,7 @@ public class ChannelFragment extends BaseListInfoFragment return true; } - int errorId = exception instanceof ExtractionException + final int errorId = exception instanceof ExtractionException ? R.string.parsing_error : R.string.general_error; onUnrecoverableError(exception, UserAction.REQUESTED_CHANNEL, diff --git a/app/src/main/java/org/schabi/newpipe/fragments/list/comments/CommentsFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/list/comments/CommentsFragment.java index c8e18f610..ff02dd790 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/list/comments/CommentsFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/list/comments/CommentsFragment.java @@ -30,7 +30,7 @@ public class CommentsFragment extends BaseListInfoFragment { public static CommentsFragment getInstance(final int serviceId, final String url, final String name) { - CommentsFragment instance = new CommentsFragment(); + final CommentsFragment instance = new CommentsFragment(); instance.setInitialData(serviceId, url, name); return instance; } diff --git a/app/src/main/java/org/schabi/newpipe/fragments/list/kiosk/DefaultKioskFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/list/kiosk/DefaultKioskFragment.java index 4b758a9c0..1797191b6 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/list/kiosk/DefaultKioskFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/list/kiosk/DefaultKioskFragment.java @@ -45,7 +45,7 @@ public class DefaultKioskFragment extends KioskFragment { currentInfo = null; currentNextPage = null; - } catch (ExtractionException e) { + } catch (final ExtractionException e) { onUnrecoverableError(e, UserAction.REQUESTED_KIOSK, "none", "Loading default kiosk from selected service", 0); } diff --git a/app/src/main/java/org/schabi/newpipe/fragments/list/kiosk/KioskFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/list/kiosk/KioskFragment.java index a9dc59951..68097e21e 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/list/kiosk/KioskFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/list/kiosk/KioskFragment.java @@ -72,9 +72,9 @@ public class KioskFragment extends BaseListInfoFragment { public static KioskFragment getInstance(final int serviceId, final String kioskId) throws ExtractionException { - KioskFragment instance = new KioskFragment(); - StreamingService service = NewPipe.getService(serviceId); - ListLinkHandlerFactory kioskLinkHandlerFactory = service.getKioskList() + final KioskFragment instance = new KioskFragment(); + final StreamingService service = NewPipe.getService(serviceId); + final ListLinkHandlerFactory kioskLinkHandlerFactory = service.getKioskList() .getListLinkHandlerFactoryByType(kioskId); instance.setInitialData(serviceId, kioskLinkHandlerFactory.fromId(kioskId).getUrl(), kioskId); @@ -101,7 +101,7 @@ public class KioskFragment extends BaseListInfoFragment { if (useAsFrontPage && isVisibleToUser && activity != null) { try { setTitle(kioskTranslatedName); - } catch (Exception e) { + } catch (final Exception e) { onUnrecoverableError(e, UserAction.UI_ERROR, "none", "none", R.string.app_ui_crash); @@ -132,7 +132,7 @@ public class KioskFragment extends BaseListInfoFragment { @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); - ActionBar supportActionBar = activity.getSupportActionBar(); + final ActionBar supportActionBar = activity.getSupportActionBar(); if (supportActionBar != null && useAsFrontPage) { supportActionBar.setDisplayHomeAsUpEnabled(false); } diff --git a/app/src/main/java/org/schabi/newpipe/fragments/list/playlist/PlaylistFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/list/playlist/PlaylistFragment.java index ebce3c39e..38594553b 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/list/playlist/PlaylistFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/list/playlist/PlaylistFragment.java @@ -85,7 +85,7 @@ public class PlaylistFragment extends BaseListInfoFragment { public static PlaylistFragment getInstance(final int serviceId, final String url, final String name) { - PlaylistFragment instance = new PlaylistFragment(); + final PlaylistFragment instance = new PlaylistFragment(); instance.setInitialData(serviceId, url, name); return instance; } @@ -288,7 +288,7 @@ public class PlaylistFragment extends BaseListInfoFragment { try { NavigationHelper.openChannelFragment(getFM(), result.getServiceId(), result.getUploaderUrl(), result.getUploaderName()); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError((AppCompatActivity) getActivity(), e); } }); @@ -339,7 +339,7 @@ public class PlaylistFragment extends BaseListInfoFragment { private PlayQueue getPlayQueue(final int index) { final List infoItems = new ArrayList<>(); - for (InfoItem i : infoListAdapter.getItemsList()) { + for (final InfoItem i : infoListAdapter.getItemsList()) { if (i instanceof StreamInfoItem) { infoItems.add((StreamInfoItem) i); } @@ -373,7 +373,7 @@ public class PlaylistFragment extends BaseListInfoFragment { return true; } - int errorId = exception instanceof ExtractionException + final int errorId = exception instanceof ExtractionException ? R.string.parsing_error : R.string.general_error; onUnrecoverableError(exception, UserAction.REQUESTED_PLAYLIST, NewPipe.getNameOfService(serviceId), url, errorId); diff --git a/app/src/main/java/org/schabi/newpipe/fragments/list/search/SearchFragment.java b/app/src/main/java/org/schabi/newpipe/fragments/list/search/SearchFragment.java index 41bce51ea..44cdb8164 100644 --- a/app/src/main/java/org/schabi/newpipe/fragments/list/search/SearchFragment.java +++ b/app/src/main/java/org/schabi/newpipe/fragments/list/search/SearchFragment.java @@ -161,7 +161,7 @@ public class SearchFragment extends BaseListFragment cf = new ArrayList<>(1); + final List cf = new ArrayList<>(1); cf.add(menuItemToFilterName.get(item.getItemId())); changeContentFilter(item, cf); @@ -458,7 +460,7 @@ public class SearchFragment extends BaseListFragment> local = flowable.toObservable() .map(searchHistoryEntries -> { - List result = new ArrayList<>(); - for (SearchHistoryEntry entry : searchHistoryEntries) { + final List result = new ArrayList<>(); + for (final SearchHistoryEntry entry : searchHistoryEntries) { result.add(new SuggestionItem(true, entry.getSearch())); } return result; @@ -742,15 +744,15 @@ public class SearchFragment extends BaseListFragment { - List result = new ArrayList<>(); - for (String entry : strings) { + final List result = new ArrayList<>(); + for (final String entry : strings) { result.add(new SuggestionItem(false, entry)); } return result; }); return Observable.zip(local, network, (localResult, networkResult) -> { - List result = new ArrayList<>(); + final List result = new ArrayList<>(); if (localResult.size() > 0) { result.addAll(localResult); } @@ -759,7 +761,7 @@ public class SearchFragment extends BaseListFragment iterator = networkResult.iterator(); while (iterator.hasNext() && localResult.size() > 0) { final SuggestionItem next = iterator.next(); - for (SuggestionItem item : localResult) { + for (final SuggestionItem item : localResult) { if (item.query.equals(next.query)) { iterator.remove(); break; @@ -813,7 +815,7 @@ public class SearchFragment extends BaseListFragment payloads) { if (!payloads.isEmpty() && holder instanceof InfoItemHolder) { - for (Object payload : payloads) { + for (final Object payload : payloads) { if (payload instanceof StreamStateEntity) { ((InfoItemHolder) holder).updateState(infoItemList .get(header == null ? position : position - 1), recordManager); diff --git a/app/src/main/java/org/schabi/newpipe/info_list/holder/ChannelInfoItemHolder.java b/app/src/main/java/org/schabi/newpipe/info_list/holder/ChannelInfoItemHolder.java index 28d447337..cf1ed255b 100644 --- a/app/src/main/java/org/schabi/newpipe/info_list/holder/ChannelInfoItemHolder.java +++ b/app/src/main/java/org/schabi/newpipe/info_list/holder/ChannelInfoItemHolder.java @@ -56,8 +56,8 @@ public class ChannelInfoItemHolder extends ChannelMiniInfoItemHolder { String details = super.getDetailLine(item); if (item.getStreamCount() >= 0) { - String formattedVideoAmount = Localization.localizeStreamCount(itemBuilder.getContext(), - item.getStreamCount()); + final String formattedVideoAmount = Localization.localizeStreamCount( + itemBuilder.getContext(), item.getStreamCount()); if (!details.isEmpty()) { details += " • " + formattedVideoAmount; diff --git a/app/src/main/java/org/schabi/newpipe/info_list/holder/CommentsMiniInfoItemHolder.java b/app/src/main/java/org/schabi/newpipe/info_list/holder/CommentsMiniInfoItemHolder.java index 613ff4b6f..944b578f5 100644 --- a/app/src/main/java/org/schabi/newpipe/info_list/holder/CommentsMiniInfoItemHolder.java +++ b/app/src/main/java/org/schabi/newpipe/info_list/holder/CommentsMiniInfoItemHolder.java @@ -45,9 +45,9 @@ public class CommentsMiniInfoItemHolder extends InfoItemHolder { @Override public String transformUrl(final Matcher match, final String url) { int timestamp = 0; - String hours = match.group(1); - String minutes = match.group(2); - String seconds = match.group(3); + final String hours = match.group(1); + final String minutes = match.group(2); + final String seconds = match.group(3); if (hours != null) { timestamp += (Integer.parseInt(hours.replace(":", "")) * 3600); } @@ -146,7 +146,7 @@ public class CommentsMiniInfoItemHolder extends InfoItemHolder { item.getServiceId(), item.getUploaderUrl(), item.getUploaderName()); - } catch (Exception e) { + } catch (final Exception e) { ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e); } } @@ -164,7 +164,7 @@ public class CommentsMiniInfoItemHolder extends InfoItemHolder { return false; } - URLSpan[] urls = itemContentView.getUrls(); + final URLSpan[] urls = itemContentView.getUrls(); return urls != null && urls.length != 0; } @@ -181,12 +181,13 @@ public class CommentsMiniInfoItemHolder extends InfoItemHolder { boolean hasEllipsis = false; if (itemContentView.getLineCount() > COMMENT_DEFAULT_LINES) { - int endOfLastLine = itemContentView.getLayout().getLineEnd(COMMENT_DEFAULT_LINES - 1); + final int endOfLastLine + = itemContentView.getLayout().getLineEnd(COMMENT_DEFAULT_LINES - 1); int end = itemContentView.getText().toString().lastIndexOf(' ', endOfLastLine - 2); if (end == -1) { end = Math.max(endOfLastLine - 2, 0); } - String newVal = itemContentView.getText().subSequence(0, end) + " …"; + final String newVal = itemContentView.getText().subSequence(0, end) + " …"; itemContentView.setText(newVal); hasEllipsis = true; } diff --git a/app/src/main/java/org/schabi/newpipe/info_list/holder/StreamMiniInfoItemHolder.java b/app/src/main/java/org/schabi/newpipe/info_list/holder/StreamMiniInfoItemHolder.java index da6c9e82f..c0096ed10 100644 --- a/app/src/main/java/org/schabi/newpipe/info_list/holder/StreamMiniInfoItemHolder.java +++ b/app/src/main/java/org/schabi/newpipe/info_list/holder/StreamMiniInfoItemHolder.java @@ -60,7 +60,7 @@ public class StreamMiniInfoItemHolder extends InfoItemHolder { R.color.duration_background_color)); itemDurationView.setVisibility(View.VISIBLE); - StreamStateEntity state2 = historyRecordManager.loadStreamState(infoItem) + final StreamStateEntity state2 = historyRecordManager.loadStreamState(infoItem) .blockingGet()[0]; if (state2 != null) { itemProgressView.setVisibility(View.VISIBLE); @@ -113,7 +113,8 @@ public class StreamMiniInfoItemHolder extends InfoItemHolder { final HistoryRecordManager historyRecordManager) { final StreamInfoItem item = (StreamInfoItem) infoItem; - StreamStateEntity state = historyRecordManager.loadStreamState(infoItem).blockingGet()[0]; + final StreamStateEntity state + = historyRecordManager.loadStreamState(infoItem).blockingGet()[0]; if (state != null && item.getDuration() > 0 && item.getStreamType() != StreamType.LIVE_STREAM) { itemProgressView.setMax((int) item.getDuration()); diff --git a/app/src/main/java/org/schabi/newpipe/local/LocalItemListAdapter.java b/app/src/main/java/org/schabi/newpipe/local/LocalItemListAdapter.java index ad0524f92..5b67f51da 100644 --- a/app/src/main/java/org/schabi/newpipe/local/LocalItemListAdapter.java +++ b/app/src/main/java/org/schabi/newpipe/local/LocalItemListAdapter.java @@ -101,7 +101,7 @@ public class LocalItemListAdapter extends RecyclerView.Adapter items, final OutputStream out, @Nullable final ImportExportEventListener eventListener) { - JsonAppendableWriter writer = JsonWriter.on(out); + final JsonAppendableWriter writer = JsonWriter.on(out); writeTo(items, writer, eventListener); writer.done(); } @@ -140,7 +140,7 @@ public final class ImportExportJsonHelper { writer.value(JSON_APP_VERSION_INT_KEY, BuildConfig.VERSION_CODE); writer.array(JSON_SUBSCRIPTIONS_ARRAY_KEY); - for (SubscriptionItem item : items) { + for (final SubscriptionItem item : items) { writer.object(); writer.value(JSON_SERVICE_ID_KEY, item.getServiceId()); writer.value(JSON_URL_KEY, item.getUrl()); diff --git a/app/src/main/java/org/schabi/newpipe/local/subscription/services/SubscriptionsExportService.java b/app/src/main/java/org/schabi/newpipe/local/subscription/services/SubscriptionsExportService.java index 12b64d89d..f7d099712 100644 --- a/app/src/main/java/org/schabi/newpipe/local/subscription/services/SubscriptionsExportService.java +++ b/app/src/main/java/org/schabi/newpipe/local/subscription/services/SubscriptionsExportService.java @@ -74,7 +74,7 @@ public class SubscriptionsExportService extends BaseImportExportService { try { outFile = new File(path); outputStream = new FileOutputStream(outFile); - } catch (FileNotFoundException e) { + } catch (final FileNotFoundException e) { handleError(e); return START_NOT_STICKY; } @@ -109,7 +109,7 @@ public class SubscriptionsExportService extends BaseImportExportService { .map(subscriptionEntities -> { final List result = new ArrayList<>(subscriptionEntities.size()); - for (SubscriptionEntity entity : subscriptionEntities) { + for (final SubscriptionEntity entity : subscriptionEntities) { result.add(new SubscriptionItem(entity.getServiceId(), entity.getUrl(), entity.getName())); } diff --git a/app/src/main/java/org/schabi/newpipe/local/subscription/services/SubscriptionsImportService.java b/app/src/main/java/org/schabi/newpipe/local/subscription/services/SubscriptionsImportService.java index 06ba55106..51afc9fda 100644 --- a/app/src/main/java/org/schabi/newpipe/local/subscription/services/SubscriptionsImportService.java +++ b/app/src/main/java/org/schabi/newpipe/local/subscription/services/SubscriptionsImportService.java @@ -110,7 +110,7 @@ public class SubscriptionsImportService extends BaseImportExportService { try { inputStream = new FileInputStream(new File(filePath)); - } catch (FileNotFoundException e) { + } catch (final FileNotFoundException e) { handleError(e); return START_NOT_STICKY; } @@ -187,7 +187,7 @@ public class SubscriptionsImportService extends BaseImportExportService { .getChannelInfo(subscriptionItem.getServiceId(), subscriptionItem.getUrl(), true) .blockingGet()); - } catch (Throwable e) { + } catch (final Throwable e) { return Notification.createOnError(e); } }) @@ -239,7 +239,7 @@ public class SubscriptionsImportService extends BaseImportExportService { private Consumer> getNotificationsConsumer() { return notification -> { if (notification.isOnNext()) { - String name = notification.getValue().getName(); + final String name = notification.getValue().getName(); eventListener.onItemCompleted(!TextUtils.isEmpty(name) ? name : ""); } else if (notification.isOnError()) { final Throwable error = notification.getError(); @@ -260,7 +260,7 @@ public class SubscriptionsImportService extends BaseImportExportService { private Function>, List> upsertBatch() { return notificationList -> { final List infoList = new ArrayList<>(notificationList.size()); - for (Notification n : notificationList) { + for (final Notification n : notificationList) { if (n.isOnNext()) { infoList.add(n.getValue()); } diff --git a/app/src/main/java/org/schabi/newpipe/player/BasePlayer.java b/app/src/main/java/org/schabi/newpipe/player/BasePlayer.java index 1a8c98fd2..f8bf45fcf 100644 --- a/app/src/main/java/org/schabi/newpipe/player/BasePlayer.java +++ b/app/src/main/java/org/schabi/newpipe/player/BasePlayer.java @@ -54,7 +54,6 @@ import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; -import io.reactivex.android.schedulers.AndroidSchedulers; import org.schabi.newpipe.BuildConfig; import org.schabi.newpipe.DownloaderImpl; import org.schabi.newpipe.R; @@ -79,6 +78,7 @@ import org.schabi.newpipe.util.SerializedCache; import java.io.IOException; import io.reactivex.Observable; +import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.SerialDisposable; @@ -280,7 +280,7 @@ public abstract class BasePlayer implements // Resolve append intents if (intent.getBooleanExtra(APPEND_ONLY, false) && playQueue != null) { - int sizeBeforeAppend = playQueue.size(); + final int sizeBeforeAppend = playQueue.size(); playQueue.append(queue.getStreams()); if ((intent.getBooleanExtra(SELECT_ON_APPEND, false) @@ -1460,7 +1460,7 @@ public abstract class BasePlayer implements return false; } - Timeline.Window timelineWindow = new Timeline.Window(); + final Timeline.Window timelineWindow = new Timeline.Window(); currentTimeline.getWindow(currentWindowIndex, timelineWindow); return timelineWindow.getDefaultPositionMs() <= simpleExoPlayer.getCurrentPosition(); } @@ -1471,7 +1471,7 @@ public abstract class BasePlayer implements } try { return simpleExoPlayer.isCurrentWindowDynamic(); - } catch (@NonNull IndexOutOfBoundsException e) { + } catch (@NonNull final IndexOutOfBoundsException e) { // Why would this even happen =( // But lets log it anyway. Save is save if (DEBUG) { diff --git a/app/src/main/java/org/schabi/newpipe/player/ServicePlayerActivity.java b/app/src/main/java/org/schabi/newpipe/player/ServicePlayerActivity.java index 3043a7fc3..0ffd7f594 100644 --- a/app/src/main/java/org/schabi/newpipe/player/ServicePlayerActivity.java +++ b/app/src/main/java/org/schabi/newpipe/player/ServicePlayerActivity.java @@ -580,7 +580,7 @@ public abstract class ServicePlayerActivity extends AppCompatActivity //////////////////////////////////////////////////////////////////////////// private void shareUrl(final String subject, final String url) { - Intent intent = new Intent(Intent.ACTION_SEND); + final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, url); @@ -734,7 +734,7 @@ public abstract class ServicePlayerActivity extends AppCompatActivity private void onMaybeMuteChanged() { if (menu != null && player != null) { - MenuItem item = menu.findItem(R.id.action_mute); + final MenuItem item = menu.findItem(R.id.action_mute); //Change the mute-button item in ActionBar //1) Text change: diff --git a/app/src/main/java/org/schabi/newpipe/player/VideoPlayer.java b/app/src/main/java/org/schabi/newpipe/player/VideoPlayer.java index e621f9f33..241640389 100644 --- a/app/src/main/java/org/schabi/newpipe/player/VideoPlayer.java +++ b/app/src/main/java/org/schabi/newpipe/player/VideoPlayer.java @@ -167,7 +167,7 @@ public abstract class VideoPlayer extends BasePlayer // workaround to match normalized captions like english to English or deutsch to Deutsch private static boolean containsCaseInsensitive(final List list, final String toFind) { - for (String i : list) { + for (final String i : list) { if (i.equalsIgnoreCase(toFind)) { return true; } @@ -279,7 +279,7 @@ public abstract class VideoPlayer extends BasePlayer qualityPopupMenu.getMenu().removeGroup(qualityPopupMenuGroupId); for (int i = 0; i < availableStreams.size(); i++) { - VideoStream videoStream = availableStreams.get(i); + final VideoStream videoStream = availableStreams.get(i); qualityPopupMenu.getMenu().add(qualityPopupMenuGroupId, i, Menu.NONE, MediaFormat .getNameById(videoStream.getFormatId()) + " " + videoStream.resolution); } @@ -311,7 +311,7 @@ public abstract class VideoPlayer extends BasePlayer } captionPopupMenu.getMenu().removeGroup(captionPopupMenuGroupId); - String userPreferredLanguage = PreferenceManager.getDefaultSharedPreferences(context) + final String userPreferredLanguage = PreferenceManager.getDefaultSharedPreferences(context) .getString(context.getString(R.string.caption_user_set_key), null); /* * only search for autogenerated cc as fallback @@ -323,7 +323,7 @@ public abstract class VideoPlayer extends BasePlayer && !userPreferredLanguage.contains("("); // Add option for turning off caption - MenuItem captionOffItem = captionPopupMenu.getMenu().add(captionPopupMenuGroupId, + final MenuItem captionOffItem = captionPopupMenu.getMenu().add(captionPopupMenuGroupId, 0, Menu.NONE, R.string.caption_none); captionOffItem.setOnMenuItemClickListener(menuItem -> { final int textRendererIndex = getRendererIndex(C.TRACK_TYPE_TEXT); @@ -339,7 +339,7 @@ public abstract class VideoPlayer extends BasePlayer // Add all available captions for (int i = 0; i < availableLanguages.size(); i++) { final String captionLanguage = availableLanguages.get(i); - MenuItem captionItem = captionPopupMenu.getMenu().add(captionPopupMenuGroupId, + final MenuItem captionItem = captionPopupMenu.getMenu().add(captionPopupMenuGroupId, i + 1, Menu.NONE, captionLanguage); captionItem.setOnMenuItemClickListener(menuItem -> { final int textRendererIndex = getRendererIndex(C.TRACK_TYPE_TEXT); @@ -579,7 +579,7 @@ public abstract class VideoPlayer extends BasePlayer .getTrackGroups(textRenderer); // Extract all loaded languages - List availableLanguages = new ArrayList<>(textTracks.length); + final List availableLanguages = new ArrayList<>(textTracks.length); for (int i = 0; i < textTracks.length; i++) { final TrackGroup textTrack = textTracks.get(i); if (textTrack.length > 0 && textTrack.getFormat(0) != null) { @@ -729,8 +729,8 @@ public abstract class VideoPlayer extends BasePlayer qualityTextView.setText(menuItem.getTitle()); return true; } else if (playbackSpeedPopupMenuGroupId == menuItem.getGroupId()) { - int speedIndex = menuItem.getItemId(); - float speed = PLAYBACK_SPEEDS[speedIndex]; + final int speedIndex = menuItem.getItemId(); + final float speed = PLAYBACK_SPEEDS[speedIndex]; setPlaybackSpeed(speed); playbackSpeedTextView.setText(formatSpeed(speed)); @@ -921,10 +921,10 @@ public abstract class VideoPlayer extends BasePlayer return; } - float scaleFrom = goneOnEnd ? 1f : 1f; - float scaleTo = goneOnEnd ? 1.8f : 1.4f; - float alphaFrom = goneOnEnd ? 1f : 0f; - float alphaTo = goneOnEnd ? 0f : 1f; + final float scaleFrom = goneOnEnd ? 1f : 1f; + final float scaleTo = goneOnEnd ? 1.8f : 1.4f; + final float alphaFrom = goneOnEnd ? 1f : 0f; + final float alphaTo = goneOnEnd ? 0f : 1f; controlViewAnimator = ObjectAnimator.ofPropertyValuesHolder(controlAnimationView, diff --git a/app/src/main/java/org/schabi/newpipe/player/VideoPlayerImpl.java b/app/src/main/java/org/schabi/newpipe/player/VideoPlayerImpl.java index 44bdc1108..2b651fc38 100644 --- a/app/src/main/java/org/schabi/newpipe/player/VideoPlayerImpl.java +++ b/app/src/main/java/org/schabi/newpipe/player/VideoPlayerImpl.java @@ -320,7 +320,7 @@ public class VideoPlayerImpl extends VideoPlayer final float captionScale, @NonNull final CaptionStyleCompat captionStyle) { if (popupPlayerSelected()) { - float captionRatio = (captionScale - 1.0f) / 5.0f + 1.0f; + final float captionRatio = (captionScale - 1.0f) / 5.0f + 1.0f; view.setFractionalTextSize(SubtitleView.DEFAULT_TEXT_SIZE_FRACTION * captionRatio); view.setApplyEmbeddedStyles(captionStyle.equals(CaptionStyleCompat.DEFAULT)); view.setStyle(captionStyle); @@ -717,7 +717,7 @@ public class VideoPlayerImpl extends VideoPlayer if (popupPlayerSelected()) { setRecovery(); service.removeViewFromParent(); - Intent intent = NavigationHelper.getPlayerIntent( + final Intent intent = NavigationHelper.getPlayerIntent( service, MainActivity.class, this.getPlayQueue(), @@ -894,7 +894,7 @@ public class VideoPlayerImpl extends VideoPlayer onPause(); try { NavigationHelper.playWithKore(getParentActivity(), Uri.parse(getVideoUrl())); - } catch (Exception e) { + } catch (final Exception e) { if (DEBUG) { Log.i(TAG, "Failed to start kore", e); } @@ -979,9 +979,9 @@ public class VideoPlayerImpl extends VideoPlayer if (l != ol || t != ot || r != or || b != ob) { // Use smaller value to be consistent between screen orientations // (and to make usage easier) - int width = r - l; - int height = b - t; - int min = Math.min(width, height); + final int width = r - l; + final int height = b - t; + final int min = Math.min(width, height); maxGestureLength = (int) (min * MAX_GESTURE_LENGTH); if (DEBUG) { @@ -995,7 +995,7 @@ public class VideoPlayerImpl extends VideoPlayer queueLayout.getLayoutParams().height = height - queueLayout.getTop(); if (popupPlayerSelected()) { - float widthDp = Math.abs(r - l) / service.getResources() + final float widthDp = Math.abs(r - l) / service.getResources() .getDisplayMetrics().density; final int visibility = widthDp > MINIMUM_SHOW_EXTRA_WIDTH_DP ? View.VISIBLE diff --git a/app/src/main/java/org/schabi/newpipe/player/event/PlayerGestureListener.java b/app/src/main/java/org/schabi/newpipe/player/event/PlayerGestureListener.java index e37a3a930..5ee8485cf 100644 --- a/app/src/main/java/org/schabi/newpipe/player/event/PlayerGestureListener.java +++ b/app/src/main/java/org/schabi/newpipe/player/event/PlayerGestureListener.java @@ -227,8 +227,8 @@ public class PlayerGestureListener isMovingInMain = true; - boolean acceptAnyArea = isVolumeGestureEnabled != isBrightnessGestureEnabled; - boolean acceptVolumeArea = acceptAnyArea + final boolean acceptAnyArea = isVolumeGestureEnabled != isBrightnessGestureEnabled; + final boolean acceptVolumeArea = acceptAnyArea || initialEvent.getX() > playerImpl.getRootView().getWidth() / 2.0; if (isVolumeGestureEnabled && acceptVolumeArea) { @@ -563,13 +563,13 @@ public class PlayerGestureListener private boolean handleMultiDrag(final MotionEvent event) { if (initPointerDistance != -1 && event.getPointerCount() == 2) { // get the movements of the fingers - double firstPointerMove = Math.hypot(event.getX(0) - initFirstPointerX, + final double firstPointerMove = Math.hypot(event.getX(0) - initFirstPointerX, event.getY(0) - initFirstPointerY); - double secPointerMove = Math.hypot(event.getX(1) - initSecPointerX, + final double secPointerMove = Math.hypot(event.getX(1) - initSecPointerX, event.getY(1) - initSecPointerY); // minimum threshold beyond which pinch gesture will work - int minimumMove = ViewConfiguration.get(service).getScaledTouchSlop(); + final int minimumMove = ViewConfiguration.get(service).getScaledTouchSlop(); if (Math.max(firstPointerMove, secPointerMove) > minimumMove) { // calculate current distance between the pointers @@ -577,9 +577,9 @@ public class PlayerGestureListener Math.hypot(event.getX(0) - event.getX(1), event.getY(0) - event.getY(1)); - double popupWidth = playerImpl.getPopupWidth(); + final double popupWidth = playerImpl.getPopupWidth(); // change co-ordinates of popup so the center stays at the same position - double newWidth = (popupWidth * currentPointerDistance / initPointerDistance); + final double newWidth = (popupWidth * currentPointerDistance / initPointerDistance); initPointerDistance = currentPointerDistance; playerImpl.getPopupLayoutParams().x += (popupWidth - newWidth) / 2; @@ -601,7 +601,7 @@ public class PlayerGestureListener * */ private int getNavigationBarHeight(final Context context) { - int resId = context.getResources() + final int resId = context.getResources() .getIdentifier("navigation_bar_height", "dimen", "android"); if (resId > 0) { return context.getResources().getDimensionPixelSize(resId); @@ -610,7 +610,7 @@ public class PlayerGestureListener } private int getStatusBarHeight(final Context context) { - int resId = context.getResources() + final int resId = context.getResources() .getIdentifier("status_bar_height", "dimen", "android"); if (resId > 0) { return context.getResources().getDimensionPixelSize(resId); diff --git a/app/src/main/java/org/schabi/newpipe/player/helper/AudioReactor.java b/app/src/main/java/org/schabi/newpipe/player/helper/AudioReactor.java index 4b326ca7d..f434b0621 100644 --- a/app/src/main/java/org/schabi/newpipe/player/helper/AudioReactor.java +++ b/app/src/main/java/org/schabi/newpipe/player/helper/AudioReactor.java @@ -133,7 +133,7 @@ public class AudioReactor implements AudioManager.OnAudioFocusChangeListener, An } private void animateAudio(final float from, final float to) { - ValueAnimator valueAnimator = new ValueAnimator(); + final ValueAnimator valueAnimator = new ValueAnimator(); valueAnimator.setFloatValues(from, to); valueAnimator.setDuration(AudioReactor.DUCK_DURATION); valueAnimator.addListener(new AnimatorListenerAdapter() { diff --git a/app/src/main/java/org/schabi/newpipe/player/helper/CacheFactory.java b/app/src/main/java/org/schabi/newpipe/player/helper/CacheFactory.java index 2ef22f2eb..9703a3588 100644 --- a/app/src/main/java/org/schabi/newpipe/player/helper/CacheFactory.java +++ b/app/src/main/java/org/schabi/newpipe/player/helper/CacheFactory.java @@ -80,13 +80,13 @@ import java.io.File; } try { - for (File file : cacheDir.listFiles()) { + for (final File file : cacheDir.listFiles()) { final String filePath = file.getAbsolutePath(); final boolean deleteSuccessful = file.delete(); Log.d(TAG, "tryDeleteCacheFiles: " + filePath + " deleted = " + deleteSuccessful); } - } catch (Exception ignored) { + } catch (final Exception ignored) { Log.e(TAG, "Failed to delete file.", ignored); } } diff --git a/app/src/main/java/org/schabi/newpipe/player/helper/LoadController.java b/app/src/main/java/org/schabi/newpipe/player/helper/LoadController.java index 92ae009f6..e164e0563 100644 --- a/app/src/main/java/org/schabi/newpipe/player/helper/LoadController.java +++ b/app/src/main/java/org/schabi/newpipe/player/helper/LoadController.java @@ -29,7 +29,7 @@ public class LoadController implements LoadControl { final int optimalPlaybackBufferMs) { this.initialPlaybackBufferUs = initialPlaybackBufferMs * 1000; - DefaultLoadControl.Builder builder = new DefaultLoadControl.Builder(); + final DefaultLoadControl.Builder builder = new DefaultLoadControl.Builder(); builder.setBufferDurationsMs(minimumPlaybackbufferMs, optimalPlaybackBufferMs, initialPlaybackBufferMs, initialPlaybackBufferMs); internalLoadControl = builder.createDefaultLoadControl(); diff --git a/app/src/main/java/org/schabi/newpipe/player/helper/MediaSessionManager.java b/app/src/main/java/org/schabi/newpipe/player/helper/MediaSessionManager.java index e101e2185..849593e89 100644 --- a/app/src/main/java/org/schabi/newpipe/player/helper/MediaSessionManager.java +++ b/app/src/main/java/org/schabi/newpipe/player/helper/MediaSessionManager.java @@ -62,7 +62,7 @@ public class MediaSessionManager { .build() ); - MediaStyle mediaStyle = new MediaStyle() + final MediaStyle mediaStyle = new MediaStyle() .setMediaSession(mediaSession.getSessionToken()); builder.setStyle(mediaStyle); @@ -76,7 +76,7 @@ public class MediaSessionManager { .build() ); - MediaStyle mediaStyle = new MediaStyle() + final MediaStyle mediaStyle = new MediaStyle() .setMediaSession(mediaSession.getSessionToken()); builder.setStyle(mediaStyle); diff --git a/app/src/main/java/org/schabi/newpipe/player/helper/PlaybackParameterDialog.java b/app/src/main/java/org/schabi/newpipe/player/helper/PlaybackParameterDialog.java index ae547de9f..2b6560534 100644 --- a/app/src/main/java/org/schabi/newpipe/player/helper/PlaybackParameterDialog.java +++ b/app/src/main/java/org/schabi/newpipe/player/helper/PlaybackParameterDialog.java @@ -94,7 +94,7 @@ public class PlaybackParameterDialog extends DialogFragment { final double playbackPitch, final boolean playbackSkipSilence, final Callback callback) { - PlaybackParameterDialog dialog = new PlaybackParameterDialog(); + final PlaybackParameterDialog dialog = new PlaybackParameterDialog(); dialog.callback = callback; dialog.initialTempo = playbackTempo; dialog.initialPitch = playbackPitch; @@ -187,8 +187,8 @@ public class PlaybackParameterDialog extends DialogFragment { private void setupTempoControl(@NonNull final View rootView) { tempoSlider = rootView.findViewById(R.id.tempoSeekbar); - TextView tempoMinimumText = rootView.findViewById(R.id.tempoMinimumText); - TextView tempoMaximumText = rootView.findViewById(R.id.tempoMaximumText); + final TextView tempoMinimumText = rootView.findViewById(R.id.tempoMinimumText); + final TextView tempoMaximumText = rootView.findViewById(R.id.tempoMaximumText); tempoCurrentText = rootView.findViewById(R.id.tempoCurrentText); tempoStepUpText = rootView.findViewById(R.id.tempoStepUp); tempoStepDownText = rootView.findViewById(R.id.tempoStepDown); @@ -212,8 +212,8 @@ public class PlaybackParameterDialog extends DialogFragment { private void setupPitchControl(@NonNull final View rootView) { pitchSlider = rootView.findViewById(R.id.pitchSeekbar); - TextView pitchMinimumText = rootView.findViewById(R.id.pitchMinimumText); - TextView pitchMaximumText = rootView.findViewById(R.id.pitchMaximumText); + final TextView pitchMinimumText = rootView.findViewById(R.id.pitchMinimumText); + final TextView pitchMaximumText = rootView.findViewById(R.id.pitchMaximumText); pitchCurrentText = rootView.findViewById(R.id.pitchCurrentText); pitchStepDownText = rootView.findViewById(R.id.pitchStepDown); pitchStepUpText = rootView.findViewById(R.id.pitchStepUp); @@ -269,12 +269,12 @@ public class PlaybackParameterDialog extends DialogFragment { } private void setupStepSizeSelector(@NonNull final View rootView) { - TextView stepSizeOnePercentText = rootView.findViewById(R.id.stepSizeOnePercent); - TextView stepSizeFivePercentText = rootView.findViewById(R.id.stepSizeFivePercent); - TextView stepSizeTenPercentText = rootView.findViewById(R.id.stepSizeTenPercent); - TextView stepSizeTwentyFivePercentText = rootView + final TextView stepSizeOnePercentText = rootView.findViewById(R.id.stepSizeOnePercent); + final TextView stepSizeFivePercentText = rootView.findViewById(R.id.stepSizeFivePercent); + final TextView stepSizeTenPercentText = rootView.findViewById(R.id.stepSizeTenPercent); + final TextView stepSizeTwentyFivePercentText = rootView .findViewById(R.id.stepSizeTwentyFivePercent); - TextView stepSizeOneHundredPercentText = rootView + final TextView stepSizeOneHundredPercentText = rootView .findViewById(R.id.stepSizeOneHundredPercent); if (stepSizeOnePercentText != null) { diff --git a/app/src/main/java/org/schabi/newpipe/player/helper/PlayerHelper.java b/app/src/main/java/org/schabi/newpipe/player/helper/PlayerHelper.java index 0a4dd83ac..09072340b 100644 --- a/app/src/main/java/org/schabi/newpipe/player/helper/PlayerHelper.java +++ b/app/src/main/java/org/schabi/newpipe/player/helper/PlayerHelper.java @@ -76,10 +76,10 @@ public final class PlayerHelper { //////////////////////////////////////////////////////////////////////////// public static String getTimeString(final int milliSeconds) { - int seconds = (milliSeconds % 60000) / 1000; - int minutes = (milliSeconds % 3600000) / 60000; - int hours = (milliSeconds % 86400000) / 3600000; - int days = (milliSeconds % (86400000 * 7)) / 86400000; + final int seconds = (milliSeconds % 60000) / 1000; + final int minutes = (milliSeconds % 3600000) / 60000; + final int hours = (milliSeconds % 86400000) / 3600000; + final int days = (milliSeconds % (86400000 * 7)) / 86400000; STRING_BUILDER.setLength(0); return days > 0 @@ -405,7 +405,7 @@ public final class PlayerHelper { private static void setScreenBrightness(@NonNull final Context context, final float screenBrightness, final long timestamp) { - SharedPreferences.Editor editor = getPreferences(context).edit(); + final SharedPreferences.Editor editor = getPreferences(context).edit(); editor.putFloat(context.getString(R.string.screen_brightness_key), screenBrightness); editor.putLong(context.getString(R.string.screen_brightness_timestamp_key), timestamp); editor.apply(); @@ -413,8 +413,8 @@ public final class PlayerHelper { private static float getScreenBrightness(@NonNull final Context context, final float screenBrightness) { - SharedPreferences sp = getPreferences(context); - long timestamp = sp + final SharedPreferences sp = getPreferences(context); + final long timestamp = sp .getLong(context.getString(R.string.screen_brightness_timestamp_key), 0); // Hypothesis: 4h covers a viewing block, e.g. evening. // External lightning conditions will change in the next @@ -441,7 +441,7 @@ public final class PlayerHelper { private static SinglePlayQueue getAutoQueuedSinglePlayQueue( final StreamInfoItem streamInfoItem) { - SinglePlayQueue singlePlayQueue = new SinglePlayQueue(streamInfoItem); + final SinglePlayQueue singlePlayQueue = new SinglePlayQueue(streamInfoItem); singlePlayQueue.getItem().setAutoQueued(true); return singlePlayQueue; } diff --git a/app/src/main/java/org/schabi/newpipe/player/mediasession/PlayQueueNavigator.java b/app/src/main/java/org/schabi/newpipe/player/mediasession/PlayQueueNavigator.java index 1f1152b62..764c375af 100644 --- a/app/src/main/java/org/schabi/newpipe/player/mediasession/PlayQueueNavigator.java +++ b/app/src/main/java/org/schabi/newpipe/player/mediasession/PlayQueueNavigator.java @@ -87,13 +87,13 @@ public class PlayQueueNavigator implements MediaSessionConnector.QueueNavigator } // Yes this is almost a copypasta, got a problem with that? =\ - int windowCount = callback.getQueueSize(); - int currentWindowIndex = callback.getCurrentPlayingIndex(); - int queueSize = Math.min(maxQueueSize, windowCount); - int startIndex = Util.constrainValue(currentWindowIndex - ((queueSize - 1) / 2), 0, + final int windowCount = callback.getQueueSize(); + final int currentWindowIndex = callback.getCurrentPlayingIndex(); + final int queueSize = Math.min(maxQueueSize, windowCount); + final int startIndex = Util.constrainValue(currentWindowIndex - ((queueSize - 1) / 2), 0, windowCount - queueSize); - List queue = new ArrayList<>(); + final List queue = new ArrayList<>(); for (int i = startIndex; i < startIndex + queueSize; i++) { queue.add(new MediaSessionCompat.QueueItem(callback.getQueueMetadata(i), i)); } diff --git a/app/src/main/java/org/schabi/newpipe/player/playback/BasePlayerMediaSession.java b/app/src/main/java/org/schabi/newpipe/player/playback/BasePlayerMediaSession.java index 0154716e0..5b20077c3 100644 --- a/app/src/main/java/org/schabi/newpipe/player/playback/BasePlayerMediaSession.java +++ b/app/src/main/java/org/schabi/newpipe/player/playback/BasePlayerMediaSession.java @@ -57,13 +57,14 @@ public class BasePlayerMediaSession implements MediaSessionCallback { } final PlayQueueItem item = player.getPlayQueue().getItem(index); - MediaDescriptionCompat.Builder descriptionBuilder = new MediaDescriptionCompat.Builder() + final MediaDescriptionCompat.Builder descriptionBuilder + = new MediaDescriptionCompat.Builder() .setMediaId(String.valueOf(index)) .setTitle(item.getTitle()) .setSubtitle(item.getUploader()); // set additional metadata for A2DP/AVRCP - Bundle additionalMetadata = new Bundle(); + final Bundle additionalMetadata = new Bundle(); additionalMetadata.putString(MediaMetadataCompat.METADATA_KEY_TITLE, item.getTitle()); additionalMetadata.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, item.getUploader()); additionalMetadata diff --git a/app/src/main/java/org/schabi/newpipe/player/playback/CustomTrackSelector.java b/app/src/main/java/org/schabi/newpipe/player/playback/CustomTrackSelector.java index e554059d9..d70707fdb 100644 --- a/app/src/main/java/org/schabi/newpipe/player/playback/CustomTrackSelector.java +++ b/app/src/main/java/org/schabi/newpipe/player/playback/CustomTrackSelector.java @@ -60,14 +60,14 @@ public class CustomTrackSelector extends DefaultTrackSelector { TextTrackScore selectedTrackScore = null; for (int groupIndex = 0; groupIndex < groups.length; groupIndex++) { - TrackGroup trackGroup = groups.get(groupIndex); - @Capabilities int[] trackFormatSupport = formatSupport[groupIndex]; + final TrackGroup trackGroup = groups.get(groupIndex); + @Capabilities final int[] trackFormatSupport = formatSupport[groupIndex]; for (int trackIndex = 0; trackIndex < trackGroup.length; trackIndex++) { if (isSupported(trackFormatSupport[trackIndex], params.exceedRendererCapabilitiesIfNecessary)) { - Format format = trackGroup.getFormat(trackIndex); - TextTrackScore trackScore = new TextTrackScore(format, params, + final Format format = trackGroup.getFormat(trackIndex); + final TextTrackScore trackScore = new TextTrackScore(format, params, trackFormatSupport[trackIndex], selectedAudioLanguage); if (formatHasLanguage(format, preferredTextLanguage)) { diff --git a/app/src/main/java/org/schabi/newpipe/player/playqueue/AbstractInfoPlayQueue.java b/app/src/main/java/org/schabi/newpipe/player/playqueue/AbstractInfoPlayQueue.java index 3c15cd342..ec364c4df 100644 --- a/app/src/main/java/org/schabi/newpipe/player/playqueue/AbstractInfoPlayQueue.java +++ b/app/src/main/java/org/schabi/newpipe/player/playqueue/AbstractInfoPlayQueue.java @@ -129,7 +129,7 @@ abstract class AbstractInfoPlayQueue ext } private static List extractListItems(final List infos) { - List result = new ArrayList<>(); + final List result = new ArrayList<>(); for (final InfoItem stream : infos) { if (stream instanceof StreamInfoItem) { result.add(new PlayQueueItem((StreamInfoItem) stream)); diff --git a/app/src/main/java/org/schabi/newpipe/player/playqueue/SinglePlayQueue.java b/app/src/main/java/org/schabi/newpipe/player/playqueue/SinglePlayQueue.java index 79cf0601c..527e80470 100644 --- a/app/src/main/java/org/schabi/newpipe/player/playqueue/SinglePlayQueue.java +++ b/app/src/main/java/org/schabi/newpipe/player/playqueue/SinglePlayQueue.java @@ -26,7 +26,7 @@ public final class SinglePlayQueue extends PlayQueue { } private static List playQueueItemsOf(final List items) { - List playQueueItems = new ArrayList<>(items.size()); + final List playQueueItems = new ArrayList<>(items.size()); for (final StreamInfoItem item : items) { playQueueItems.add(new PlayQueueItem(item)); } diff --git a/app/src/main/java/org/schabi/newpipe/player/resolver/VideoPlaybackResolver.java b/app/src/main/java/org/schabi/newpipe/player/resolver/VideoPlaybackResolver.java index 2eb766769..2318bef20 100644 --- a/app/src/main/java/org/schabi/newpipe/player/resolver/VideoPlaybackResolver.java +++ b/app/src/main/java/org/schabi/newpipe/player/resolver/VideoPlaybackResolver.java @@ -52,7 +52,7 @@ public class VideoPlaybackResolver implements PlaybackResolver { return liveSource; } - List mediaSources = new ArrayList<>(); + final List mediaSources = new ArrayList<>(); // Create video stream source final List videos = ListHelper.getSortedStreamVideosList(context, diff --git a/app/src/main/java/org/schabi/newpipe/report/ErrorActivity.java b/app/src/main/java/org/schabi/newpipe/report/ErrorActivity.java index 52761e467..7ff3af91a 100644 --- a/app/src/main/java/org/schabi/newpipe/report/ErrorActivity.java +++ b/app/src/main/java/org/schabi/newpipe/report/ErrorActivity.java @@ -112,9 +112,9 @@ public class ErrorActivity extends AppCompatActivity { private static void startErrorActivity(final Class returnActivity, final Context context, final ErrorInfo errorInfo, final List el) { - ActivityCommunicator ac = ActivityCommunicator.getCommunicator(); + final ActivityCommunicator ac = ActivityCommunicator.getCommunicator(); ac.setReturnActivity(returnActivity); - Intent intent = new Intent(context, ErrorActivity.class); + final Intent intent = new Intent(context, ErrorActivity.class); intent.putExtra(ERROR_INFO, errorInfo); intent.putExtra(ERROR_LIST, elToSl(el)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); @@ -154,9 +154,9 @@ public class ErrorActivity extends AppCompatActivity { public static void reportError(final Context context, final CrashReportData report, final ErrorInfo errorInfo) { - String[] el = new String[]{report.getString(ReportField.STACK_TRACE)}; + final String[] el = new String[]{report.getString(ReportField.STACK_TRACE)}; - Intent intent = new Intent(context, ErrorActivity.class); + final Intent intent = new Intent(context, ErrorActivity.class); intent.putExtra(ERROR_INFO, errorInfo); intent.putExtra(ERROR_LIST, el); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); @@ -172,7 +172,7 @@ public class ErrorActivity extends AppCompatActivity { // errorList to StringList private static String[] elToSl(final List stackTraces) { - String[] out = new String[stackTraces.size()]; + final String[] out = new String[stackTraces.size()]; for (int i = 0; i < stackTraces.size(); i++) { out[i] = getStackTrace(stackTraces.get(i)); } @@ -186,12 +186,12 @@ public class ErrorActivity extends AppCompatActivity { ThemeHelper.setTheme(this); setContentView(R.layout.activity_error); - Intent intent = getIntent(); + final Intent intent = getIntent(); - Toolbar toolbar = findViewById(R.id.toolbar); + final Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); - ActionBar actionBar = getSupportActionBar(); + final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(R.string.error_report_title); @@ -203,11 +203,11 @@ public class ErrorActivity extends AppCompatActivity { final Button reportGithubButton = findViewById(R.id.errorReportGitHubButton); userCommentBox = findViewById(R.id.errorCommentBox); - TextView errorView = findViewById(R.id.errorView); - TextView infoView = findViewById(R.id.errorInfosView); - TextView errorMessageView = findViewById(R.id.errorMessageView); + final TextView errorView = findViewById(R.id.errorView); + final TextView infoView = findViewById(R.id.errorInfosView); + final TextView errorMessageView = findViewById(R.id.errorMessageView); - ActivityCommunicator ac = ActivityCommunicator.getCommunicator(); + final ActivityCommunicator ac = ActivityCommunicator.getCommunicator(); returnActivity = ac.getReturnActivity(); errorInfo = intent.getParcelableExtra(ERROR_INFO); errorList = intent.getStringArrayExtra(ERROR_LIST); @@ -242,27 +242,27 @@ public class ErrorActivity extends AppCompatActivity { errorView.setText(formErrorText(errorList)); // print stack trace once again for debugging: - for (String e : errorList) { + for (final String e : errorList) { Log.e(TAG, e); } } @Override public boolean onCreateOptionsMenu(final Menu menu) { - MenuInflater inflater = getMenuInflater(); + final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.error_menu, menu); return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { - int id = item.getItemId(); + final int id = item.getItemId(); switch (id) { case android.R.id.home: goToReturnActivity(); break; case R.id.menu_item_share_error: - Intent intent = new Intent(); + final Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, buildJson()); intent.setType("text/plain"); @@ -304,9 +304,9 @@ public class ErrorActivity extends AppCompatActivity { } private String formErrorText(final String[] el) { - StringBuilder text = new StringBuilder(); + final StringBuilder text = new StringBuilder(); if (el != null) { - for (String e : el) { + for (final String e : el) { text.append("-------------------------------------\n").append(e); } } @@ -334,19 +334,19 @@ public class ErrorActivity extends AppCompatActivity { } private void goToReturnActivity() { - Class checkedReturnActivity = getReturnActivity(returnActivity); + final Class checkedReturnActivity = getReturnActivity(returnActivity); if (checkedReturnActivity == null) { super.onBackPressed(); } else { - Intent intent = new Intent(this, checkedReturnActivity); + final Intent intent = new Intent(this, checkedReturnActivity); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); NavUtils.navigateUpTo(this, intent); } } private void buildInfo(final ErrorInfo info) { - TextView infoLabelView = findViewById(R.id.errorInfoLabelsView); - TextView infoView = findViewById(R.id.errorInfosView); + final TextView infoLabelView = findViewById(R.id.errorInfoLabelsView); + final TextView infoView = findViewById(R.id.errorInfosView); String text = ""; infoLabelView.setText(getString(R.string.info_labels).replace("\\n", "\n")); @@ -383,7 +383,7 @@ public class ErrorActivity extends AppCompatActivity { .value("user_comment", userCommentBox.getText().toString()) .end() .done(); - } catch (Throwable e) { + } catch (final Throwable e) { Log.e(TAG, "Error while erroring: Could not build json"); e.printStackTrace(); } @@ -441,7 +441,7 @@ public class ErrorActivity extends AppCompatActivity { } htmlErrorReport.append("
\n"); return htmlErrorReport.toString(); - } catch (Throwable e) { + } catch (final Throwable e) { Log.e(TAG, "Error while erroring: Could not build markdown"); e.printStackTrace(); return ""; @@ -478,7 +478,7 @@ public class ErrorActivity extends AppCompatActivity { private void addGuruMeditation() { //just an easter egg - TextView sorryView = findViewById(R.id.errorSorryView); + final TextView sorryView = findViewById(R.id.errorSorryView); String text = sorryView.getText().toString(); text += "\n" + getString(R.string.guru_meditation); sorryView.setText(text); @@ -491,7 +491,7 @@ public class ErrorActivity extends AppCompatActivity { } public String getCurrentTimeStamp() { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df.format(new Date()); } diff --git a/app/src/main/java/org/schabi/newpipe/settings/AppearanceSettingsFragment.java b/app/src/main/java/org/schabi/newpipe/settings/AppearanceSettingsFragment.java index a9531693c..ab875ed5d 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/AppearanceSettingsFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/AppearanceSettingsFragment.java @@ -42,7 +42,7 @@ public class AppearanceSettingsFragment extends BasePreferenceFragment { @Override public void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); - String themeKey = getString(R.string.theme_key); + final String themeKey = getString(R.string.theme_key); startThemeKey = defaultPreferences .getString(themeKey, getString(R.string.default_theme_value)); findPreference(themeKey).setOnPreferenceChangeListener(themePreferenceChange); @@ -64,7 +64,7 @@ public class AppearanceSettingsFragment extends BasePreferenceFragment { if (preference.getKey().equals(captionSettingsKey) && CAPTIONING_SETTINGS_ACCESSIBLE) { try { startActivity(new Intent(Settings.ACTION_CAPTIONING_SETTINGS)); - } catch (ActivityNotFoundException e) { + } catch (final ActivityNotFoundException e) { Toast.makeText(getActivity(), R.string.general_error, Toast.LENGTH_SHORT).show(); } } diff --git a/app/src/main/java/org/schabi/newpipe/settings/BasePreferenceFragment.java b/app/src/main/java/org/schabi/newpipe/settings/BasePreferenceFragment.java index 125931ee1..d8b686297 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/BasePreferenceFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/BasePreferenceFragment.java @@ -39,7 +39,7 @@ public abstract class BasePreferenceFragment extends PreferenceFragmentCompat { private void updateTitle() { if (getActivity() instanceof AppCompatActivity) { - ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); + final ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(getPreferenceScreen().getTitle()); } diff --git a/app/src/main/java/org/schabi/newpipe/settings/ContentSettingsFragment.java b/app/src/main/java/org/schabi/newpipe/settings/ContentSettingsFragment.java index b0bb30aa7..6ea2cc8a6 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/ContentSettingsFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/ContentSettingsFragment.java @@ -32,7 +32,6 @@ import org.schabi.newpipe.util.ZipHelper; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; @@ -91,7 +90,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment { } if (preference.getKey().equals(youtubeRestrictedModeEnabledKey)) { - Context context = getContext(); + final Context context = getContext(); if (context != null) { DownloaderImpl.getInstance().updateYoutubeRestrictedModeCookies(context); } else { @@ -105,7 +104,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment { @Override public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) { - String homeDir = getActivity().getApplicationInfo().dataDir; + final String homeDir = getActivity().getApplicationInfo().dataDir; databasesDir = new File(homeDir + "/databases"); newpipeDb = new File(homeDir + "/databases/newpipe.db"); newpipeDbJournal = new File(homeDir + "/databases/newpipe.db-journal"); @@ -117,9 +116,9 @@ public class ContentSettingsFragment extends BasePreferenceFragment { addPreferencesFromResource(R.xml.content_settings); - Preference importDataPreference = findPreference(getString(R.string.import_data)); + final Preference importDataPreference = findPreference(getString(R.string.import_data)); importDataPreference.setOnPreferenceClickListener((Preference p) -> { - Intent i = new Intent(getActivity(), FilePickerActivityHelper.class) + final Intent i = new Intent(getActivity(), FilePickerActivityHelper.class) .putExtra(FilePickerActivityHelper.EXTRA_ALLOW_MULTIPLE, false) .putExtra(FilePickerActivityHelper.EXTRA_ALLOW_CREATE_DIR, false) .putExtra(FilePickerActivityHelper.EXTRA_MODE, @@ -128,9 +127,9 @@ public class ContentSettingsFragment extends BasePreferenceFragment { return true; }); - Preference exportDataPreference = findPreference(getString(R.string.export_data)); + final Preference exportDataPreference = findPreference(getString(R.string.export_data)); exportDataPreference.setOnPreferenceClickListener((Preference p) -> { - Intent i = new Intent(getActivity(), FilePickerActivityHelper.class) + final Intent i = new Intent(getActivity(), FilePickerActivityHelper.class) .putExtra(FilePickerActivityHelper.EXTRA_ALLOW_MULTIPLE, false) .putExtra(FilePickerActivityHelper.EXTRA_ALLOW_CREATE_DIR, true) .putExtra(FilePickerActivityHelper.EXTRA_MODE, @@ -175,12 +174,12 @@ public class ContentSettingsFragment extends BasePreferenceFragment { if ((requestCode == REQUEST_IMPORT_PATH || requestCode == REQUEST_EXPORT_PATH) && resultCode == Activity.RESULT_OK && data.getData() != null) { - String path = Utils.getFileForUri(data.getData()).getAbsolutePath(); + final String path = Utils.getFileForUri(data.getData()).getAbsolutePath(); if (requestCode == REQUEST_EXPORT_PATH) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US); + final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US); exportDatabase(path + "/NewPipeData-" + sdf.format(new Date()) + ".zip"); } else { - AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.override_current_data) .setPositiveButton(getString(R.string.finish), (DialogInterface d, int id) -> importDatabase(path)) @@ -196,7 +195,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment { //checkpoint before export NewPipeDatabase.checkpoint(); - ZipOutputStream outZip = new ZipOutputStream( + final ZipOutputStream outZip = new ZipOutputStream( new BufferedOutputStream( new FileOutputStream(path))); ZipHelper.addFileToZip(outZip, newpipeDb.getPath(), "newpipe.db"); @@ -208,7 +207,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment { Toast.makeText(getContext(), R.string.export_complete_toast, Toast.LENGTH_SHORT) .show(); - } catch (Exception e) { + } catch (final Exception e) { onError(e); } } @@ -217,12 +216,11 @@ public class ContentSettingsFragment extends BasePreferenceFragment { ObjectOutputStream output = null; try { output = new ObjectOutputStream(new FileOutputStream(dst)); - SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getContext()); + final SharedPreferences pref + = PreferenceManager.getDefaultSharedPreferences(getContext()); output.writeObject(pref.getAll()); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } finally { try { @@ -230,7 +228,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment { output.flush(); output.close(); } - } catch (IOException ex) { + } catch (final IOException ex) { ex.printStackTrace(); } } @@ -241,14 +239,14 @@ public class ContentSettingsFragment extends BasePreferenceFragment { ZipFile zipFile = null; try { zipFile = new ZipFile(filePath); - } catch (IOException ioe) { + } catch (final IOException ioe) { Toast.makeText(getContext(), R.string.no_valid_zip_file, Toast.LENGTH_SHORT) .show(); return; } finally { try { zipFile.close(); - } catch (Exception ignored) { + } catch (final Exception ignored) { } } @@ -272,7 +270,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment { //If settings file exist, ask if it should be imported. if (ZipHelper.extractFileFromZip(filePath, newpipeSettings.getPath(), "newpipe.settings")) { - AlertDialog.Builder alert = new AlertDialog.Builder(getContext()); + final AlertDialog.Builder alert = new AlertDialog.Builder(getContext()); alert.setTitle(R.string.import_settings); alert.setNegativeButton(android.R.string.no, (dialog, which) -> { @@ -291,7 +289,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment { // restart app to properly load db System.exit(0); } - } catch (Exception e) { + } catch (final Exception e) { onError(e); } } @@ -300,13 +298,13 @@ public class ContentSettingsFragment extends BasePreferenceFragment { ObjectInputStream input = null; try { input = new ObjectInputStream(new FileInputStream(src)); - SharedPreferences.Editor prefEdit = PreferenceManager + final SharedPreferences.Editor prefEdit = PreferenceManager .getDefaultSharedPreferences(getContext()).edit(); prefEdit.clear(); - Map entries = (Map) input.readObject(); - for (Map.Entry entry : entries.entrySet()) { - Object v = entry.getValue(); - String key = entry.getKey(); + final Map entries = (Map) input.readObject(); + for (final Map.Entry entry : entries.entrySet()) { + final Object v = entry.getValue(); + final String key = entry.getKey(); if (v instanceof Boolean) { prefEdit.putBoolean(key, (Boolean) v); @@ -321,18 +319,14 @@ public class ContentSettingsFragment extends BasePreferenceFragment { } } prefEdit.commit(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { + } catch (final IOException | ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (input != null) { input.close(); } - } catch (IOException ex) { + } catch (final IOException ex) { ex.printStackTrace(); } } diff --git a/app/src/main/java/org/schabi/newpipe/settings/DownloadSettingsFragment.java b/app/src/main/java/org/schabi/newpipe/settings/DownloadSettingsFragment.java index aaa572eab..a4b29fc49 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/DownloadSettingsFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/DownloadSettingsFragment.java @@ -120,7 +120,7 @@ public class DownloadSettingsFragment extends BasePreferenceFragment { try { rawUri = URLDecoder.decode(rawUri, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { + } catch (final UnsupportedEncodingException e) { // nothing to do } @@ -132,7 +132,7 @@ public class DownloadSettingsFragment extends BasePreferenceFragment { } private boolean hasInvalidPath(final String prefKey) { - String value = defaultPreferences.getString(prefKey, null); + final String value = defaultPreferences.getString(prefKey, null); return value == null || value.isEmpty(); } @@ -152,20 +152,20 @@ public class DownloadSettingsFragment extends BasePreferenceFragment { } try { - Uri uri = Uri.parse(oldPath); + final Uri uri = Uri.parse(oldPath); context.getContentResolver() .releasePersistableUriPermission(uri, StoredDirectoryHelper.PERMISSION_FLAGS); context.revokeUriPermission(uri, StoredDirectoryHelper.PERMISSION_FLAGS); Log.i(TAG, "Revoke old path permissions success on " + oldPath); - } catch (Exception err) { + } catch (final Exception err) { Log.e(TAG, "Error revoking old path permissions on " + oldPath, err); } } private void showMessageDialog(@StringRes final int title, @StringRes final int message) { - AlertDialog.Builder msg = new AlertDialog.Builder(ctx); + final AlertDialog.Builder msg = new AlertDialog.Builder(ctx); msg.setTitle(title); msg.setMessage(message); msg.setPositiveButton(getString(R.string.finish), null); @@ -179,8 +179,8 @@ public class DownloadSettingsFragment extends BasePreferenceFragment { + "preference = [" + preference + "]"); } - String key = preference.getKey(); - int request; + final String key = preference.getKey(); + final int request; if (key.equals(storageUseSafPreference)) { Toast.makeText(getContext(), R.string.download_choose_new_path, @@ -194,7 +194,7 @@ public class DownloadSettingsFragment extends BasePreferenceFragment { return super.onPreferenceTreeClick(preference); } - Intent i; + final Intent i; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && NewPipeSettings.useStorageAccessFramework(ctx)) { i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) @@ -229,7 +229,7 @@ public class DownloadSettingsFragment extends BasePreferenceFragment { return; } - String key; + final String key; if (requestCode == REQUEST_DOWNLOAD_VIDEO_PATH) { key = downloadPathVideoPreference; } else if (requestCode == REQUEST_DOWNLOAD_AUDIO_PATH) { @@ -262,19 +262,20 @@ public class DownloadSettingsFragment extends BasePreferenceFragment { context.grantUriPermission(context.getPackageName(), uri, StoredDirectoryHelper.PERMISSION_FLAGS); - StoredDirectoryHelper mainStorage = new StoredDirectoryHelper(context, uri, null); + final StoredDirectoryHelper mainStorage + = new StoredDirectoryHelper(context, uri, null); Log.i(TAG, "Acquiring tree success from " + uri.toString()); if (!mainStorage.canWrite()) { throw new IOException("No write permissions on " + uri.toString()); } - } catch (IOException err) { + } catch (final IOException err) { Log.e(TAG, "Error acquiring tree from " + uri.toString(), err); showMessageDialog(R.string.general_error, R.string.no_available_dir); return; } } else { - File target = Utils.getFileForUri(uri); + final File target = Utils.getFileForUri(uri); if (!target.canWrite()) { showMessageDialog(R.string.download_to_sdcard_error_title, R.string.download_to_sdcard_error_message); diff --git a/app/src/main/java/org/schabi/newpipe/settings/NewPipeSettings.java b/app/src/main/java/org/schabi/newpipe/settings/NewPipeSettings.java index 47a16f6f3..8ce5fe4c2 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/NewPipeSettings.java +++ b/app/src/main/java/org/schabi/newpipe/settings/NewPipeSettings.java @@ -60,14 +60,14 @@ public final class NewPipeSettings { private static void getDir(final Context context, final int keyID, final String defaultDirectoryName) { - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final String key = context.getString(keyID); - String downloadPath = prefs.getString(key, null); + final String downloadPath = prefs.getString(key, null); if ((downloadPath != null) && (!downloadPath.isEmpty())) { return; } - SharedPreferences.Editor spEditor = prefs.edit(); + final SharedPreferences.Editor spEditor = prefs.edit(); spEditor.putString(key, getNewPipeChildFolderPathForDir(getDir(defaultDirectoryName))); spEditor.apply(); } diff --git a/app/src/main/java/org/schabi/newpipe/settings/PeertubeInstanceListFragment.java b/app/src/main/java/org/schabi/newpipe/settings/PeertubeInstanceListFragment.java index 03e246533..dfa975eef 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/PeertubeInstanceListFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/PeertubeInstanceListFragment.java @@ -96,16 +96,16 @@ public class PeertubeInstanceListFragment extends Fragment { } private void initViews(@NonNull final View rootView) { - TextView instanceHelpTV = rootView.findViewById(R.id.instanceHelpTV); + final TextView instanceHelpTV = rootView.findViewById(R.id.instanceHelpTV); instanceHelpTV.setText(getString(R.string.peertube_instance_url_help, getString(R.string.peertube_instance_list_url))); initButton(rootView); - RecyclerView listInstances = rootView.findViewById(R.id.instances); + final RecyclerView listInstances = rootView.findViewById(R.id.instances); listInstances.setLayoutManager(new LinearLayoutManager(requireContext())); - ItemTouchHelper itemTouchHelper = new ItemTouchHelper(getItemTouchCallback()); + final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(getItemTouchCallback()); itemTouchHelper.attachToRecyclerView(listInstances); instanceListAdapter = new InstanceListAdapter(requireContext(), itemTouchHelper); @@ -178,7 +178,7 @@ public class PeertubeInstanceListFragment extends Fragment { private void updateTitle() { if (getActivity() instanceof AppCompatActivity) { - ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); + final ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(R.string.peertube_instance_url_title); } @@ -186,14 +186,14 @@ public class PeertubeInstanceListFragment extends Fragment { } private void saveChanges() { - JsonStringWriter jsonWriter = JsonWriter.string().object().array("instances"); - for (PeertubeInstance instance : instanceList) { + final JsonStringWriter jsonWriter = JsonWriter.string().object().array("instances"); + for (final PeertubeInstance instance : instanceList) { jsonWriter.object(); jsonWriter.value("name", instance.getName()); jsonWriter.value("url", instance.getUrl()); jsonWriter.end(); } - String jsonToSave = jsonWriter.end().end().done(); + final String jsonToSave = jsonWriter.end().end().done(); sharedPreferences.edit().putString(savedInstanceListKey, jsonToSave).apply(); } @@ -222,12 +222,12 @@ public class PeertubeInstanceListFragment extends Fragment { final EditText urlET = new EditText(c); urlET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); urlET.setHint(R.string.peertube_instance_add_help); - AlertDialog dialog = new AlertDialog.Builder(c) + final AlertDialog dialog = new AlertDialog.Builder(c) .setTitle(R.string.peertube_instance_add_title) .setIcon(R.drawable.place_holder_peertube) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.finish, (dialog1, which) -> { - String url = urlET.getText().toString(); + final String url = urlET.getText().toString(); addInstance(url); }) .create(); @@ -236,13 +236,13 @@ public class PeertubeInstanceListFragment extends Fragment { } private void addInstance(final String url) { - String cleanUrl = cleanUrl(url); + final String cleanUrl = cleanUrl(url); if (cleanUrl == null) { return; } progressBar.setVisibility(View.VISIBLE); - Disposable disposable = Single.fromCallable(() -> { - PeertubeInstance instance = new PeertubeInstance(cleanUrl); + final Disposable disposable = Single.fromCallable(() -> { + final PeertubeInstance instance = new PeertubeInstance(cleanUrl); instance.fetchInstanceMetaData(); return instance; }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) @@ -273,7 +273,7 @@ public class PeertubeInstanceListFragment extends Fragment { return null; } // only allow if not already exists - for (PeertubeInstance instance : instanceList) { + for (final PeertubeInstance instance : instanceList) { if (instance.getUrl().equals(cleanUrl)) { Toast.makeText(getActivity(), R.string.peertube_instance_add_exists, Toast.LENGTH_SHORT).show(); @@ -331,7 +331,7 @@ public class PeertubeInstanceListFragment extends Fragment { @Override public void onSwiped(final RecyclerView.ViewHolder viewHolder, final int swipeDir) { - int position = viewHolder.getAdapterPosition(); + final int position = viewHolder.getAdapterPosition(); // do not allow swiping the selected instance if (instanceList.get(position).getUrl().equals(selectedInstance.getUrl())) { instanceListAdapter.notifyItemChanged(position); @@ -372,7 +372,7 @@ public class PeertubeInstanceListFragment extends Fragment { @Override public InstanceListAdapter.TabViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) { - View view = inflater.inflate(R.layout.item_instance, parent, false); + final View view = inflater.inflate(R.layout.item_instance, parent, false); return new InstanceListAdapter.TabViewHolder(view); } diff --git a/app/src/main/java/org/schabi/newpipe/settings/SelectChannelFragment.java b/app/src/main/java/org/schabi/newpipe/settings/SelectChannelFragment.java index df529fee0..1bc65da70 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/SelectChannelFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/SelectChannelFragment.java @@ -94,10 +94,10 @@ public class SelectChannelFragment extends DialogFragment { @Override public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.select_channel_fragment, container, false); + final View v = inflater.inflate(R.layout.select_channel_fragment, container, false); recyclerView = v.findViewById(R.id.items_list); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); - SelectChannelAdapter channelAdapter = new SelectChannelAdapter(); + final SelectChannelAdapter channelAdapter = new SelectChannelAdapter(); recyclerView.setAdapter(channelAdapter); progressBar = v.findViewById(R.id.progressBar); @@ -107,7 +107,7 @@ public class SelectChannelFragment extends DialogFragment { emptyView.setVisibility(View.GONE); - SubscriptionManager subscriptionManager = new SubscriptionManager(getContext()); + final SubscriptionManager subscriptionManager = new SubscriptionManager(getContext()); subscriptionManager.subscriptions().toObservable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) @@ -130,7 +130,7 @@ public class SelectChannelFragment extends DialogFragment { private void clickedItem(final int position) { if (onSelectedListener != null) { - SubscriptionEntity entry = subscriptions.get(position); + final SubscriptionEntity entry = subscriptions.get(position); onSelectedListener .onChannelSelected(entry.getServiceId(), entry.getUrl(), entry.getName()); } @@ -199,14 +199,14 @@ public class SelectChannelFragment extends DialogFragment { @Override public SelectChannelItemHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { - View item = LayoutInflater.from(parent.getContext()) + final View item = LayoutInflater.from(parent.getContext()) .inflate(R.layout.select_channel_item, parent, false); return new SelectChannelItemHolder(item); } @Override public void onBindViewHolder(final SelectChannelItemHolder holder, final int position) { - SubscriptionEntity entry = subscriptions.get(position); + final SubscriptionEntity entry = subscriptions.get(position); holder.titleView.setText(entry.getName()); holder.view.setOnClickListener(new View.OnClickListener() { @Override diff --git a/app/src/main/java/org/schabi/newpipe/settings/SelectKioskFragment.java b/app/src/main/java/org/schabi/newpipe/settings/SelectKioskFragment.java index 13d34dec8..9d0fece4f 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/SelectKioskFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/SelectKioskFragment.java @@ -76,12 +76,12 @@ public class SelectKioskFragment extends DialogFragment { @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.select_kiosk_fragment, container, false); + final View v = inflater.inflate(R.layout.select_kiosk_fragment, container, false); recyclerView = v.findViewById(R.id.items_list); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); try { selectKioskAdapter = new SelectKioskAdapter(); - } catch (Exception e) { + } catch (final Exception e) { onError(e); } recyclerView.setAdapter(selectKioskAdapter); @@ -135,9 +135,9 @@ public class SelectKioskFragment extends DialogFragment { private final List kioskList = new Vector<>(); SelectKioskAdapter() throws Exception { - for (StreamingService service : NewPipe.getServices()) { - for (String kioskId : service.getKioskList().getAvailableKiosks()) { - String name = String.format(getString(R.string.service_kiosk_string), + for (final StreamingService service : NewPipe.getServices()) { + for (final String kioskId : service.getKioskList().getAvailableKiosks()) { + final String name = String.format(getString(R.string.service_kiosk_string), service.getServiceInfo().getName(), KioskTranslator.getTranslatedKioskName(kioskId, getContext())); kioskList.add(new Entry(ServiceHelper.getIcon(service.getServiceId()), @@ -151,7 +151,7 @@ public class SelectKioskFragment extends DialogFragment { } public SelectKioskItemHolder onCreateViewHolder(final ViewGroup parent, final int type) { - View item = LayoutInflater.from(parent.getContext()) + final View item = LayoutInflater.from(parent.getContext()) .inflate(R.layout.select_kiosk_item, parent, false); return new SelectKioskItemHolder(item); } diff --git a/app/src/main/java/org/schabi/newpipe/settings/SelectPlaylistFragment.java b/app/src/main/java/org/schabi/newpipe/settings/SelectPlaylistFragment.java index 1d5c94421..c858c7f77 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/SelectPlaylistFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/SelectPlaylistFragment.java @@ -74,7 +74,7 @@ public class SelectPlaylistFragment extends DialogFragment { inflater.inflate(R.layout.select_playlist_fragment, container, false); recyclerView = v.findViewById(R.id.items_list); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); - SelectPlaylistAdapter playlistAdapter = new SelectPlaylistAdapter(); + final SelectPlaylistAdapter playlistAdapter = new SelectPlaylistAdapter(); recyclerView.setAdapter(playlistAdapter); progressBar = v.findViewById(R.id.progressBar); diff --git a/app/src/main/java/org/schabi/newpipe/settings/SettingsActivity.java b/app/src/main/java/org/schabi/newpipe/settings/SettingsActivity.java index 26a33917f..d2d4c2404 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/SettingsActivity.java +++ b/app/src/main/java/org/schabi/newpipe/settings/SettingsActivity.java @@ -53,7 +53,7 @@ public class SettingsActivity extends AppCompatActivity super.onCreate(savedInstanceBundle); setContentView(R.layout.settings_layout); - Toolbar toolbar = findViewById(R.id.toolbar); + final Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (savedInstanceBundle == null) { @@ -69,7 +69,7 @@ public class SettingsActivity extends AppCompatActivity @Override public boolean onCreateOptionsMenu(final Menu menu) { - ActionBar actionBar = getSupportActionBar(); + final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(true); @@ -80,7 +80,7 @@ public class SettingsActivity extends AppCompatActivity @Override public boolean onOptionsItemSelected(final MenuItem item) { - int id = item.getItemId(); + final int id = item.getItemId(); if (id == android.R.id.home) { if (getSupportFragmentManager().getBackStackEntryCount() == 0) { finish(); @@ -95,7 +95,7 @@ public class SettingsActivity extends AppCompatActivity @Override public boolean onPreferenceStartFragment(final PreferenceFragmentCompat caller, final Preference preference) { - Fragment fragment = Fragment + final Fragment fragment = Fragment .instantiate(this, preference.getFragment(), preference.getExtras()); getSupportFragmentManager().beginTransaction() .setCustomAnimations(R.animator.custom_fade_in, R.animator.custom_fade_out, diff --git a/app/src/main/java/org/schabi/newpipe/settings/UpdateSettingsFragment.java b/app/src/main/java/org/schabi/newpipe/settings/UpdateSettingsFragment.java index 2b103e794..476cf97ab 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/UpdateSettingsFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/UpdateSettingsFragment.java @@ -19,7 +19,7 @@ public class UpdateSettingsFragment extends BasePreferenceFragment { public void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); - String updateToggleKey = getString(R.string.update_app_key); + final String updateToggleKey = getString(R.string.update_app_key); findPreference(updateToggleKey).setOnPreferenceChangeListener(updatePreferenceChange); } diff --git a/app/src/main/java/org/schabi/newpipe/settings/VideoAudioSettingsFragment.java b/app/src/main/java/org/schabi/newpipe/settings/VideoAudioSettingsFragment.java index bef9a7b56..ce6d6dad5 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/VideoAudioSettingsFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/VideoAudioSettingsFragment.java @@ -35,7 +35,7 @@ public class VideoAudioSettingsFragment extends BasePreferenceFragment { // show a snackbar to let the user give permission if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && s.equals(getString(R.string.minimize_on_exit_key))) { - String newSetting = sharedPreferences.getString(s, null); + final String newSetting = sharedPreferences.getString(s, null); if (newSetting != null && newSetting.equals(getString(R.string.minimize_on_exit_popup_key)) && !Settings.canDrawOverlays(getContext())) { @@ -68,7 +68,7 @@ public class VideoAudioSettingsFragment extends BasePreferenceFragment { final boolean inexactSeek = getPreferenceManager().getSharedPreferences() .getBoolean(res.getString(R.string.use_inexact_seek_key), false); - for (String durationsValue : durationsValues) { + for (final String durationsValue : durationsValues) { currentDurationValue = Integer.parseInt(durationsValue) / (int) DateUtils.SECOND_IN_MILLIS; if (inexactSeek && currentDurationValue % 10 == 5) { @@ -81,7 +81,7 @@ public class VideoAudioSettingsFragment extends BasePreferenceFragment { res.getQuantityString(R.plurals.seconds, currentDurationValue), currentDurationValue)); - } catch (Resources.NotFoundException ignored) { + } catch (final Resources.NotFoundException ignored) { // if this happens, the translation is missing, // and the english string will be displayed instead } @@ -96,7 +96,7 @@ public class VideoAudioSettingsFragment extends BasePreferenceFragment { final int newDuration = selectedDuration / (int) DateUtils.SECOND_IN_MILLIS + 5; durations.setValue(Integer.toString(newDuration * (int) DateUtils.SECOND_IN_MILLIS)); - Toast toast = Toast + final Toast toast = Toast .makeText(getContext(), getString(R.string.new_seek_duration_toast, newDuration), Toast.LENGTH_LONG); diff --git a/app/src/main/java/org/schabi/newpipe/settings/tabs/ChooseTabsFragment.java b/app/src/main/java/org/schabi/newpipe/settings/tabs/ChooseTabsFragment.java index 1b26cd529..44fe987ee 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/tabs/ChooseTabsFragment.java +++ b/app/src/main/java/org/schabi/newpipe/settings/tabs/ChooseTabsFragment.java @@ -173,7 +173,7 @@ public class ChooseTabsFragment extends Fragment { return; } - Dialog.OnClickListener actionListener = (dialog, which) -> { + final Dialog.OnClickListener actionListener = (dialog, which) -> { final ChooseTabListItem selected = availableTabs[which]; addTab(selected.tabId); }; @@ -201,19 +201,19 @@ public class ChooseTabsFragment extends Fragment { switch (type) { case KIOSK: - SelectKioskFragment selectKioskFragment = new SelectKioskFragment(); + final SelectKioskFragment selectKioskFragment = new SelectKioskFragment(); selectKioskFragment.setOnSelectedListener((serviceId, kioskId, kioskName) -> addTab(new Tab.KioskTab(serviceId, kioskId))); selectKioskFragment.show(requireFragmentManager(), "select_kiosk"); return; case CHANNEL: - SelectChannelFragment selectChannelFragment = new SelectChannelFragment(); + final SelectChannelFragment selectChannelFragment = new SelectChannelFragment(); selectChannelFragment.setOnSelectedListener((serviceId, url, name) -> addTab(new Tab.ChannelTab(serviceId, url, name))); selectChannelFragment.show(requireFragmentManager(), "select_channel"); return; case PLAYLIST: - SelectPlaylistFragment selectPlaylistFragment = new SelectPlaylistFragment(); + final SelectPlaylistFragment selectPlaylistFragment = new SelectPlaylistFragment(); selectPlaylistFragment.setOnSelectedListener( new SelectPlaylistFragment.OnSelectedListener() { @Override @@ -238,7 +238,7 @@ public class ChooseTabsFragment extends Fragment { private ChooseTabListItem[] getAvailableTabs(final Context context) { final ArrayList returnList = new ArrayList<>(); - for (Tab.Type type : Tab.Type.values()) { + for (final Tab.Type type : Tab.Type.values()) { final Tab tab = type.getTab(); switch (type) { case BLANK: @@ -329,7 +329,7 @@ public class ChooseTabsFragment extends Fragment { @Override public void onSwiped(final RecyclerView.ViewHolder viewHolder, final int swipeDir) { - int position = viewHolder.getAdapterPosition(); + final int position = viewHolder.getAdapterPosition(); tabList.remove(position); selectedTabsAdapter.notifyItemRemoved(position); diff --git a/app/src/main/java/org/schabi/newpipe/settings/tabs/Tab.java b/app/src/main/java/org/schabi/newpipe/settings/tabs/Tab.java index b0511cd11..8e440c93d 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/tabs/Tab.java +++ b/app/src/main/java/org/schabi/newpipe/settings/tabs/Tab.java @@ -65,7 +65,7 @@ public abstract class Tab { @Nullable public static Type typeFrom(final int tabId) { - for (Type available : Type.values()) { + for (final Type available : Type.values()) { if (available.getTabId() == tabId) { return available; } @@ -481,7 +481,7 @@ public abstract class Tab { try { final StreamingService service = NewPipe.getService(kioskServiceId); kioskId = service.getKioskList().getDefaultKioskId(); - } catch (ExtractionException e) { + } catch (final ExtractionException e) { ErrorActivity.reportError(context, e, null, null, ErrorActivity.ErrorInfo.make(UserAction.REQUESTED_KIOSK, "none", "Loading default kiosk from selected service", 0)); diff --git a/app/src/main/java/org/schabi/newpipe/settings/tabs/TabsJsonHelper.java b/app/src/main/java/org/schabi/newpipe/settings/tabs/TabsJsonHelper.java index d18aad9d3..057ca50f0 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/tabs/TabsJsonHelper.java +++ b/app/src/main/java/org/schabi/newpipe/settings/tabs/TabsJsonHelper.java @@ -59,7 +59,7 @@ public final class TabsJsonHelper { final JsonArray tabsArray = outerJsonObject.getArray(JSON_TABS_ARRAY_KEY); - for (Object o : tabsArray) { + for (final Object o : tabsArray) { if (!(o instanceof JsonObject)) { continue; } @@ -70,7 +70,7 @@ public final class TabsJsonHelper { returnTabs.add(tab); } } - } catch (JsonParserException e) { + } catch (final JsonParserException e) { throw new InvalidJsonException(e); } @@ -93,7 +93,7 @@ public final class TabsJsonHelper { jsonWriter.array(JSON_TABS_ARRAY_KEY); if (tabList != null) { - for (Tab tab : tabList) { + for (final Tab tab : tabList) { tab.writeJsonOn(jsonWriter); } } diff --git a/app/src/main/java/org/schabi/newpipe/settings/tabs/TabsManager.java b/app/src/main/java/org/schabi/newpipe/settings/tabs/TabsManager.java index c76df7047..316e3a835 100644 --- a/app/src/main/java/org/schabi/newpipe/settings/tabs/TabsManager.java +++ b/app/src/main/java/org/schabi/newpipe/settings/tabs/TabsManager.java @@ -30,7 +30,7 @@ public final class TabsManager { final String savedJson = sharedPreferences.getString(savedTabsKey, null); try { return TabsJsonHelper.getTabsFromJson(savedJson); - } catch (TabsJsonHelper.InvalidJsonException e) { + } catch (final TabsJsonHelper.InvalidJsonException e) { Toast.makeText(context, R.string.saved_tabs_invalid_json, Toast.LENGTH_SHORT).show(); return getDefaultTabs(); } diff --git a/app/src/main/java/org/schabi/newpipe/streams/DataReader.java b/app/src/main/java/org/schabi/newpipe/streams/DataReader.java index dcd751e81..b9d1026f0 100644 --- a/app/src/main/java/org/schabi/newpipe/streams/DataReader.java +++ b/app/src/main/java/org/schabi/newpipe/streams/DataReader.java @@ -70,7 +70,7 @@ public class DataReader { } public long readUnsignedInt() throws IOException { - long value = readInt(); + final long value = readInt(); return value & 0xffffffffL; } @@ -82,8 +82,9 @@ public class DataReader { public long readLong() throws IOException { primitiveRead(LONG_SIZE); - long high = primitive[0] << 24 | primitive[1] << 16 | primitive[2] << 8 | primitive[3]; - long low = primitive[4] << 24 | primitive[5] << 16 | primitive[6] << 8 | primitive[7]; + final long high + = primitive[0] << 24 | primitive[1] << 16 | primitive[2] << 8 | primitive[3]; + final long low = primitive[4] << 24 | primitive[5] << 16 | primitive[6] << 8 | primitive[7]; return high << 32 | low; } @@ -114,7 +115,7 @@ public class DataReader { total += Math.max(stream.read(buffer, offset, count), 0); } else { while (count > 0 && !fillBuffer()) { - int read = Math.min(readCount, count); + final int read = Math.min(readCount, count); System.arraycopy(readBuffer, readOffset, buffer, offset, read); readOffset += read; @@ -169,7 +170,7 @@ public class DataReader { if (viewSize < 1) { return -1; } - int res = DataReader.this.read(); + final int res = DataReader.this.read(); if (res > 0) { viewSize--; } @@ -188,7 +189,7 @@ public class DataReader { return -1; } - int res = DataReader.this.read(buffer, offset, Math.min(viewSize, count)); + final int res = DataReader.this.read(buffer, offset, Math.min(viewSize, count)); viewSize -= res; return res; @@ -199,7 +200,7 @@ public class DataReader { if (viewSize < 1) { return 0; } - int res = (int) DataReader.this.skipBytes(Math.min(amount, viewSize)); + final int res = (int) DataReader.this.skipBytes(Math.min(amount, viewSize)); viewSize -= res; return res; @@ -230,8 +231,8 @@ public class DataReader { private final short[] primitive = new short[LONG_SIZE]; private void primitiveRead(final int amount) throws IOException { - byte[] buffer = new byte[amount]; - int read = read(buffer, 0, amount); + final byte[] buffer = new byte[amount]; + final int read = read(buffer, 0, amount); if (read != amount) { throw new EOFException("Truncated stream, missing " diff --git a/app/src/main/java/org/schabi/newpipe/streams/Mp4DashReader.java b/app/src/main/java/org/schabi/newpipe/streams/Mp4DashReader.java index ff3aabd78..60390946b 100644 --- a/app/src/main/java/org/schabi/newpipe/streams/Mp4DashReader.java +++ b/app/src/main/java/org/schabi/newpipe/streams/Mp4DashReader.java @@ -116,7 +116,7 @@ public class Mp4DashReader { tracks[i].trak = moov.trak[i]; if (moov.mvexTrex != null) { - for (Trex mvexTrex : moov.mvexTrex) { + for (final Trex mvexTrex : moov.mvexTrex) { if (tracks[i].trak.tkhd.trackId == mvexTrex.trackId) { tracks[i].trex = mvexTrex; } @@ -174,7 +174,7 @@ public class Mp4DashReader { } public Mp4DashChunk getNextChunk(final boolean infoOnly) throws IOException { - Mp4Track track = tracks[selectedTrack]; + final Mp4Track track = tracks[selectedTrack]; while (stream.available()) { @@ -233,7 +233,7 @@ public class Mp4DashReader { continue; // find another chunk } - Mp4DashChunk chunk = new Mp4DashChunk(); + final Mp4DashChunk chunk = new Mp4DashChunk(); chunk.moof = moof; if (!infoOnly) { chunk.data = stream.getView(moof.traf.trun.chunkSize); @@ -261,13 +261,13 @@ public class Mp4DashReader { private String boxName(final int type) { try { return new String(ByteBuffer.allocate(4).putInt(type).array(), "UTF-8"); - } catch (UnsupportedEncodingException e) { + } catch (final UnsupportedEncodingException e) { return "0x" + Integer.toHexString(type); } } private Box readBox() throws IOException { - Box b = new Box(); + final Box b = new Box(); b.offset = stream.position(); b.size = stream.readUnsignedInt(); b.type = stream.readInt(); @@ -280,7 +280,7 @@ public class Mp4DashReader { } private Box readBox(final int expected) throws IOException { - Box b = readBox(); + final Box b = readBox(); if (b.type != expected) { throw new NoSuchElementException("expected " + boxName(expected) + " found " + boxName(b)); @@ -290,13 +290,13 @@ public class Mp4DashReader { private byte[] readFullBox(final Box ref) throws IOException { // full box reading is limited to 2 GiB, and should be enough - int size = (int) ref.size; + final int size = (int) ref.size; - ByteBuffer buffer = ByteBuffer.allocate(size); + final ByteBuffer buffer = ByteBuffer.allocate(size); buffer.putInt(size); buffer.putInt(ref.type); - int read = size - 8; + final int read = size - 8; if (stream.read(buffer.array(), 8, read) != read) { throw new EOFException(String.format("EOF reached in box: type=%s offset=%s size=%s", @@ -307,7 +307,7 @@ public class Mp4DashReader { } private void ensure(final Box ref) throws IOException { - long skip = ref.offset + ref.size - stream.position(); + final long skip = ref.offset + ref.size - stream.position(); if (skip == 0) { return; @@ -325,7 +325,7 @@ public class Mp4DashReader { Box b; while (stream.position() < (ref.offset + ref.size)) { b = readBox(); - for (int type : expected) { + for (final int type : expected) { if (b.type == type) { return b; } @@ -345,7 +345,7 @@ public class Mp4DashReader { } private Moof parseMoof(final Box ref, final int trackId) throws IOException { - Moof obj = new Moof(); + final Moof obj = new Moof(); Box b = readBox(ATOM_MFHD); obj.mfhdSequenceNumber = parseMfhd(); @@ -372,7 +372,7 @@ public class Mp4DashReader { } private Traf parseTraf(final Box ref, final int trackId) throws IOException { - Traf traf = new Traf(); + final Traf traf = new Traf(); Box b = readBox(ATOM_TFHD); traf.tfhd = parseTfhd(trackId); @@ -397,7 +397,7 @@ public class Mp4DashReader { } private Tfhd parseTfhd(final int trackId) throws IOException { - Tfhd obj = new Tfhd(); + final Tfhd obj = new Tfhd(); obj.bFlags = stream.readInt(); obj.trackId = stream.readInt(); @@ -426,13 +426,13 @@ public class Mp4DashReader { } private long parseTfdt() throws IOException { - int version = stream.read(); + final int version = stream.read(); stream.skipBytes(3); // flags return version == 0 ? stream.readUnsignedInt() : stream.readLong(); } private Trun parseTrun() throws IOException { - Trun obj = new Trun(); + final Trun obj = new Trun(); obj.bFlags = stream.readInt(); obj.entryCount = stream.readInt(); // unsigned int @@ -461,7 +461,7 @@ public class Mp4DashReader { stream.read(obj.bEntries); for (int i = 0; i < obj.entryCount; i++) { - TrunEntry entry = obj.getEntry(i); + final TrunEntry entry = obj.getEntry(i); if (hasFlag(obj.bFlags, 0x0100)) { obj.chunkDuration += entry.sampleDuration; } @@ -480,7 +480,7 @@ public class Mp4DashReader { private int[] parseFtyp(final Box ref) throws IOException { int i = 0; - int[] list = new int[(int) ((ref.offset + ref.size - stream.position() - 4) / 4)]; + final int[] list = new int[(int) ((ref.offset + ref.size - stream.position() - 4) / 4)]; list[i++] = stream.readInt(); // major brand @@ -494,14 +494,14 @@ public class Mp4DashReader { } private Mvhd parseMvhd() throws IOException { - int version = stream.read(); + final int version = stream.read(); stream.skipBytes(3); // flags // creation entries_time // modification entries_time stream.skipBytes(2 * (version == 0 ? 4 : 8)); - Mvhd obj = new Mvhd(); + final Mvhd obj = new Mvhd(); obj.timeScale = stream.readUnsignedInt(); // chunkDuration @@ -520,9 +520,9 @@ public class Mp4DashReader { } private Tkhd parseTkhd() throws IOException { - int version = stream.read(); + final int version = stream.read(); - Tkhd obj = new Tkhd(); + final Tkhd obj = new Tkhd(); // flags // creation entries_time @@ -553,7 +553,7 @@ public class Mp4DashReader { } private Trak parseTrak(final Box ref) throws IOException { - Trak trak = new Trak(); + final Trak trak = new Trak(); Box b = readBox(ATOM_TKHD); trak.tkhd = parseTkhd(); @@ -576,7 +576,7 @@ public class Mp4DashReader { } private Mdia parseMdia(final Box ref) throws IOException { - Mdia obj = new Mdia(); + final Mdia obj = new Mdia(); Box b; while ((b = untilBox(ref, ATOM_MDHD, ATOM_HDLR, ATOM_MINF)) != null) { @@ -585,8 +585,8 @@ public class Mp4DashReader { obj.mdhd = readFullBox(b); // read time scale - ByteBuffer buffer = ByteBuffer.wrap(obj.mdhd); - byte version = buffer.get(8); + final ByteBuffer buffer = ByteBuffer.wrap(obj.mdhd); + final byte version = buffer.get(8); buffer.position(12 + ((version == 0 ? 4 : 8) * 2)); obj.mdhdTimeScale = buffer.getInt(); break; @@ -608,7 +608,7 @@ public class Mp4DashReader { // flags stream.skipBytes(4); - Hdlr obj = new Hdlr(); + final Hdlr obj = new Hdlr(); obj.bReserved = new byte[12]; obj.type = stream.readInt(); @@ -623,11 +623,11 @@ public class Mp4DashReader { private Moov parseMoov(final Box ref) throws IOException { Box b = readBox(ATOM_MVHD); - Moov moov = new Moov(); + final Moov moov = new Moov(); moov.mvhd = parseMvhd(); ensure(b); - ArrayList tmp = new ArrayList<>((int) moov.mvhd.nextTrackId); + final ArrayList tmp = new ArrayList<>((int) moov.mvhd.nextTrackId); while ((b = untilBox(ref, ATOM_TRAK, ATOM_MVEX)) != null) { switch (b.type) { @@ -648,7 +648,7 @@ public class Mp4DashReader { } private Trex[] parseMvex(final Box ref, final int possibleTrackCount) throws IOException { - ArrayList tmp = new ArrayList<>(possibleTrackCount); + final ArrayList tmp = new ArrayList<>(possibleTrackCount); Box b; while ((b = untilBox(ref, ATOM_TREX)) != null) { @@ -664,7 +664,7 @@ public class Mp4DashReader { // flags stream.skipBytes(4); - Trex obj = new Trex(); + final Trex obj = new Trex(); obj.trackId = stream.readInt(); obj.defaultSampleDescriptionIndex = stream.readInt(); obj.defaultSampleDuration = stream.readInt(); @@ -675,17 +675,17 @@ public class Mp4DashReader { } private Elst parseEdts(final Box ref) throws IOException { - Box b = untilBox(ref, ATOM_ELST); + final Box b = untilBox(ref, ATOM_ELST); if (b == null) { return null; } - Elst obj = new Elst(); + final Elst obj = new Elst(); - boolean v1 = stream.read() == 1; + final boolean v1 = stream.read() == 1; stream.skipBytes(3); // flags - int entryCount = stream.readInt(); + final int entryCount = stream.readInt(); if (entryCount < 1) { obj.bMediaRate = 0x00010000; // default media rate (1.0) return obj; @@ -707,7 +707,7 @@ public class Mp4DashReader { } private Minf parseMinf(final Box ref) throws IOException { - Minf obj = new Minf(); + final Minf obj = new Minf(); Box b; while ((b = untilAnyBox(ref)) != null) { @@ -738,7 +738,7 @@ public class Mp4DashReader { * @return stsd box inside */ private byte[] parseStbl(final Box ref) throws IOException { - Box b = untilBox(ref, ATOM_STSD); + final Box b = untilBox(ref, ATOM_STSD); if (b == null) { return new byte[0]; // this never should happens (missing codec startup data) @@ -796,8 +796,8 @@ public class Mp4DashReader { int entriesRowSize; public TrunEntry getEntry(final int i) { - ByteBuffer buffer = ByteBuffer.wrap(bEntries, i * entriesRowSize, entriesRowSize); - TrunEntry entry = new TrunEntry(); + final ByteBuffer buffer = ByteBuffer.wrap(bEntries, i * entriesRowSize, entriesRowSize); + final TrunEntry entry = new TrunEntry(); if (hasFlag(bFlags, 0x0100)) { entry.sampleDuration = buffer.getInt(); @@ -819,7 +819,7 @@ public class Mp4DashReader { } public TrunEntry getAbsoluteEntry(final int i, final Tfhd header) { - TrunEntry entry = getEntry(i); + final TrunEntry entry = getEntry(i); if (!hasFlag(bFlags, 0x0100) && hasFlag(header.bFlags, 0x20)) { entry.sampleFlags = header.defaultSampleFlags; @@ -928,7 +928,7 @@ public class Mp4DashReader { return null; } - Mp4DashSample sample = new Mp4DashSample(); + final Mp4DashSample sample = new Mp4DashSample(); sample.info = moof.traf.trun.getAbsoluteEntry(i++, moof.traf.tfhd); sample.data = new byte[sample.info.sampleSize]; diff --git a/app/src/main/java/org/schabi/newpipe/streams/Mp4FromDashWriter.java b/app/src/main/java/org/schabi/newpipe/streams/Mp4FromDashWriter.java index 2baf8fe55..8f71c6934 100644 --- a/app/src/main/java/org/schabi/newpipe/streams/Mp4FromDashWriter.java +++ b/app/src/main/java/org/schabi/newpipe/streams/Mp4FromDashWriter.java @@ -51,7 +51,7 @@ public class Mp4FromDashWriter { private final ArrayList compatibleBrands = new ArrayList<>(5); public Mp4FromDashWriter(final SharpStream... sources) throws IOException { - for (SharpStream src : sources) { + for (final SharpStream src : sources) { if (!src.canRewind() && !src.canRead()) { throw new IOException("All sources must be readable and allow rewind"); } @@ -128,7 +128,7 @@ public class Mp4FromDashWriter { done = true; parsed = true; - for (SharpStream src : sourceTracks) { + for (final SharpStream src : sourceTracks) { src.close(); } @@ -157,17 +157,17 @@ public class Mp4FromDashWriter { outStream = output; long read = 8; // mdat box header size long totalSampleSize = 0; - int[] sampleExtra = new int[readers.length]; - int[] defaultMediaTime = new int[readers.length]; - int[] defaultSampleDuration = new int[readers.length]; - int[] sampleCount = new int[readers.length]; + final int[] sampleExtra = new int[readers.length]; + final int[] defaultMediaTime = new int[readers.length]; + final int[] defaultSampleDuration = new int[readers.length]; + final int[] sampleCount = new int[readers.length]; - TablesInfo[] tablesInfo = new TablesInfo[tracks.length]; + final TablesInfo[] tablesInfo = new TablesInfo[tracks.length]; for (int i = 0; i < tablesInfo.length; i++) { tablesInfo[i] = new TablesInfo(); } - int singleSampleBuffer; + final int singleSampleBuffer; if (tracks.length == 1 && tracks[0].kind == TrackKind.Audio) { // near 1 second of audio data per chunk, avoid split the audio stream in large chunks singleSampleBuffer = tracks[0].trak.mdia.mdhdTimeScale / 1000; @@ -250,10 +250,10 @@ public class Mp4FromDashWriter { } - boolean is64 = read > THRESHOLD_FOR_CO64; + final boolean is64 = read > THRESHOLD_FOR_CO64; // calculate the moov size - int auxSize = makeMoov(defaultMediaTime, tablesInfo, is64); + final int auxSize = makeMoov(defaultMediaTime, tablesInfo, is64); if (auxSize < THRESHOLD_MOOV_LENGTH) { auxBuffer = ByteBuffer.allocate(auxSize); // cache moov in the memory @@ -267,9 +267,9 @@ public class Mp4FromDashWriter { // reserve moov space in the output stream if (auxSize > 0) { int length = auxSize; - byte[] buffer = new byte[64 * 1024]; // 64 KiB + final byte[] buffer = new byte[64 * 1024]; // 64 KiB while (length > 0) { - int count = Math.min(length, buffer.length); + final int count = Math.min(length, buffer.length); outWrite(buffer, count); length -= count; } @@ -305,9 +305,10 @@ public class Mp4FromDashWriter { outWrite(makeMdat(totalSampleSize, is64)); - int[] sampleIndex = new int[readers.length]; - int[] sizes = new int[singleSampleBuffer > 0 ? singleSampleBuffer : SAMPLES_PER_CHUNK]; - int[] sync = new int[singleSampleBuffer > 0 ? singleSampleBuffer : SAMPLES_PER_CHUNK]; + final int[] sampleIndex = new int[readers.length]; + final int[] sizes + = new int[singleSampleBuffer > 0 ? singleSampleBuffer : SAMPLES_PER_CHUNK]; + final int[] sync = new int[singleSampleBuffer > 0 ? singleSampleBuffer : SAMPLES_PER_CHUNK]; int written = readers.length; while (written > 0) { @@ -318,9 +319,9 @@ public class Mp4FromDashWriter { continue; // track is done } - long chunkOffset = writeOffset; + final long chunkOffset = writeOffset; int syncCount = 0; - int limit; + final int limit; if (singleSampleBuffer > 0) { limit = singleSampleBuffer; } else { @@ -329,7 +330,7 @@ public class Mp4FromDashWriter { int j = 0; for (; j < limit; j++) { - Mp4DashSample sample = getNextSample(i); + final Mp4DashSample sample = getNextSample(i); if (sample == null) { if (tablesInfo[i].ctts > 0 && sampleExtra[i] >= 0) { @@ -409,7 +410,7 @@ public class Mp4FromDashWriter { } } - Mp4DashSample sample = readersChunks[track].getNextSample(); + final Mp4DashSample sample = readersChunks[track].getNextSample(); if (sample == null) { readersChunks[track] = null; return getNextSample(track); @@ -434,8 +435,8 @@ public class Mp4FromDashWriter { auxSeek(offset); - int size = count * 4; - ByteBuffer buffer = ByteBuffer.allocate(size); + final int size = count * 4; + final ByteBuffer buffer = ByteBuffer.allocate(size); for (int i = 0; i < count; i++) { buffer.putInt(values[i]); @@ -466,10 +467,10 @@ public class Mp4FromDashWriter { private void initChunkTables(final TablesInfo tables, final int firstCount, final int successiveCount) { // tables.stsz holds amount of samples of the track (total) - int totalSamples = (tables.stsz - firstCount); - float chunkAmount = totalSamples / (float) successiveCount; - int remainChunkOffset = (int) Math.ceil(chunkAmount); - boolean remain = remainChunkOffset != (int) chunkAmount; + final int totalSamples = (tables.stsz - firstCount); + final float chunkAmount = totalSamples / (float) successiveCount; + final int remainChunkOffset = (int) Math.ceil(chunkAmount); + final boolean remain = remainChunkOffset != (int) chunkAmount; int index = 0; tables.stsc = 1; @@ -529,7 +530,7 @@ public class Mp4FromDashWriter { } private int lengthFor(final int offset) throws IOException { - int size = auxOffset() - offset; + final int size = auxOffset() - offset; if (moovSimulation) { return size; @@ -545,7 +546,7 @@ public class Mp4FromDashWriter { private int make(final int type, final int extra, final int columns, final int rows) throws IOException { final byte base = 16; - int size = columns * rows * 4; + final int size = columns * rows * 4; int total = size + base; int offset = auxOffset(); @@ -618,7 +619,7 @@ public class Mp4FromDashWriter { size += 4; } - ByteBuffer buffer = ByteBuffer.allocate(size); + final ByteBuffer buffer = ByteBuffer.allocate(size); buffer.putInt(size); buffer.putInt(0x66747970); // "ftyp" @@ -631,7 +632,7 @@ public class Mp4FromDashWriter { buffer.putInt(0x6D703432); // "mp42" compatible brand } - for (Integer brand : compatibleBrands) { + for (final Integer brand : compatibleBrands) { buffer.putInt(brand); // compatible brand } @@ -648,7 +649,7 @@ public class Mp4FromDashWriter { size += 8; } - ByteBuffer buffer = ByteBuffer.allocate(is64 ? 16 : 8) + final ByteBuffer buffer = ByteBuffer.allocate(is64 ? 16 : 8) .putInt(is64 ? 0x01 : (int) size) .putInt(0x6D646174); // mdat @@ -689,14 +690,14 @@ public class Mp4FromDashWriter { private int makeMoov(final int[] defaultMediaTime, final TablesInfo[] tablesInfo, final boolean is64) throws RuntimeException, IOException { - int start = auxOffset(); + final int start = auxOffset(); auxWrite(new byte[]{ 0x00, 0x00, 0x00, 0x00, 0x6D, 0x6F, 0x6F, 0x76 }); long longestTrack = 0; - long[] durations = new long[tracks.length]; + final long[] durations = new long[tracks.length]; for (int i = 0; i < durations.length; i++) { durations[i] = (long) Math.ceil( @@ -723,7 +724,7 @@ public class Mp4FromDashWriter { private void makeTrak(final int index, final long duration, final int defaultMediaTime, final TablesInfo tables, final boolean is64) throws IOException { - int start = auxOffset(); + final int start = auxOffset(); auxWrite(new byte[]{ // trak header @@ -732,7 +733,7 @@ public class Mp4FromDashWriter { 0x00, 0x00, 0x00, 0x68, 0x74, 0x6B, 0x68, 0x64, 0x01, 0x00, 0x00, 0x03 }); - ByteBuffer buffer = ByteBuffer.allocate(48); + final ByteBuffer buffer = ByteBuffer.allocate(48); buffer.putLong(time); buffer.putLong(time); buffer.putInt(index + 1); @@ -757,8 +758,8 @@ public class Mp4FromDashWriter { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 // elst header }); - int bMediaRate; - int mediaTime; + final int bMediaRate; + final int mediaTime; if (tracks[index].trak.edstElst == null) { // is a audio track ¿is edst/elst optional for audio tracks? @@ -784,17 +785,17 @@ public class Mp4FromDashWriter { private void makeMdia(final Mdia mdia, final TablesInfo tablesInfo, final boolean is64, final boolean isAudio) throws IOException { - int startMdia = auxOffset(); + final int startMdia = auxOffset(); auxWrite(new byte[]{0x00, 0x00, 0x00, 0x00, 0x6D, 0x64, 0x69, 0x61}); // mdia auxWrite(mdia.mdhd); auxWrite(makeHdlr(mdia.hdlr)); - int startMinf = auxOffset(); + final int startMinf = auxOffset(); auxWrite(new byte[]{0x00, 0x00, 0x00, 0x00, 0x6D, 0x69, 0x6E, 0x66}); // minf auxWrite(mdia.minf.mhd); auxWrite(mdia.minf.dinf); - int startStbl = auxOffset(); + final int startStbl = auxOffset(); auxWrite(new byte[]{0x00, 0x00, 0x00, 0x00, 0x73, 0x74, 0x62, 0x6C}); // stbl auxWrite(mdia.minf.stblStsd); @@ -838,7 +839,7 @@ public class Mp4FromDashWriter { } private byte[] makeHdlr(final Hdlr hdlr) { - ByteBuffer buffer = ByteBuffer.wrap(new byte[]{ + final ByteBuffer buffer = ByteBuffer.wrap(new byte[]{ 0x00, 0x00, 0x00, 0x21, 0x68, 0x64, 0x6C, 0x72, // hdlr 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -854,7 +855,7 @@ public class Mp4FromDashWriter { } private int makeSbgp() throws IOException { - int offset = auxOffset(); + final int offset = auxOffset(); auxWrite(new byte[] { 0x00, 0x00, 0x00, 0x1C, // box size @@ -883,7 +884,7 @@ public class Mp4FromDashWriter { * most of m4a encoders and ffmpeg uses this box with dummy values (same values) */ - ByteBuffer buffer = ByteBuffer.wrap(new byte[] { + final ByteBuffer buffer = ByteBuffer.wrap(new byte[] { 0x00, 0x00, 0x00, 0x1A, // box size 0x73, 0x67, 0x70, 0x64, // "sgpd" 0x01, 0x00, 0x00, 0x00, // box flags (unknown flag sets) diff --git a/app/src/main/java/org/schabi/newpipe/streams/OggFromWebMWriter.java b/app/src/main/java/org/schabi/newpipe/streams/OggFromWebMWriter.java index 9542dbc05..44104f133 100644 --- a/app/src/main/java/org/schabi/newpipe/streams/OggFromWebMWriter.java +++ b/app/src/main/java/org/schabi/newpipe/streams/OggFromWebMWriter.java @@ -145,10 +145,10 @@ public class OggFromWebMWriter implements Closeable { } public void build() throws IOException { - float resolution; + final float resolution; SimpleBlock bloq; - ByteBuffer header = ByteBuffer.allocate(27 + (255 * 255)); - ByteBuffer page = ByteBuffer.allocate(64 * 1024); + final ByteBuffer header = ByteBuffer.allocate(27 + (255 * 255)); + final ByteBuffer page = ByteBuffer.allocate(64 * 1024); header.order(ByteOrder.LITTLE_ENDIAN); @@ -181,7 +181,7 @@ public class OggFromWebMWriter implements Closeable { } /* step 3: create packet with metadata */ - byte[] buffer = makeMetadata(); + final byte[] buffer = makeMetadata(); if (buffer != null) { addPacketSegment(buffer.length); makePacketheader(0x00, header, buffer); @@ -194,7 +194,7 @@ public class OggFromWebMWriter implements Closeable { bloq = getNextBlock(); if (bloq != null && addPacketSegment(bloq)) { - int pos = page.position(); + final int pos = page.position(); //noinspection ResultOfMethodCallIgnored bloq.data.read(page.array(), pos, bloq.dataSize); page.position(pos + bloq.dataSize); @@ -334,10 +334,10 @@ public class OggFromWebMWriter implements Closeable { private float getSampleFrequencyFromTrack(final byte[] bMetadata) { // hardcoded way - ByteBuffer buffer = ByteBuffer.wrap(bMetadata); + final ByteBuffer buffer = ByteBuffer.wrap(bMetadata); while (buffer.remaining() >= 6) { - int id = buffer.getShort() & 0xFFFF; + final int id = buffer.getShort() & 0xFFFF; if (id == 0x0000B584) { return buffer.getFloat(); } @@ -353,7 +353,7 @@ public class OggFromWebMWriter implements Closeable { } private boolean addPacketSegment(final SimpleBlock block) { - long timestamp = block.absoluteTimeCodeNs + webmTrack.codecDelay; + final long timestamp = block.absoluteTimeCodeNs + webmTrack.codecDelay; if (timestamp >= segmentTableNextTimestamp) { return false; @@ -368,7 +368,7 @@ public class OggFromWebMWriter implements Closeable { } int available = (segmentTable.length - segmentTableSize) * 255; - boolean extra = (size % 255) == 0; + final boolean extra = (size % 255) == 0; if (extra) { // add a zero byte entry in the table @@ -396,7 +396,7 @@ public class OggFromWebMWriter implements Closeable { for (int i = 0; i < 0x100; i++) { int crc = i << 24; for (int j = 0; j < 8; j++) { - long b = crc >>> 31; + final long b = crc >>> 31; crc <<= 1; crc ^= (int) (0x100000000L - b) & 0x04c11db7; } @@ -407,7 +407,7 @@ public class OggFromWebMWriter implements Closeable { private int calcCrc32(final int initialCrc, final byte[] buffer, final int size) { int crc = initialCrc; for (int i = 0; i < size; i++) { - int reg = (crc >>> 24) & 0xff; + final int reg = (crc >>> 24) & 0xff; crc = (crc << 8) ^ crc32Table[reg ^ (buffer[i] & 0xff)]; } diff --git a/app/src/main/java/org/schabi/newpipe/streams/SrtFromTtmlWriter.java b/app/src/main/java/org/schabi/newpipe/streams/SrtFromTtmlWriter.java index eddb951e5..8cb31141b 100644 --- a/app/src/main/java/org/schabi/newpipe/streams/SrtFromTtmlWriter.java +++ b/app/src/main/java/org/schabi/newpipe/streams/SrtFromTtmlWriter.java @@ -65,23 +65,23 @@ public class SrtFromTtmlWriter { */ // parse XML - byte[] buffer = new byte[(int) ttml.available()]; + final byte[] buffer = new byte[(int) ttml.available()]; ttml.read(buffer); - Document doc = Jsoup.parse(new ByteArrayInputStream(buffer), "UTF-8", "", + final Document doc = Jsoup.parse(new ByteArrayInputStream(buffer), "UTF-8", "", Parser.xmlParser()); - StringBuilder text = new StringBuilder(128); - Elements paragraphList = doc.select("body > div > p"); + final StringBuilder text = new StringBuilder(128); + final Elements paragraphList = doc.select("body > div > p"); // check if has frames if (paragraphList.size() < 1) { return; } - for (Element paragraph : paragraphList) { + for (final Element paragraph : paragraphList) { text.setLength(0); - for (Node children : paragraph.childNodes()) { + for (final Node children : paragraph.childNodes()) { if (children instanceof TextNode) { text.append(((TextNode) children).text()); } else if (children instanceof Element @@ -94,8 +94,8 @@ public class SrtFromTtmlWriter { continue; } - String begin = getTimestamp(paragraph, "begin"); - String end = getTimestamp(paragraph, "end"); + final String begin = getTimestamp(paragraph, "begin"); + final String end = getTimestamp(paragraph, "end"); writeFrame(begin, end, text); } diff --git a/app/src/main/java/org/schabi/newpipe/streams/WebMReader.java b/app/src/main/java/org/schabi/newpipe/streams/WebMReader.java index 56cea9f2d..6e2ba8360 100644 --- a/app/src/main/java/org/schabi/newpipe/streams/WebMReader.java +++ b/app/src/main/java/org/schabi/newpipe/streams/WebMReader.java @@ -99,7 +99,7 @@ public class WebMReader { ensure(segment.ref); // WARNING: track cannot be the same or have different index in new segments - Element elem = untilElement(null, ID_SEGMENT); + final Element elem = untilElement(null, ID_SEGMENT); if (elem == null) { done = true; return null; @@ -113,7 +113,7 @@ public class WebMReader { int length = (int) parent.contentSize; long value = 0; while (length-- > 0) { - int read = stream.read(); + final int read = stream.read(); if (read == -1) { throw new EOFException(); } @@ -127,9 +127,9 @@ public class WebMReader { } private byte[] readBlob(final Element parent) throws IOException { - long length = parent.contentSize; - byte[] buffer = new byte[(int) length]; - int read = stream.read(buffer); + final long length = parent.contentSize; + final byte[] buffer = new byte[(int) length]; + final int read = stream.read(buffer); if (read < length) { throw new EOFException(); } @@ -168,7 +168,7 @@ public class WebMReader { } private Element readElement() throws IOException { - Element elem = new Element(); + final Element elem = new Element(); elem.offset = stream.position(); elem.type = (int) readEncodedNumber(); elem.contentSize = readEncodedNumber(); @@ -178,7 +178,7 @@ public class WebMReader { } private Element readElement(final int expected) throws IOException { - Element elem = readElement(); + final Element elem = readElement(); if (expected != 0 && elem.type != expected) { throw new NoSuchElementException("expected " + elementID(expected) + " found " + elementID(elem.type)); @@ -194,7 +194,7 @@ public class WebMReader { if (expected.length < 1) { return elem; } - for (int type : expected) { + for (final int type : expected) { if (elem.type == type) { return elem; } @@ -211,7 +211,7 @@ public class WebMReader { } private void ensure(final Element ref) throws IOException { - long skip = (ref.offset + ref.size) - stream.position(); + final long skip = (ref.offset + ref.size) - stream.position(); if (skip == 0) { return; @@ -249,7 +249,7 @@ public class WebMReader { private Info readInfo(final Element ref) throws IOException { Element elem; - Info info = new Info(); + final Info info = new Info(); while ((elem = untilElement(ref, ID_TIMECODE_SCALE, ID_DURATION)) != null) { switch (elem.type) { @@ -272,7 +272,7 @@ public class WebMReader { private Segment readSegment(final Element ref, final int trackLacingExpected, final boolean metadataExpected) throws IOException { - Segment obj = new Segment(ref); + final Segment obj = new Segment(ref); Element elem; while ((elem = untilElement(ref, ID_INFO, ID_TRACKS, ID_CLUSTER)) != null) { if (elem.type == ID_CLUSTER) { @@ -300,11 +300,11 @@ public class WebMReader { } private WebMTrack[] readTracks(final Element ref, final int lacingExpected) throws IOException { - ArrayList trackEntries = new ArrayList<>(2); + final ArrayList trackEntries = new ArrayList<>(2); Element elemTrackEntry; while ((elemTrackEntry = untilElement(ref, ID_TRACK_ENTRY)) != null) { - WebMTrack entry = new WebMTrack(); + final WebMTrack entry = new WebMTrack(); boolean drop = false; Element elem; while ((elem = untilElement(elemTrackEntry)) != null) { @@ -348,10 +348,10 @@ public class WebMReader { ensure(elemTrackEntry); } - WebMTrack[] entries = new WebMTrack[trackEntries.size()]; + final WebMTrack[] entries = new WebMTrack[trackEntries.size()]; trackEntries.toArray(entries); - for (WebMTrack entry : entries) { + for (final WebMTrack entry : entries) { switch (entry.trackType) { case 1: entry.kind = TrackKind.Video; @@ -369,7 +369,7 @@ public class WebMReader { } private SimpleBlock readSimpleBlock(final Element ref) throws IOException { - SimpleBlock obj = new SimpleBlock(ref); + final SimpleBlock obj = new SimpleBlock(ref); obj.trackNumber = readEncodedNumber(); obj.relativeTimeCode = stream.readShort(); obj.flags = (byte) stream.read(); @@ -385,9 +385,9 @@ public class WebMReader { } private Cluster readCluster(final Element ref) throws IOException { - Cluster obj = new Cluster(ref); + final Cluster obj = new Cluster(ref); - Element elem = untilElement(ref, ID_TIMECODE); + final Element elem = untilElement(ref, ID_TIMECODE); if (elem == null) { throw new NoSuchElementException("Cluster at " + String.valueOf(ref.offset) + " without Timecode element"); @@ -443,7 +443,7 @@ public class WebMReader { } ensure(segment.currentCluster); - Element elem = untilElement(segment.ref, ID_CLUSTER); + final Element elem = untilElement(segment.ref, ID_CLUSTER); if (elem == null) { return null; } diff --git a/app/src/main/java/org/schabi/newpipe/streams/WebMWriter.java b/app/src/main/java/org/schabi/newpipe/streams/WebMWriter.java index 02b22965d..55792d099 100644 --- a/app/src/main/java/org/schabi/newpipe/streams/WebMWriter.java +++ b/app/src/main/java/org/schabi/newpipe/streams/WebMWriter.java @@ -107,7 +107,7 @@ public class WebMWriter implements Closeable { done = true; parsed = true; - for (SharpStream src : sourceTracks) { + for (final SharpStream src : sourceTracks) { src.close(); } @@ -128,12 +128,12 @@ public class WebMWriter implements Closeable { makeEBML(out); - long offsetSegmentSizeSet = written + 5; - long offsetInfoDurationSet = written + 94; - long offsetClusterSet = written + 58; - long offsetCuesSet = written + 75; + final long offsetSegmentSizeSet = written + 5; + final long offsetInfoDurationSet = written + 94; + final long offsetClusterSet = written + 58; + final long offsetCuesSet = written + 75; - ArrayList listBuffer = new ArrayList<>(4); + final ArrayList listBuffer = new ArrayList<>(4); /* segment */ listBuffer.add(new byte[]{ @@ -141,7 +141,7 @@ public class WebMWriter implements Closeable { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00// segment content size }); - long segmentOffset = written + listBuffer.get(0).length; + final long segmentOffset = written + listBuffer.get(0).length; /* seek head */ listBuffer.add(new byte[]{ @@ -177,11 +177,11 @@ public class WebMWriter implements Closeable { dump(listBuffer, out); // reserve space for Cues element - long cueOffset = written; + final long cueOffset = written; makeEbmlVoid(out, CUE_RESERVE_SIZE, true); - int[] defaultSampleDuration = new int[infoTracks.length]; - long[] duration = new long[infoTracks.length]; + final int[] defaultSampleDuration = new int[infoTracks.length]; + final long[] duration = new long[infoTracks.length]; for (int i = 0; i < infoTracks.length; i++) { if (infoTracks[i].defaultDuration < 0) { @@ -194,9 +194,9 @@ public class WebMWriter implements Closeable { } // Select a track for the cue - int cuesForTrackId = selectTrackForCue(); + final int cuesForTrackId = selectTrackForCue(); long nextCueTime = infoTracks[cuesForTrackId].trackType == 1 ? -1 : 0; - ArrayList keyFrames = new ArrayList<>(32); + final ArrayList keyFrames = new ArrayList<>(32); int firstClusterOffset = (int) written; long currentClusterOffset = makeCluster(out, 0, 0, true); @@ -213,7 +213,7 @@ public class WebMWriter implements Closeable { blockWritten = 0; int i = 0; while (i < readers.length) { - Block bloq = getNextBlockFrom(i); + final Block bloq = getNextBlockFrom(i); if (bloq == null) { i++; continue; @@ -272,7 +272,7 @@ public class WebMWriter implements Closeable { makeCluster(out, -1, currentClusterOffset, false); - long segmentSize = written - offsetSegmentSizeSet - 7; + final long segmentSize = written - offsetSegmentSizeSet - 7; /* Segment size */ seekTo(out, offsetSegmentSizeSet); @@ -303,8 +303,8 @@ public class WebMWriter implements Closeable { short cueSize = 0; dump(new byte[]{0x1c, 0x53, (byte) 0xbb, 0x6b, 0x20, 0x00, 0x00}, out); // header size is 7 - for (KeyFrame keyFrame : keyFrames) { - int size = makeCuePoint(cuesForTrackId, keyFrame, outBuffer); + for (final KeyFrame keyFrame : keyFrames) { + final int size = makeCuePoint(cuesForTrackId, keyFrame, outBuffer); if ((cueSize + size + 7 + MINIMUM_EBML_VOID_SIZE) > CUE_RESERVE_SIZE) { break; // no space left @@ -323,7 +323,7 @@ public class WebMWriter implements Closeable { /* seek head, seek for cues element */ writeInt(out, offsetCuesSet, (int) (cueOffset - segmentOffset)); - for (ClusterInfo cluster : clustersOffsetsSizes) { + for (final ClusterInfo cluster : clustersOffsetsSizes) { writeInt(out, cluster.offset, cluster.size | 0x10000000); } } @@ -344,13 +344,13 @@ public class WebMWriter implements Closeable { } } - SimpleBlock res = readersCluster[internalTrackId].getNextSimpleBlock(); + final SimpleBlock res = readersCluster[internalTrackId].getNextSimpleBlock(); if (res == null) { readersCluster[internalTrackId] = null; return new Block(); // fake block to indicate the end of the cluster } - Block bloq = new Block(); + final Block bloq = new Block(); bloq.data = res.data; bloq.dataSize = res.dataSize; bloq.trackNumber = internalTrackId; @@ -384,13 +384,13 @@ public class WebMWriter implements Closeable { private void writeBlock(final SharpStream stream, final Block bloq, final long clusterTimecode) throws IOException { - long relativeTimeCode = bloq.absoluteTimecode - clusterTimecode; + final long relativeTimeCode = bloq.absoluteTimecode - clusterTimecode; if (relativeTimeCode < Short.MIN_VALUE || relativeTimeCode > Short.MAX_VALUE) { throw new IndexOutOfBoundsException("SimpleBlock timecode overflow."); } - ArrayList listBuffer = new ArrayList<>(5); + final ArrayList listBuffer = new ArrayList<>(5); listBuffer.add(new byte[]{(byte) 0xa3}); listBuffer.add(null); // block size listBuffer.add(encode(bloq.trackNumber + 1, false)); @@ -458,7 +458,7 @@ public class WebMWriter implements Closeable { } private ArrayList makeTracks() { - ArrayList buffer = new ArrayList<>(1); + final ArrayList buffer = new ArrayList<>(1); buffer.add(new byte[]{0x16, 0x54, (byte) 0xae, 0x6b}); buffer.add(null); @@ -470,8 +470,8 @@ public class WebMWriter implements Closeable { } private ArrayList makeTrackEntry(final int internalTrackId, final WebMTrack track) { - byte[] id = encode(internalTrackId + 1, true); - ArrayList buffer = new ArrayList<>(12); + final byte[] id = encode(internalTrackId + 1, true); + final ArrayList buffer = new ArrayList<>(12); /* track */ buffer.add(new byte[]{(byte) 0xae}); @@ -536,7 +536,7 @@ public class WebMWriter implements Closeable { private int makeCuePoint(final int internalTrackId, final KeyFrame keyFrame, final byte[] buffer) { - ArrayList cue = new ArrayList<>(5); + final ArrayList cue = new ArrayList<>(5); /* CuePoint */ cue.add(new byte[]{(byte) 0xbb}); @@ -552,7 +552,7 @@ public class WebMWriter implements Closeable { int size = 0; lengthFor(cue); - for (byte[] buff : cue) { + for (final byte[] buff : cue) { System.arraycopy(buff, 0, buffer, size, buff.length); size += buff.length; } @@ -562,7 +562,7 @@ public class WebMWriter implements Closeable { private ArrayList makeCueTrackPosition(final int internalTrackId, final KeyFrame keyFrame) { - ArrayList buffer = new ArrayList<>(8); + final ArrayList buffer = new ArrayList<>(8); /* CueTrackPositions */ buffer.add(new byte[]{(byte) 0xb7}); @@ -598,7 +598,7 @@ public class WebMWriter implements Closeable { if (wipe) { size -= 4; while (size > 0) { - int write = Math.min(size, outBuffer.length); + final int write = Math.min(size, outBuffer.length); dump(outBuffer, write, out); size -= write; } @@ -617,7 +617,7 @@ public class WebMWriter implements Closeable { private void dump(final ArrayList buffers, final SharpStream stream) throws IOException { - for (byte[] buffer : buffers) { + for (final byte[] buffer : buffers) { stream.write(buffer); written += buffer.length; } @@ -649,9 +649,9 @@ public class WebMWriter implements Closeable { length++; } - int offset = withLength ? 1 : 0; - byte[] buffer = new byte[offset + length]; - long marker = (long) Math.floor((length - 1f) / 8f); + final int offset = withLength ? 1 : 0; + final byte[] buffer = new byte[offset + length]; + final long marker = (long) Math.floor((length - 1f) / 8f); int shift = 0; for (int i = length - 1; i >= 0; i--, shift += 8) { @@ -670,10 +670,9 @@ public class WebMWriter implements Closeable { } private ArrayList encode(final String value) { - byte[] str; - str = value.getBytes(StandardCharsets.UTF_8); // or use "utf-8" + final byte[] str = value.getBytes(StandardCharsets.UTF_8); // or use "utf-8" - ArrayList buffer = new ArrayList<>(2); + final ArrayList buffer = new ArrayList<>(2); buffer.add(encode(str.length, false)); buffer.add(str); @@ -700,7 +699,7 @@ public class WebMWriter implements Closeable { } } - int kind; + final int kind; if (audioTracks == infoTracks.length) { kind = 2; } else if (videoTracks == infoTracks.length) { diff --git a/app/src/main/java/org/schabi/newpipe/util/AnimationUtils.java b/app/src/main/java/org/schabi/newpipe/util/AnimationUtils.java index 4fa14ed01..9220891a9 100644 --- a/app/src/main/java/org/schabi/newpipe/util/AnimationUtils.java +++ b/app/src/main/java/org/schabi/newpipe/util/AnimationUtils.java @@ -84,11 +84,11 @@ public final class AnimationUtils { String id; try { id = view.getResources().getResourceEntryName(view.getId()); - } catch (Exception e) { + } catch (final Exception e) { id = view.getId() + ""; } - String msg = String.format("%8s → [%s:%s] [%s %s:%s] execOnEnd=%s", enterOrExit, + final String msg = String.format("%8s → [%s:%s] [%s %s:%s] execOnEnd=%s", enterOrExit, view.getClass().getSimpleName(), id, animationType, duration, delay, execOnEnd); Log.d(TAG, "animateView()" + msg); } @@ -158,7 +158,7 @@ public final class AnimationUtils { } final int[][] empty = new int[][]{new int[0]}; - ValueAnimator viewPropertyAnimator = ValueAnimator + final ValueAnimator viewPropertyAnimator = ValueAnimator .ofObject(new ArgbEvaluator(), colorStart, colorEnd); viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator()); viewPropertyAnimator.setDuration(duration); @@ -201,7 +201,7 @@ public final class AnimationUtils { + "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"); } - ValueAnimator viewPropertyAnimator = ValueAnimator + final ValueAnimator viewPropertyAnimator = ValueAnimator .ofObject(new ArgbEvaluator(), colorStart, colorEnd); viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator()); viewPropertyAnimator.setDuration(duration); @@ -233,7 +233,7 @@ public final class AnimationUtils { + "from " + height + " to → " + targetHeight + " in: " + view); } - ValueAnimator animator = ValueAnimator.ofFloat(height, targetHeight); + final ValueAnimator animator = ValueAnimator.ofFloat(height, targetHeight); animator.setInterpolator(new FastOutSlowInInterpolator()); animator.setDuration(duration); animator.addUpdateListener(animation -> { @@ -462,7 +462,7 @@ public final class AnimationUtils { public static void slideUp(final View view, final long duration, final long delay, @FloatRange(from = 0.0f, to = 1.0f) final float translationPercent) { - int translationY = (int) (view.getResources().getDisplayMetrics().heightPixels + final int translationY = (int) (view.getResources().getDisplayMetrics().heightPixels * (translationPercent)); view.animate().setListener(null).cancel(); diff --git a/app/src/main/java/org/schabi/newpipe/util/BitmapUtils.java b/app/src/main/java/org/schabi/newpipe/util/BitmapUtils.java index 5b1c46372..b6f1eaf49 100644 --- a/app/src/main/java/org/schabi/newpipe/util/BitmapUtils.java +++ b/app/src/main/java/org/schabi/newpipe/util/BitmapUtils.java @@ -14,14 +14,14 @@ public final class BitmapUtils { return null; } - float sourceWidth = inputBitmap.getWidth(); - float sourceHeight = inputBitmap.getHeight(); + final float sourceWidth = inputBitmap.getWidth(); + final float sourceHeight = inputBitmap.getHeight(); - float xScale = newWidth / sourceWidth; - float yScale = newHeight / sourceHeight; + final float xScale = newWidth / sourceWidth; + final float yScale = newHeight / sourceHeight; - float newXScale; - float newYScale; + final float newXScale; + final float newYScale; if (yScale > xScale) { newXScale = xScale / yScale; @@ -31,15 +31,14 @@ public final class BitmapUtils { newYScale = yScale / xScale; } - float scaledWidth = newXScale * sourceWidth; - float scaledHeight = newYScale * sourceHeight; + final float scaledWidth = newXScale * sourceWidth; + final float scaledHeight = newYScale * sourceHeight; - int left = (int) ((sourceWidth - scaledWidth) / 2); - int top = (int) ((sourceHeight - scaledHeight) / 2); - int width = (int) scaledWidth; - int height = (int) scaledHeight; + final int left = (int) ((sourceWidth - scaledWidth) / 2); + final int top = (int) ((sourceHeight - scaledHeight) / 2); + final int width = (int) scaledWidth; + final int height = (int) scaledHeight; return Bitmap.createBitmap(inputBitmap, left, top, width, height); } - } diff --git a/app/src/main/java/org/schabi/newpipe/util/CommentTextOnTouchListener.java b/app/src/main/java/org/schabi/newpipe/util/CommentTextOnTouchListener.java index 770592537..cf347e7c4 100644 --- a/app/src/main/java/org/schabi/newpipe/util/CommentTextOnTouchListener.java +++ b/app/src/main/java/org/schabi/newpipe/util/CommentTextOnTouchListener.java @@ -37,12 +37,12 @@ public class CommentTextOnTouchListener implements View.OnTouchListener { if (!(v instanceof TextView)) { return false; } - TextView widget = (TextView) v; - Object text = widget.getText(); + final TextView widget = (TextView) v; + final Object text = widget.getText(); if (text instanceof Spanned) { - Spannable buffer = (Spannable) text; + final Spannable buffer = (Spannable) text; - int action = event.getAction(); + final int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { @@ -55,11 +55,11 @@ public class CommentTextOnTouchListener implements View.OnTouchListener { x += widget.getScrollX(); y += widget.getScrollY(); - Layout layout = widget.getLayout(); - int line = layout.getLineForVertical(y); - int off = layout.getOffsetForHorizontal(line, x); + final Layout layout = widget.getLayout(); + final int line = layout.getLineForVertical(y); + final int off = layout.getOffsetForHorizontal(line, x); - ClickableSpan[] link = buffer.getSpans(off, off, + final ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { @@ -86,17 +86,17 @@ public class CommentTextOnTouchListener implements View.OnTouchListener { private boolean handleUrl(final Context context, final URLSpan urlSpan) { String url = urlSpan.getURL(); int seconds = -1; - Matcher matcher = TIMESTAMP_PATTERN.matcher(url); + final Matcher matcher = TIMESTAMP_PATTERN.matcher(url); if (matcher.matches()) { url = matcher.group(1); seconds = Integer.parseInt(matcher.group(2)); } - StreamingService service; - StreamingService.LinkType linkType; + final StreamingService service; + final StreamingService.LinkType linkType; try { service = NewPipe.getServiceByUrl(url); linkType = service.getLinkTypeByUrl(url); - } catch (ExtractionException e) { + } catch (final ExtractionException e) { return false; } if (linkType == StreamingService.LinkType.NONE) { @@ -112,18 +112,20 @@ public class CommentTextOnTouchListener implements View.OnTouchListener { private boolean playOnPopup(final Context context, final String url, final StreamingService service, final int seconds) { - LinkHandlerFactory factory = service.getStreamLHFactory(); - String cleanUrl = null; + final LinkHandlerFactory factory = service.getStreamLHFactory(); + final String cleanUrl; try { cleanUrl = factory.getUrl(factory.getId(url)); - } catch (ParsingException e) { + } catch (final ParsingException e) { return false; } - Single single = ExtractorHelper.getStreamInfo(service.getServiceId(), cleanUrl, false); + final Single single + = ExtractorHelper.getStreamInfo(service.getServiceId(), cleanUrl, false); single.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(info -> { - PlayQueue playQueue = new SinglePlayQueue((StreamInfo) info, seconds * 1000); + final PlayQueue playQueue + = new SinglePlayQueue((StreamInfo) info, seconds * 1000); NavigationHelper.playOnPopupPlayer(context, playQueue, false); }); return true; diff --git a/app/src/main/java/org/schabi/newpipe/util/CookieUtils.java b/app/src/main/java/org/schabi/newpipe/util/CookieUtils.java index d8b81b4ce..d970ec472 100644 --- a/app/src/main/java/org/schabi/newpipe/util/CookieUtils.java +++ b/app/src/main/java/org/schabi/newpipe/util/CookieUtils.java @@ -12,8 +12,8 @@ public final class CookieUtils { } public static String concatCookies(final Collection cookieStrings) { - Set cookieSet = new HashSet<>(); - for (String cookies : cookieStrings) { + final Set cookieSet = new HashSet<>(); + for (final String cookies : cookieStrings) { cookieSet.addAll(splitCookies(cookies)); } return TextUtils.join("; ", cookieSet).trim(); diff --git a/app/src/main/java/org/schabi/newpipe/util/DeviceUtils.java b/app/src/main/java/org/schabi/newpipe/util/DeviceUtils.java index 0afa0663c..d852c2296 100644 --- a/app/src/main/java/org/schabi/newpipe/util/DeviceUtils.java +++ b/app/src/main/java/org/schabi/newpipe/util/DeviceUtils.java @@ -27,7 +27,7 @@ public final class DeviceUtils { return isTV; } - PackageManager pm = App.getApp().getPackageManager(); + final PackageManager pm = App.getApp().getPackageManager(); // from doc: https://developer.android.com/training/tv/start/hardware.html#runtime-check boolean isTv = ((UiModeManager) context.getSystemService(UI_MODE_SERVICE)) @@ -37,7 +37,8 @@ public final class DeviceUtils { // from https://stackoverflow.com/a/58932366 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - boolean isBatteryAbsent = ((BatteryManager) context.getSystemService(BATTERY_SERVICE)) + final boolean isBatteryAbsent + = ((BatteryManager) context.getSystemService(BATTERY_SERVICE)) .getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) == 0; isTv = isTv || (isBatteryAbsent && !pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN) diff --git a/app/src/main/java/org/schabi/newpipe/util/ExtractorHelper.java b/app/src/main/java/org/schabi/newpipe/util/ExtractorHelper.java index 9b8b2494e..a1a73d7ac 100644 --- a/app/src/main/java/org/schabi/newpipe/util/ExtractorHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/ExtractorHelper.java @@ -101,7 +101,7 @@ public final class ExtractorHelper { public static Single> suggestionsFor(final int serviceId, final String query) { checkServiceId(serviceId); return Single.fromCallable(() -> { - SuggestionExtractor extractor = NewPipe.getService(serviceId) + final SuggestionExtractor extractor = NewPipe.getService(serviceId) .getSuggestionExtractor(); return extractor != null ? extractor.suggestionList(query) @@ -212,10 +212,10 @@ public final class ExtractorHelper { final InfoItem.InfoType infoType, final Single loadFromNetwork) { checkServiceId(serviceId); - Single actualLoadFromNetwork = loadFromNetwork + final Single actualLoadFromNetwork = loadFromNetwork .doOnSuccess(info -> CACHE.putInfo(serviceId, url, info, infoType)); - Single load; + final Single load; if (forceLoad) { CACHE.removeInfo(serviceId, url, infoType); load = actualLoadFromNetwork; @@ -243,7 +243,7 @@ public final class ExtractorHelper { checkServiceId(serviceId); return Maybe.defer(() -> { //noinspection unchecked - I info = (I) CACHE.getFromKey(serviceId, url, infoType); + final I info = (I) CACHE.getFromKey(serviceId, url, infoType); if (MainActivity.DEBUG) { Log.d(TAG, "loadFromCache() called, info > " + info); } @@ -283,7 +283,7 @@ public final class ExtractorHelper { if (exception instanceof ReCaptchaException) { Toast.makeText(context, R.string.recaptcha_request_toast, Toast.LENGTH_LONG).show(); // Starting ReCaptcha Challenge Activity - Intent intent = new Intent(context, ReCaptchaActivity.class); + final Intent intent = new Intent(context, ReCaptchaActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else if (ExceptionUtils.isNetworkRelated(exception)) { @@ -293,7 +293,7 @@ public final class ExtractorHelper { } else if (exception instanceof ContentNotSupportedException) { Toast.makeText(context, R.string.content_not_supported, Toast.LENGTH_LONG).show(); } else { - int errorId = exception instanceof YoutubeStreamExtractor.DecryptException + final int errorId = exception instanceof YoutubeStreamExtractor.DecryptException ? R.string.youtube_signature_decryption_error : exception instanceof ParsingException ? R.string.parsing_error : R.string.general_error; diff --git a/app/src/main/java/org/schabi/newpipe/util/FilenameUtils.java b/app/src/main/java/org/schabi/newpipe/util/FilenameUtils.java index 3179662ba..dda01b60c 100644 --- a/app/src/main/java/org/schabi/newpipe/util/FilenameUtils.java +++ b/app/src/main/java/org/schabi/newpipe/util/FilenameUtils.java @@ -22,7 +22,7 @@ public final class FilenameUtils { * @return the filename */ public static String createFilename(final Context context, final String title) { - SharedPreferences sharedPreferences = PreferenceManager + final SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); final String charsetLd = context.getString(R.string.charset_letters_and_digits_value); @@ -48,7 +48,7 @@ public final class FilenameUtils { charset = selectedCharset; // Is the user using a custom charset? } - Pattern pattern = Pattern.compile(charset); + final Pattern pattern = Pattern.compile(charset); return createFilename(title, pattern, replacementChar); } diff --git a/app/src/main/java/org/schabi/newpipe/util/InfoCache.java b/app/src/main/java/org/schabi/newpipe/util/InfoCache.java index 035416dcd..a07f05828 100644 --- a/app/src/main/java/org/schabi/newpipe/util/InfoCache.java +++ b/app/src/main/java/org/schabi/newpipe/util/InfoCache.java @@ -59,7 +59,7 @@ public final class InfoCache { } private static void removeStaleCache() { - for (Map.Entry entry : InfoCache.LRU_CACHE.snapshot().entrySet()) { + for (final Map.Entry entry : InfoCache.LRU_CACHE.snapshot().entrySet()) { final CacheData data = entry.getValue(); if (data != null && data.isExpired()) { InfoCache.LRU_CACHE.remove(entry.getKey()); diff --git a/app/src/main/java/org/schabi/newpipe/util/LayoutManagerSmoothScroller.java b/app/src/main/java/org/schabi/newpipe/util/LayoutManagerSmoothScroller.java index 2ca128409..fd50d2edb 100644 --- a/app/src/main/java/org/schabi/newpipe/util/LayoutManagerSmoothScroller.java +++ b/app/src/main/java/org/schabi/newpipe/util/LayoutManagerSmoothScroller.java @@ -20,7 +20,7 @@ public class LayoutManagerSmoothScroller extends LinearLayoutManager { @Override public void smoothScrollToPosition(final RecyclerView recyclerView, final RecyclerView.State state, final int position) { - RecyclerView.SmoothScroller smoothScroller + final RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext()); smoothScroller.setTargetPosition(position); startSmoothScroll(smoothScroller); diff --git a/app/src/main/java/org/schabi/newpipe/util/ListHelper.java b/app/src/main/java/org/schabi/newpipe/util/ListHelper.java index 47486ae49..be0630cac 100644 --- a/app/src/main/java/org/schabi/newpipe/util/ListHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/ListHelper.java @@ -44,7 +44,7 @@ public final class ListHelper { */ public static int getDefaultResolutionIndex(final Context context, final List videoStreams) { - String defaultResolution = computeDefaultResolution(context, + final String defaultResolution = computeDefaultResolution(context, R.string.default_resolution_key, R.string.default_resolution_value); return getDefaultResolutionWithDefaultFormat(context, defaultResolution, videoStreams); } @@ -70,7 +70,7 @@ public final class ListHelper { */ public static int getPopupDefaultResolutionIndex(final Context context, final List videoStreams) { - String defaultResolution = computeDefaultResolution(context, + final String defaultResolution = computeDefaultResolution(context, R.string.default_popup_resolution_key, R.string.default_popup_resolution_value); return getDefaultResolutionWithDefaultFormat(context, defaultResolution, videoStreams); } @@ -90,8 +90,8 @@ public final class ListHelper { public static int getDefaultAudioFormat(final Context context, final List audioStreams) { - MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_audio_format_key, - R.string.default_audio_format_value); + final MediaFormat defaultFormat = getDefaultFormat(context, + R.string.default_audio_format_key, R.string.default_audio_format_value); // If the user has chosen to limit resolution to conserve mobile data // usage then we should also limit our audio usage. @@ -117,12 +117,13 @@ public final class ListHelper { final List videoOnlyStreams, final boolean ascendingOrder) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences preferences + = PreferenceManager.getDefaultSharedPreferences(context); - boolean showHigherResolutions = preferences.getBoolean( + final boolean showHigherResolutions = preferences.getBoolean( context.getString(R.string.show_higher_resolutions_key), false); - MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_video_format_key, - R.string.default_video_format_value); + final MediaFormat defaultFormat = getDefaultFormat(context, + R.string.default_video_format_key, R.string.default_video_format_value); return getSortedStreamVideosList(defaultFormat, showHigherResolutions, videoStreams, videoOnlyStreams, ascendingOrder); @@ -134,14 +135,15 @@ public final class ListHelper { private static String computeDefaultResolution(final Context context, final int key, final int value) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences preferences + = PreferenceManager.getDefaultSharedPreferences(context); // Load the prefered resolution otherwise the best available String resolution = preferences != null ? preferences.getString(context.getString(key), context.getString(value)) : context.getString(R.string.best_resolution_key); - String maxResolution = getResolutionLimit(context); + final String maxResolution = getResolutionLimit(context); if (maxResolution != null && (resolution.equals(context.getString(R.string.best_resolution_key)) || compareVideoStreamResolution(maxResolution, resolution) < 1)) { @@ -173,7 +175,7 @@ public final class ListHelper { return 0; } - int defaultStreamIndex + final int defaultStreamIndex = getVideoStreamIndex(defaultResolution, defaultFormat, videoStreams); // this is actually an error, @@ -200,11 +202,11 @@ public final class ListHelper { final List videoStreams, final List videoOnlyStreams, final boolean ascendingOrder) { - ArrayList retList = new ArrayList<>(); - HashMap hashMap = new HashMap<>(); + final ArrayList retList = new ArrayList<>(); + final HashMap hashMap = new HashMap<>(); if (videoOnlyStreams != null) { - for (VideoStream stream : videoOnlyStreams) { + for (final VideoStream stream : videoOnlyStreams) { if (!showHigherResolutions && HIGH_RESOLUTION_LIST.contains(stream.getResolution())) { continue; @@ -213,7 +215,7 @@ public final class ListHelper { } } if (videoStreams != null) { - for (VideoStream stream : videoStreams) { + for (final VideoStream stream : videoStreams) { if (!showHigherResolutions && HIGH_RESOLUTION_LIST.contains(stream.getResolution())) { continue; @@ -223,12 +225,12 @@ public final class ListHelper { } // Add all to the hashmap - for (VideoStream videoStream : retList) { + for (final VideoStream videoStream : retList) { hashMap.put(videoStream.getResolution(), videoStream); } // Override the values when the key == resolution, with the defaultFormat - for (VideoStream videoStream : retList) { + for (final VideoStream videoStream : retList) { if (videoStream.getFormat() == defaultFormat) { hashMap.put(videoStream.getResolution(), videoStream); } @@ -262,7 +264,7 @@ public final class ListHelper { private static void sortStreamList(final List videoStreams, final boolean ascendingOrder) { Collections.sort(videoStreams, (o1, o2) -> { - int result = compareVideoStreamResolution(o1, o2); + final int result = compareVideoStreamResolution(o1, o2); return result == 0 ? 0 : (ascendingOrder ? result : -result); }); } @@ -282,7 +284,7 @@ public final class ListHelper { while (result == -1) { AudioStream prevStream = null; for (int idx = 0; idx < audioStreams.size(); idx++) { - AudioStream stream = audioStreams.get(idx); + final AudioStream stream = audioStreams.get(idx); if ((format == null || stream.getFormat() == format) && (prevStream == null || compareAudioStreamBitrate(prevStream, stream, AUDIO_FORMAT_QUALITY_RANKING) < 0)) { @@ -314,7 +316,7 @@ public final class ListHelper { while (result == -1) { AudioStream prevStream = null; for (int idx = 0; idx < audioStreams.size(); idx++) { - AudioStream stream = audioStreams.get(idx); + final AudioStream stream = audioStreams.get(idx); if ((format == null || stream.getFormat() == format) && (prevStream == null || compareAudioStreamBitrate(prevStream, stream, AUDIO_FORMAT_EFFICIENCY_RANKING) > 0)) { @@ -357,12 +359,13 @@ public final class ListHelper { int resMatchOnlyIndex = -1; int resMatchOnlyNoRefreshIndex = -1; int lowerResMatchNoRefreshIndex = -1; - String targetResolutionNoRefresh = targetResolution.replaceAll("p\\d+$", "p"); + final String targetResolutionNoRefresh = targetResolution.replaceAll("p\\d+$", "p"); for (int idx = 0; idx < videoStreams.size(); idx++) { - MediaFormat format = targetFormat == null ? null : videoStreams.get(idx).getFormat(); - String resolution = videoStreams.get(idx).getResolution(); - String resolutionNoRefresh = resolution.replaceAll("p\\d+$", "p"); + final MediaFormat format + = targetFormat == null ? null : videoStreams.get(idx).getFormat(); + final String resolution = videoStreams.get(idx).getResolution(); + final String resolutionNoRefresh = resolution.replaceAll("p\\d+$", "p"); if (format == targetFormat && resolution.equals(targetResolution)) { fullMatchIndex = idx; @@ -414,8 +417,8 @@ public final class ListHelper { private static int getDefaultResolutionWithDefaultFormat(final Context context, final String defaultResolution, final List videoStreams) { - MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_video_format_key, - R.string.default_video_format_value); + final MediaFormat defaultFormat = getDefaultFormat(context, + R.string.default_video_format_key, R.string.default_video_format_value); return getDefaultResolutionIndex(defaultResolution, context.getString(R.string.best_resolution_key), defaultFormat, videoStreams); } @@ -423,10 +426,11 @@ public final class ListHelper { private static MediaFormat getDefaultFormat(final Context context, @StringRes final int defaultFormatKey, @StringRes final int defaultFormatValueKey) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences preferences + = PreferenceManager.getDefaultSharedPreferences(context); - String defaultFormat = context.getString(defaultFormatValueKey); - String defaultFormatString = preferences.getString( + final String defaultFormat = context.getString(defaultFormatValueKey); + final String defaultFormatString = preferences.getString( context.getString(defaultFormatKey), defaultFormat); MediaFormat defaultMediaFormat = getMediaFormatFromKey(context, defaultFormatString); @@ -479,9 +483,9 @@ public final class ListHelper { } private static int compareVideoStreamResolution(final String r1, final String r2) { - int res1 = Integer.parseInt(r1.replaceAll("0p\\d+$", "1") + final int res1 = Integer.parseInt(r1.replaceAll("0p\\d+$", "1") .replaceAll("[^\\d.]", "")); - int res2 = Integer.parseInt(r2.replaceAll("0p\\d+$", "1") + final int res2 = Integer.parseInt(r2.replaceAll("0p\\d+$", "1") .replaceAll("[^\\d.]", "")); return res1 - res2; } @@ -496,7 +500,7 @@ public final class ListHelper { return 1; } - int resComp = compareVideoStreamResolution(streamA.getResolution(), + final int resComp = compareVideoStreamResolution(streamA.getResolution(), streamB.getResolution()); if (resComp != 0) { return resComp; @@ -521,9 +525,10 @@ public final class ListHelper { private static String getResolutionLimit(final Context context) { String resolutionLimit = null; if (isMeteredNetwork(context)) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - String defValue = context.getString(R.string.limit_data_usage_none_key); - String value = preferences.getString( + final SharedPreferences preferences + = PreferenceManager.getDefaultSharedPreferences(context); + final String defValue = context.getString(R.string.limit_data_usage_none_key); + final String value = preferences.getString( context.getString(R.string.limit_mobile_data_usage_key), defValue); resolutionLimit = defValue.equals(value) ? null : value; } @@ -537,7 +542,7 @@ public final class ListHelper { * @return {@code true} if connected to a metered network */ public static boolean isMeteredNetwork(final Context context) { - ConnectivityManager manager + final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (manager == null || manager.getActiveNetworkInfo() == null) { return false; diff --git a/app/src/main/java/org/schabi/newpipe/util/Localization.java b/app/src/main/java/org/schabi/newpipe/util/Localization.java index 7e336f02d..3642216ff 100644 --- a/app/src/main/java/org/schabi/newpipe/util/Localization.java +++ b/app/src/main/java/org/schabi/newpipe/util/Localization.java @@ -110,19 +110,19 @@ public final class Localization { } public static Locale getPreferredLocale(final Context context) { - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); - String languageCode = sp.getString(context.getString(R.string.content_language_key), + final String languageCode = sp.getString(context.getString(R.string.content_language_key), context.getString(R.string.default_localization_key)); try { if (languageCode.length() == 2) { return new Locale(languageCode); } else if (languageCode.contains("_")) { - String country = languageCode.substring(languageCode.indexOf("_")); + final String country = languageCode.substring(languageCode.indexOf("_")); return new Locale(languageCode.substring(0, 2), country); } - } catch (Exception ignored) { + } catch (final Exception ignored) { } return Locale.getDefault(); @@ -133,7 +133,7 @@ public final class Localization { } public static String localizeNumber(final Context context, final double number) { - NumberFormat nf = NumberFormat.getInstance(getAppLocale(context)); + final NumberFormat nf = NumberFormat.getInstance(getAppLocale(context)); return nf.format(number); } @@ -184,7 +184,7 @@ public final class Localization { } public static String shortCount(final Context context, final long count) { - double value = (double) count; + final double value = (double) count; if (count >= 1000000000) { return localizeNumber(context, round(value / 1000000000, 1)) + context.getString(R.string.short_billion); @@ -230,8 +230,8 @@ public final class Localization { // is not the responsibility of this method handle long numbers // (it probably will fall in the "other" category, // or some language have some specific rule... then we have to change it) - int safeCount = count > Integer.MAX_VALUE ? Integer.MAX_VALUE : count < Integer.MIN_VALUE - ? Integer.MIN_VALUE : (int) count; + final int safeCount = count > Integer.MAX_VALUE ? Integer.MAX_VALUE + : count < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int) count; return context.getResources().getQuantityString(pluralId, safeCount, formattedCount); } @@ -305,30 +305,30 @@ public final class Localization { } public static String relativeTime(final Calendar calendarTime) { - String time = getPrettyTime().formatUnrounded(calendarTime); + final String time = getPrettyTime().formatUnrounded(calendarTime); return time.startsWith("-") ? time.substring(1) : time; //workaround fix for russian showing -1 day ago, -19hrs ago… } private static void changeAppLanguage(final Locale loc, final Resources res) { - DisplayMetrics dm = res.getDisplayMetrics(); - Configuration conf = res.getConfiguration(); + final DisplayMetrics dm = res.getDisplayMetrics(); + final Configuration conf = res.getConfiguration(); conf.setLocale(loc); res.updateConfiguration(conf, dm); } public static Locale getAppLocale(final Context context) { - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String lang = prefs.getString(context.getString(R.string.app_language_key), "en"); - Locale loc; + final Locale loc; if (lang.equals(context.getString(R.string.default_localization_key))) { loc = Locale.getDefault(); } else if (lang.matches(".*-.*")) { //to differentiate different versions of the language //for example, pt (portuguese in Portugal) and pt-br (portuguese in Brazil) - String[] localisation = lang.split("-"); + final String[] localisation = lang.split("-"); lang = localisation[0]; - String country = localisation[1]; + final String country = localisation[1]; loc = new Locale(lang, country); } else { loc = new Locale(lang); diff --git a/app/src/main/java/org/schabi/newpipe/util/NavigationHelper.java b/app/src/main/java/org/schabi/newpipe/util/NavigationHelper.java index 0c8f83474..96dfc1925 100644 --- a/app/src/main/java/org/schabi/newpipe/util/NavigationHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/NavigationHelper.java @@ -74,7 +74,7 @@ public final class NavigationHelper { @NonNull final PlayQueue playQueue, @Nullable final String quality, final boolean resumePlayback) { - Intent intent = new Intent(context, targetClazz); + final Intent intent = new Intent(context, targetClazz); final String cacheKey = SerializedCache.getInstance().put(playQueue, PlayQueue.class); if (cacheKey != null) { @@ -243,27 +243,27 @@ public final class NavigationHelper { return; } - AudioStream audioStream = info.getAudioStreams().get(index); + final AudioStream audioStream = info.getAudioStreams().get(index); playOnExternalPlayer(context, info.getName(), info.getUploaderName(), audioStream); } public static void playOnExternalVideoPlayer(final Context context, final StreamInfo info) { - ArrayList videoStreamsList = new ArrayList<>( + final ArrayList videoStreamsList = new ArrayList<>( ListHelper.getSortedStreamVideosList(context, info.getVideoStreams(), null, false)); - int index = ListHelper.getDefaultResolutionIndex(context, videoStreamsList); + final int index = ListHelper.getDefaultResolutionIndex(context, videoStreamsList); if (index == -1) { Toast.makeText(context, R.string.video_streams_empty, Toast.LENGTH_SHORT).show(); return; } - VideoStream videoStream = videoStreamsList.get(index); + final VideoStream videoStream = videoStreamsList.get(index); playOnExternalPlayer(context, info.getName(), info.getUploaderName(), videoStream); } public static void playOnExternalPlayer(final Context context, final String name, final String artist, final Stream stream) { - Intent intent = new Intent(); + final Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(stream.getUrl()), stream.getFormat().getMimeType()); intent.putExtra(Intent.EXTRA_TITLE, name); @@ -282,7 +282,7 @@ public final class NavigationHelper { new AlertDialog.Builder(context) .setMessage(R.string.no_player_found) .setPositiveButton(R.string.install, (dialog, which) -> { - Intent i = new Intent(); + final Intent i = new Intent(); i.setAction(Intent.ACTION_VIEW); i.setData(Uri.parse(context.getString(R.string.fdroid_vlc_url))); context.startActivity(i); @@ -313,7 +313,7 @@ public final class NavigationHelper { public static void gotoMainFragment(final FragmentManager fragmentManager) { ImageLoader.getInstance().clearMemoryCache(); - boolean popped = fragmentManager.popBackStackImmediate(MAIN_FRAGMENT_TAG, 0); + final boolean popped = fragmentManager.popBackStackImmediate(MAIN_FRAGMENT_TAG, 0); if (!popped) { openMainFragment(fragmentManager); } @@ -483,7 +483,7 @@ public final class NavigationHelper { public static void openSearch(final Context context, final int serviceId, final String searchString) { - Intent mIntent = new Intent(context, MainActivity.class); + final Intent mIntent = new Intent(context, MainActivity.class); mIntent.putExtra(Constants.KEY_SERVICE_ID, serviceId); mIntent.putExtra(Constants.KEY_SEARCH_STRING, searchString); mIntent.putExtra(Constants.KEY_OPEN_SEARCH, true); @@ -496,7 +496,7 @@ public final class NavigationHelper { public static void openChannel(final Context context, final int serviceId, final String url, final String name) { - Intent openIntent = getOpenIntent(context, url, serviceId, + final Intent openIntent = getOpenIntent(context, url, serviceId, StreamingService.LinkType.CHANNEL); if (name != null && !name.isEmpty()) { openIntent.putExtra(Constants.KEY_TITLE, name); @@ -511,7 +511,7 @@ public final class NavigationHelper { public static void openVideoDetail(final Context context, final int serviceId, final String url, final String title) { - Intent openIntent = getOpenIntent(context, url, serviceId, + final Intent openIntent = getOpenIntent(context, url, serviceId, StreamingService.LinkType.STREAM); if (title != null && !title.isEmpty()) { openIntent.putExtra(Constants.KEY_TITLE, title); @@ -520,26 +520,26 @@ public final class NavigationHelper { } public static void openMainActivity(final Context context) { - Intent mIntent = new Intent(context, MainActivity.class); + final Intent mIntent = new Intent(context, MainActivity.class); mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(mIntent); } public static void openRouterActivity(final Context context, final String url) { - Intent mIntent = new Intent(context, RouterActivity.class); + final Intent mIntent = new Intent(context, RouterActivity.class); mIntent.setData(Uri.parse(url)); mIntent.putExtra(RouterActivity.INTERNAL_ROUTE_KEY, true); context.startActivity(mIntent); } public static void openAbout(final Context context) { - Intent intent = new Intent(context, AboutActivity.class); + final Intent intent = new Intent(context, AboutActivity.class); context.startActivity(intent); } public static void openSettings(final Context context) { - Intent intent = new Intent(context, SettingsActivity.class); + final Intent intent = new Intent(context, SettingsActivity.class); context.startActivity(intent); } @@ -548,7 +548,7 @@ public final class NavigationHelper { activity, PermissionHelper.DOWNLOADS_REQUEST_CODE)) { return false; } - Intent intent = new Intent(activity, DownloadActivity.class); + final Intent intent = new Intent(activity, DownloadActivity.class); activity.startActivity(intent); return true; } @@ -559,7 +559,7 @@ public final class NavigationHelper { private static Intent getServicePlayerActivityIntent(final Context context, final Class activityClass) { - Intent intent = new Intent(context, activityClass); + final Intent intent = new Intent(context, activityClass); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } @@ -571,7 +571,7 @@ public final class NavigationHelper { private static Intent getOpenIntent(final Context context, final String url, final int serviceId, final StreamingService.LinkType type) { - Intent mIntent = new Intent(context, MainActivity.class); + final Intent mIntent = new Intent(context, MainActivity.class); mIntent.putExtra(Constants.KEY_SERVICE_ID, serviceId); mIntent.putExtra(Constants.KEY_URL, url); mIntent.putExtra(Constants.KEY_LINK_TYPE, type); @@ -585,14 +585,14 @@ public final class NavigationHelper { public static Intent getIntentByLink(final Context context, final StreamingService service, final String url) throws ExtractionException { - StreamingService.LinkType linkType = service.getLinkTypeByUrl(url); + final StreamingService.LinkType linkType = service.getLinkTypeByUrl(url); if (linkType == StreamingService.LinkType.NONE) { throw new ExtractionException("Url not known to service. service=" + service + " url=" + url); } - Intent rIntent = getOpenIntent(context, url, service.getServiceId(), linkType); + final Intent rIntent = getOpenIntent(context, url, service.getServiceId(), linkType); if (linkType == StreamingService.LinkType.STREAM) { rIntent.putExtra(VideoDetailFragment.AUTO_PLAY, @@ -621,7 +621,7 @@ public final class NavigationHelper { try { // Try market:// scheme context.startActivity(new Intent(Intent.ACTION_VIEW, openMarketUrl(packageName))); - } catch (ActivityNotFoundException e) { + } catch (final ActivityNotFoundException e) { // Fall back to google play URL (don't worry F-Droid can handle it :) context.startActivity(new Intent(Intent.ACTION_VIEW, getGooglePlayUrl(packageName))); } @@ -648,7 +648,7 @@ public final class NavigationHelper { * @param videoURL the url to the video */ public static void playWithKore(final Context context, final Uri videoURL) { - Intent intent = new Intent(Intent.ACTION_VIEW); + final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setPackage(context.getString(R.string.kore_package)); intent.setData(videoURL); context.startActivity(intent); diff --git a/app/src/main/java/org/schabi/newpipe/util/PeertubeHelper.java b/app/src/main/java/org/schabi/newpipe/util/PeertubeHelper.java index e89cbf5db..5481b519c 100644 --- a/app/src/main/java/org/schabi/newpipe/util/PeertubeHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/PeertubeHelper.java @@ -23,27 +23,27 @@ public final class PeertubeHelper { private PeertubeHelper() { } public static List getInstanceList(final Context context) { - SharedPreferences sharedPreferences = PreferenceManager + final SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); - String savedInstanceListKey = context.getString(R.string.peertube_instance_list_key); + final String savedInstanceListKey = context.getString(R.string.peertube_instance_list_key); final String savedJson = sharedPreferences.getString(savedInstanceListKey, null); if (null == savedJson) { return Collections.singletonList(getCurrentInstance()); } try { - JsonArray array = JsonParser.object().from(savedJson).getArray("instances"); - List result = new ArrayList<>(); - for (Object o : array) { + final JsonArray array = JsonParser.object().from(savedJson).getArray("instances"); + final List result = new ArrayList<>(); + for (final Object o : array) { if (o instanceof JsonObject) { - JsonObject instance = (JsonObject) o; - String name = instance.getString("name"); - String url = instance.getString("url"); + final JsonObject instance = (JsonObject) o; + final String name = instance.getString("name"); + final String url = instance.getString("url"); result.add(new PeertubeInstance(url, name)); } } return result; - } catch (JsonParserException e) { + } catch (final JsonParserException e) { return Collections.singletonList(getCurrentInstance()); } @@ -51,13 +51,14 @@ public final class PeertubeHelper { public static PeertubeInstance selectInstance(final PeertubeInstance instance, final Context context) { - SharedPreferences sharedPreferences = PreferenceManager + final SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); - String selectedInstanceKey = context.getString(R.string.peertube_selected_instance_key); - JsonStringWriter jsonWriter = JsonWriter.string().object(); + final String selectedInstanceKey + = context.getString(R.string.peertube_selected_instance_key); + final JsonStringWriter jsonWriter = JsonWriter.string().object(); jsonWriter.value("name", instance.getName()); jsonWriter.value("url", instance.getUrl()); - String jsonToSave = jsonWriter.end().done(); + final String jsonToSave = jsonWriter.end().done(); sharedPreferences.edit().putString(selectedInstanceKey, jsonToSave).apply(); ServiceList.PeerTube.setInstance(instance); return instance; diff --git a/app/src/main/java/org/schabi/newpipe/util/PermissionHelper.java b/app/src/main/java/org/schabi/newpipe/util/PermissionHelper.java index 9ba6ed36c..ba157e6be 100644 --- a/app/src/main/java/org/schabi/newpipe/util/PermissionHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/PermissionHelper.java @@ -101,12 +101,12 @@ public final class PermissionHelper { @RequiresApi(api = Build.VERSION_CODES.M) public static boolean checkSystemAlertWindowPermission(final Context context) { if (!Settings.canDrawOverlays(context)) { - Intent i = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, + final Intent i = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName())); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(i); - } catch (ActivityNotFoundException ignored) { + } catch (final ActivityNotFoundException ignored) { } return false; } else { @@ -120,8 +120,9 @@ public final class PermissionHelper { } public static void showPopupEnablementToast(final Context context) { - Toast toast = Toast.makeText(context, R.string.msg_popup_permission, Toast.LENGTH_LONG); - TextView messageView = toast.getView().findViewById(android.R.id.message); + final Toast toast + = Toast.makeText(context, R.string.msg_popup_permission, Toast.LENGTH_LONG); + final TextView messageView = toast.getView().findViewById(android.R.id.message); if (messageView != null) { messageView.setGravity(Gravity.CENTER); } diff --git a/app/src/main/java/org/schabi/newpipe/util/RelatedStreamInfo.java b/app/src/main/java/org/schabi/newpipe/util/RelatedStreamInfo.java index fcd392d67..2526956c5 100644 --- a/app/src/main/java/org/schabi/newpipe/util/RelatedStreamInfo.java +++ b/app/src/main/java/org/schabi/newpipe/util/RelatedStreamInfo.java @@ -16,11 +16,11 @@ public class RelatedStreamInfo extends ListInfo { } public static RelatedStreamInfo getInfo(final StreamInfo info) { - ListLinkHandler handler = new ListLinkHandler( + final ListLinkHandler handler = new ListLinkHandler( info.getOriginalUrl(), info.getUrl(), info.getId(), Collections.emptyList(), null); - RelatedStreamInfo relatedStreamInfo = new RelatedStreamInfo( + final RelatedStreamInfo relatedStreamInfo = new RelatedStreamInfo( info.getServiceId(), handler, info.getName()); - List streams = new ArrayList<>(); + final List streams = new ArrayList<>(); streams.addAll(info.getRelatedStreams()); relatedStreamInfo.setRelatedItems(streams); return relatedStreamInfo; diff --git a/app/src/main/java/org/schabi/newpipe/util/SecondaryStreamHelper.java b/app/src/main/java/org/schabi/newpipe/util/SecondaryStreamHelper.java index 081d981a1..8c697d327 100644 --- a/app/src/main/java/org/schabi/newpipe/util/SecondaryStreamHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/SecondaryStreamHelper.java @@ -39,9 +39,9 @@ public class SecondaryStreamHelper { return null; } - boolean m4v = videoStream.getFormat() == MediaFormat.MPEG_4; + final boolean m4v = videoStream.getFormat() == MediaFormat.MPEG_4; - for (AudioStream audio : audioStreams) { + for (final AudioStream audio : audioStreams) { if (audio.getFormat() == (m4v ? MediaFormat.M4A : MediaFormat.WEBMA)) { return audio; } @@ -53,7 +53,7 @@ public class SecondaryStreamHelper { // retry, but this time in reverse order for (int i = audioStreams.size() - 1; i >= 0; i--) { - AudioStream audio = audioStreams.get(i); + final AudioStream audio = audioStreams.get(i); if (audio.getFormat() == MediaFormat.WEBMA_OPUS) { return audio; } diff --git a/app/src/main/java/org/schabi/newpipe/util/ServiceHelper.java b/app/src/main/java/org/schabi/newpipe/util/ServiceHelper.java index dacf7d844..1ab54343a 100644 --- a/app/src/main/java/org/schabi/newpipe/util/ServiceHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/ServiceHelper.java @@ -117,7 +117,7 @@ public final class ServiceHelper { int serviceId; try { serviceId = NewPipe.getService(serviceName).getServiceId(); - } catch (ExtractionException e) { + } catch (final ExtractionException e) { serviceId = DEFAULT_FALLBACK_SERVICE.getServiceId(); } @@ -128,7 +128,7 @@ public final class ServiceHelper { String serviceName; try { serviceName = NewPipe.getService(serviceId).getServiceInfo().getName(); - } catch (ExtractionException e) { + } catch (final ExtractionException e) { serviceName = DEFAULT_FALLBACK_SERVICE.getServiceInfo().getName(); } @@ -136,7 +136,7 @@ public final class ServiceHelper { } public static void setSelectedServiceId(final Context context, final String serviceName) { - int serviceId = NewPipe.getIdOfService(serviceName); + final int serviceId = NewPipe.getIdOfService(serviceName); if (serviceId == -1) { setSelectedServicePreferences(context, DEFAULT_FALLBACK_SERVICE.getServiceInfo().getName()); @@ -170,29 +170,29 @@ public final class ServiceHelper { public static void initService(final Context context, final int serviceId) { if (serviceId == ServiceList.PeerTube.getServiceId()) { - SharedPreferences sharedPreferences = PreferenceManager + final SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); - String json = sharedPreferences.getString(context.getString( + final String json = sharedPreferences.getString(context.getString( R.string.peertube_selected_instance_key), null); if (null == json) { return; } - JsonObject jsonObject = null; + final JsonObject jsonObject; try { jsonObject = JsonParser.object().from(json); - } catch (JsonParserException e) { + } catch (final JsonParserException e) { return; } - String name = jsonObject.getString("name"); - String url = jsonObject.getString("url"); - PeertubeInstance instance = new PeertubeInstance(url, name); + final String name = jsonObject.getString("name"); + final String url = jsonObject.getString("url"); + final PeertubeInstance instance = new PeertubeInstance(url, name); ServiceList.PeerTube.setInstance(instance); } } public static void initServices(final Context context) { - for (StreamingService s : ServiceList.all()) { + for (final StreamingService s : ServiceList.all()) { initService(context, s.getServiceId()); } } diff --git a/app/src/main/java/org/schabi/newpipe/util/ShareUtils.java b/app/src/main/java/org/schabi/newpipe/util/ShareUtils.java index a3571b96f..1283f67f5 100644 --- a/app/src/main/java/org/schabi/newpipe/util/ShareUtils.java +++ b/app/src/main/java/org/schabi/newpipe/util/ShareUtils.java @@ -77,7 +77,7 @@ public final class ShareUtils { * @param url the url to share */ public static void shareUrl(final Context context, final String subject, final String url) { - Intent intent = new Intent(Intent.ACTION_SEND); + final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, url); diff --git a/app/src/main/java/org/schabi/newpipe/util/StateSaver.java b/app/src/main/java/org/schabi/newpipe/util/StateSaver.java index 2a1dff5c9..cfe2b3272 100644 --- a/app/src/main/java/org/schabi/newpipe/util/StateSaver.java +++ b/app/src/main/java/org/schabi/newpipe/util/StateSaver.java @@ -66,7 +66,7 @@ public final class StateSaver { * @param context used to get the available cache dir */ public static void init(final Context context) { - File externalCacheDir = context.getExternalCacheDir(); + final File externalCacheDir = context.getExternalCacheDir(); if (externalCacheDir != null) { cacheDirPath = externalCacheDir.getAbsolutePath(); } @@ -86,7 +86,7 @@ public final class StateSaver { return null; } - SavedState savedState = outState.getParcelable(KEY_SAVED_STATE); + final SavedState savedState = outState.getParcelable(KEY_SAVED_STATE); if (savedState == null) { return null; } @@ -122,7 +122,7 @@ public final class StateSaver { return savedState; } - File file = new File(savedState.getPathFileSaved()); + final File file = new File(savedState.getPathFileSaved()); if (!file.exists()) { if (MainActivity.DEBUG) { Log.d(TAG, "Cache file doesn't exist: " + file.getAbsolutePath()); @@ -131,7 +131,7 @@ public final class StateSaver { } fileInputStream = new FileInputStream(file); - ObjectInputStream inputStream = new ObjectInputStream(fileInputStream); + final ObjectInputStream inputStream = new ObjectInputStream(fileInputStream); //noinspection unchecked savedObjects = (Queue) inputStream.readObject(); if (savedObjects != null) { @@ -139,13 +139,13 @@ public final class StateSaver { } return savedState; - } catch (Exception e) { + } catch (final Exception e) { Log.e(TAG, "Failed to restore state", e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); - } catch (IOException ignored) { + } catch (final IOException ignored) { } } } @@ -165,7 +165,7 @@ public final class StateSaver { @Nullable final SavedState savedState, final Bundle outState, final WriteRead writeRead) { @NonNull - String currentSavedPrefix; + final String currentSavedPrefix; if (savedState == null || TextUtils.isEmpty(savedState.getPrefixFileSaved())) { // Generate unique prefix currentSavedPrefix = System.nanoTime() - writeRead.hashCode() + ""; @@ -215,7 +215,7 @@ public final class StateSaver { + "writeRead = [" + writeRead + "]"); } - LinkedList savedObjects = new LinkedList<>(); + final LinkedList savedObjects = new LinkedList<>(); writeRead.writeTo(savedObjects); if (isChangingConfig) { @@ -247,36 +247,36 @@ public final class StateSaver { } } - File file = new File(cacheDir, prefixFileName + final File file = new File(cacheDir, prefixFileName + (TextUtils.isEmpty(suffixFileName) ? ".cache" : suffixFileName)); if (file.exists() && file.length() > 0) { // If the file already exists, just return it return new SavedState(prefixFileName, file.getAbsolutePath()); } else { // Delete any file that contains the prefix - File[] files = cacheDir.listFiles(new FilenameFilter() { + final File[] files = cacheDir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return name.contains(prefixFileName); } }); - for (File fileToDelete : files) { + for (final File fileToDelete : files) { fileToDelete.delete(); } } fileOutputStream = new FileOutputStream(file); - ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream); + final ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream); outputStream.writeObject(savedObjects); return new SavedState(prefixFileName, file.getAbsolutePath()); - } catch (Exception e) { + } catch (final Exception e) { Log.e(TAG, "Failed to save state", e); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); - } catch (IOException ignored) { } + } catch (final IOException ignored) { } } } return null; @@ -298,7 +298,7 @@ public final class StateSaver { try { //noinspection ResultOfMethodCallIgnored new File(savedState.getPathFileSaved()).delete(); - } catch (Exception ignored) { + } catch (final Exception ignored) { } } } @@ -319,7 +319,7 @@ public final class StateSaver { cacheDir = new File(cacheDir, CACHE_DIR_NAME); if (cacheDir.exists()) { - for (File file : cacheDir.listFiles()) { + for (final File file : cacheDir.listFiles()) { file.delete(); } } diff --git a/app/src/main/java/org/schabi/newpipe/util/StreamDialogEntry.java b/app/src/main/java/org/schabi/newpipe/util/StreamDialogEntry.java index 92aee8ba7..a1e2e6eb9 100644 --- a/app/src/main/java/org/schabi/newpipe/util/StreamDialogEntry.java +++ b/app/src/main/java/org/schabi/newpipe/util/StreamDialogEntry.java @@ -76,7 +76,7 @@ public enum StreamDialogEntry { */ public static void setEnabledEntries(final StreamDialogEntry... entries) { // cleanup from last time StreamDialogEntry was used - for (StreamDialogEntry streamDialogEntry : values()) { + for (final StreamDialogEntry streamDialogEntry : values()) { streamDialogEntry.customAction = null; } @@ -84,7 +84,7 @@ public enum StreamDialogEntry { } public static String[] getCommands(final Context context) { - String[] commands = new String[enabledEntries.length]; + final String[] commands = new String[enabledEntries.length]; for (int i = 0; i != enabledEntries.length; ++i) { commands[i] = context.getResources().getString(enabledEntries[i].resource); } diff --git a/app/src/main/java/org/schabi/newpipe/util/StreamItemAdapter.java b/app/src/main/java/org/schabi/newpipe/util/StreamItemAdapter.java index 6a244a69b..2bfd27c47 100644 --- a/app/src/main/java/org/schabi/newpipe/util/StreamItemAdapter.java +++ b/app/src/main/java/org/schabi/newpipe/util/StreamItemAdapter.java @@ -111,7 +111,7 @@ public class StreamItemAdapter extends BaseA String qualityString; if (stream instanceof VideoStream) { - VideoStream videoStream = ((VideoStream) stream); + final VideoStream videoStream = ((VideoStream) stream); qualityString = videoStream.getResolution(); if (secondaryStreams != null) { @@ -123,7 +123,7 @@ public class StreamItemAdapter extends BaseA } } } else if (stream instanceof AudioStream) { - AudioStream audioStream = ((AudioStream) stream); + final AudioStream audioStream = ((AudioStream) stream); qualityString = audioStream.getAverageBitrate() > 0 ? audioStream.getAverageBitrate() + "kbps" : audioStream.getFormat().getName(); @@ -137,10 +137,11 @@ public class StreamItemAdapter extends BaseA } if (streamsWrapper.getSizeInBytes(position) > 0) { - SecondaryStreamHelper secondary = secondaryStreams == null ? null + final SecondaryStreamHelper secondary = secondaryStreams == null ? null : secondaryStreams.get(position); if (secondary != null) { - long size = secondary.getSizeInBytes() + streamsWrapper.getSizeInBytes(position); + final long size + = secondary.getSizeInBytes() + streamsWrapper.getSizeInBytes(position); sizeView.setText(Utility.formatBytes(size)); } else { sizeView.setText(streamsWrapper.getFormattedSize(position)); @@ -204,7 +205,7 @@ public class StreamItemAdapter extends BaseA final StreamSizeWrapper streamsWrapper) { final Callable fetchAndSet = () -> { boolean hasChanged = false; - for (X stream : streamsWrapper.getStreamsList()) { + for (final X stream : streamsWrapper.getStreamsList()) { if (streamsWrapper.getSizeInBytes(stream) > -2) { continue; } diff --git a/app/src/main/java/org/schabi/newpipe/util/TLSSocketFactoryCompat.java b/app/src/main/java/org/schabi/newpipe/util/TLSSocketFactoryCompat.java index 105af5086..a83e844ea 100644 --- a/app/src/main/java/org/schabi/newpipe/util/TLSSocketFactoryCompat.java +++ b/app/src/main/java/org/schabi/newpipe/util/TLSSocketFactoryCompat.java @@ -27,7 +27,7 @@ public class TLSSocketFactoryCompat extends SSLSocketFactory { private SSLSocketFactory internalSSLSocketFactory; public TLSSocketFactoryCompat() throws KeyManagementException, NoSuchAlgorithmException { - SSLContext context = SSLContext.getInstance("TLS"); + final SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, null); internalSSLSocketFactory = context.getSocketFactory(); } @@ -35,7 +35,7 @@ public class TLSSocketFactoryCompat extends SSLSocketFactory { public TLSSocketFactoryCompat(final TrustManager[] tm) throws KeyManagementException, NoSuchAlgorithmException { - SSLContext context = SSLContext.getInstance("TLS"); + final SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tm, new java.security.SecureRandom()); internalSSLSocketFactory = context.getSocketFactory(); } diff --git a/app/src/main/java/org/schabi/newpipe/util/ThemeHelper.java b/app/src/main/java/org/schabi/newpipe/util/ThemeHelper.java index 74ea34fcc..88e1a31cd 100644 --- a/app/src/main/java/org/schabi/newpipe/util/ThemeHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/ThemeHelper.java @@ -126,11 +126,11 @@ public final class ThemeHelper { */ @StyleRes public static int getThemeForService(final Context context, final int serviceId) { - String lightTheme = context.getResources().getString(R.string.light_theme_key); - String darkTheme = context.getResources().getString(R.string.dark_theme_key); - String blackTheme = context.getResources().getString(R.string.black_theme_key); + final String lightTheme = context.getResources().getString(R.string.light_theme_key); + final String darkTheme = context.getResources().getString(R.string.dark_theme_key); + final String blackTheme = context.getResources().getString(R.string.black_theme_key); - String selectedTheme = getSelectedThemeString(context); + final String selectedTheme = getSelectedThemeString(context); int defaultTheme = R.style.DarkTheme; if (selectedTheme.equals(lightTheme)) { @@ -148,7 +148,7 @@ public final class ThemeHelper { final StreamingService service; try { service = NewPipe.getService(serviceId); - } catch (ExtractionException ignored) { + } catch (final ExtractionException ignored) { return defaultTheme; } @@ -162,7 +162,7 @@ public final class ThemeHelper { } themeName += "." + service.getServiceInfo().getName(); - int resourceId = context + final int resourceId = context .getResources() .getIdentifier(themeName, "style", context.getPackageName()); @@ -175,11 +175,11 @@ public final class ThemeHelper { @StyleRes public static int getSettingsThemeStyle(final Context context) { - String lightTheme = context.getResources().getString(R.string.light_theme_key); - String darkTheme = context.getResources().getString(R.string.dark_theme_key); - String blackTheme = context.getResources().getString(R.string.black_theme_key); + final String lightTheme = context.getResources().getString(R.string.light_theme_key); + final String darkTheme = context.getResources().getString(R.string.dark_theme_key); + final String blackTheme = context.getResources().getString(R.string.black_theme_key); - String selectedTheme = getSelectedThemeString(context); + final String selectedTheme = getSelectedThemeString(context); if (selectedTheme.equals(lightTheme)) { return R.style.LightSettingsTheme; @@ -201,8 +201,8 @@ public final class ThemeHelper { * @return resource ID */ public static int resolveResourceIdFromAttr(final Context context, @AttrRes final int attr) { - TypedArray a = context.getTheme().obtainStyledAttributes(new int[]{attr}); - int attributeResourceId = a.getResourceId(0, 0); + final TypedArray a = context.getTheme().obtainStyledAttributes(new int[]{attr}); + final int attributeResourceId = a.getResourceId(0, 0); a.recycle(); return attributeResourceId; } @@ -226,8 +226,8 @@ public final class ThemeHelper { } private static String getSelectedThemeString(final Context context) { - String themeKey = context.getString(R.string.theme_key); - String defaultTheme = context.getResources().getString(R.string.default_theme_value); + final String themeKey = context.getString(R.string.theme_key); + final String defaultTheme = context.getResources().getString(R.string.default_theme_value); return PreferenceManager.getDefaultSharedPreferences(context) .getString(themeKey, defaultTheme); } diff --git a/app/src/main/java/org/schabi/newpipe/util/ZipHelper.java b/app/src/main/java/org/schabi/newpipe/util/ZipHelper.java index 31f5fd222..7ed90d693 100644 --- a/app/src/main/java/org/schabi/newpipe/util/ZipHelper.java +++ b/app/src/main/java/org/schabi/newpipe/util/ZipHelper.java @@ -44,10 +44,10 @@ public final class ZipHelper { */ public static void addFileToZip(final ZipOutputStream outZip, final String file, final String name) throws Exception { - byte[] data = new byte[BUFFER_SIZE]; - FileInputStream fi = new FileInputStream(file); - BufferedInputStream inputStream = new BufferedInputStream(fi, BUFFER_SIZE); - ZipEntry entry = new ZipEntry(name); + final byte[] data = new byte[BUFFER_SIZE]; + final FileInputStream fi = new FileInputStream(file); + final BufferedInputStream inputStream = new BufferedInputStream(fi, BUFFER_SIZE); + final ZipEntry entry = new ZipEntry(name); outZip.putNextEntry(entry); int count; while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) { @@ -69,11 +69,11 @@ public final class ZipHelper { public static boolean extractFileFromZip(final String filePath, final String file, final String name) throws Exception { - ZipInputStream inZip = new ZipInputStream( + final ZipInputStream inZip = new ZipInputStream( new BufferedInputStream( new FileInputStream(filePath))); - byte[] data = new byte[BUFFER_SIZE]; + final byte[] data = new byte[BUFFER_SIZE]; boolean found = false; @@ -82,14 +82,14 @@ public final class ZipHelper { if (ze.getName().equals(name)) { found = true; // delete old file first - File oldFile = new File(file); + final File oldFile = new File(file); if (oldFile.exists()) { if (!oldFile.delete()) { throw new Exception("Could not delete " + file); } } - FileOutputStream outFile = new FileOutputStream(file); + final FileOutputStream outFile = new FileOutputStream(file); int count = 0; while ((count = inZip.read(data)) != -1) { outFile.write(data, 0, count); diff --git a/app/src/main/java/org/schabi/newpipe/views/AnimatedProgressBar.java b/app/src/main/java/org/schabi/newpipe/views/AnimatedProgressBar.java index 0fbf6a254..b1fabe715 100644 --- a/app/src/main/java/org/schabi/newpipe/views/AnimatedProgressBar.java +++ b/app/src/main/java/org/schabi/newpipe/views/AnimatedProgressBar.java @@ -59,7 +59,7 @@ public final class AnimatedProgressBar extends ProgressBar { @Override protected void applyTransformation(final float interpolatedTime, final Transformation t) { super.applyTransformation(interpolatedTime, t); - float value = from + (to - from) * interpolatedTime; + final float value = from + (to - from) * interpolatedTime; progressBar.setProgress((int) value); } } diff --git a/app/src/main/java/org/schabi/newpipe/views/CollapsibleView.java b/app/src/main/java/org/schabi/newpipe/views/CollapsibleView.java index 028e9b674..b34a6be63 100644 --- a/app/src/main/java/org/schabi/newpipe/views/CollapsibleView.java +++ b/app/src/main/java/org/schabi/newpipe/views/CollapsibleView.java @@ -178,7 +178,7 @@ public class CollapsibleView extends LinearLayout { } public void broadcastState() { - for (StateListener listener : listeners) { + for (final StateListener listener : listeners) { listener.onStateChanged(currentState); } } diff --git a/app/src/main/java/org/schabi/newpipe/views/FocusAwareDrawerLayout.java b/app/src/main/java/org/schabi/newpipe/views/FocusAwareDrawerLayout.java index 0da42fab6..500562668 100644 --- a/app/src/main/java/org/schabi/newpipe/views/FocusAwareDrawerLayout.java +++ b/app/src/main/java/org/schabi/newpipe/views/FocusAwareDrawerLayout.java @@ -55,9 +55,10 @@ public final class FocusAwareDrawerLayout extends DrawerLayout { boolean hasOpenPanels = false; for (int i = 0; i < getChildCount(); ++i) { - View child = getChildAt(i); + final View child = getChildAt(i); - DrawerLayout.LayoutParams lp = (DrawerLayout.LayoutParams) child.getLayoutParams(); + final DrawerLayout.LayoutParams lp + = (DrawerLayout.LayoutParams) child.getLayoutParams(); if (lp.gravity != 0 && isDrawerVisible(child)) { hasOpenPanels = true; @@ -82,9 +83,10 @@ public final class FocusAwareDrawerLayout extends DrawerLayout { View content = null; for (int i = 0; i < getChildCount(); ++i) { - View child = getChildAt(i); + final View child = getChildAt(i); - DrawerLayout.LayoutParams lp = (DrawerLayout.LayoutParams) child.getLayoutParams(); + final DrawerLayout.LayoutParams lp + = (DrawerLayout.LayoutParams) child.getLayoutParams(); if (lp.gravity == 0) { content = child; diff --git a/app/src/main/java/org/schabi/newpipe/views/FocusOverlayView.java b/app/src/main/java/org/schabi/newpipe/views/FocusOverlayView.java index 64817a154..4a342784e 100644 --- a/app/src/main/java/org/schabi/newpipe/views/FocusOverlayView.java +++ b/app/src/main/java/org/schabi/newpipe/views/FocusOverlayView.java @@ -87,12 +87,12 @@ public final class FocusOverlayView extends Drawable implements } private void updateRect() { - View focusedView = focused == null ? null : this.focused.get(); + final View focusedView = focused == null ? null : this.focused.get(); - int l = focusRect.left; - int r = focusRect.right; - int t = focusRect.top; - int b = focusRect.bottom; + final int l = focusRect.left; + final int r = focusRect.right; + final int t = focusRect.top; + final int b = focusRect.bottom; if (focusedView != null && isShown(focusedView)) { focusedView.getGlobalVisibleRect(focusRect); @@ -184,40 +184,40 @@ public final class FocusOverlayView extends Drawable implements } public static void setupFocusObserver(final Dialog dialog) { - Rect displayRect = new Rect(); + final Rect displayRect = new Rect(); - Window window = dialog.getWindow(); + final Window window = dialog.getWindow(); assert window != null; - View decor = window.getDecorView(); + final View decor = window.getDecorView(); decor.getWindowVisibleDisplayFrame(displayRect); - FocusOverlayView overlay = new FocusOverlayView(dialog.getContext()); + final FocusOverlayView overlay = new FocusOverlayView(dialog.getContext()); overlay.setBounds(0, 0, displayRect.width(), displayRect.height()); setupOverlay(window, overlay); } public static void setupFocusObserver(final Activity activity) { - Rect displayRect = new Rect(); + final Rect displayRect = new Rect(); - Window window = activity.getWindow(); - View decor = window.getDecorView(); + final Window window = activity.getWindow(); + final View decor = window.getDecorView(); decor.getWindowVisibleDisplayFrame(displayRect); - FocusOverlayView overlay = new FocusOverlayView(activity); + final FocusOverlayView overlay = new FocusOverlayView(activity); overlay.setBounds(0, 0, displayRect.width(), displayRect.height()); setupOverlay(window, overlay); } private static void setupOverlay(final Window window, final FocusOverlayView overlay) { - ViewGroup decor = (ViewGroup) window.getDecorView(); + final ViewGroup decor = (ViewGroup) window.getDecorView(); decor.getOverlay().add(overlay); fixFocusHierarchy(decor); - ViewTreeObserver observer = decor.getViewTreeObserver(); + final ViewTreeObserver observer = decor.getViewTreeObserver(); observer.addOnScrollChangedListener(overlay); observer.addOnGlobalFocusChangeListener(overlay); observer.addOnGlobalLayoutListener(overlay); @@ -235,7 +235,7 @@ public final class FocusOverlayView extends Drawable implements window.setCallback(new WindowCallbackWrapper(window.getCallback()) { @Override public boolean dispatchKeyEvent(final KeyEvent event) { - boolean res = super.dispatchKeyEvent(event); + final boolean res = super.dispatchKeyEvent(event); overlay.onKey(event); return res; } @@ -280,10 +280,10 @@ public final class FocusOverlayView extends Drawable implements return; // clusters aren't supposed to nest } - int childCount = viewGroup.getChildCount(); + final int childCount = viewGroup.getChildCount(); for (int i = 0; i < childCount; ++i) { - View view = viewGroup.getChildAt(i); + final View view = viewGroup.getChildAt(i); if (view instanceof ViewGroup) { clearFocusObstacles((ViewGroup) view); diff --git a/app/src/main/java/org/schabi/newpipe/views/LargeTextMovementMethod.java b/app/src/main/java/org/schabi/newpipe/views/LargeTextMovementMethod.java index 3a3384b51..36e0eabb0 100644 --- a/app/src/main/java/org/schabi/newpipe/views/LargeTextMovementMethod.java +++ b/app/src/main/java/org/schabi/newpipe/views/LargeTextMovementMethod.java @@ -64,7 +64,7 @@ public class LargeTextMovementMethod extends LinkMovementMethod { final int keyCode, final int movementMetaState, final KeyEvent event) { - int newDir = keyToDir(keyCode); + final int newDir = keyToDir(keyCode); if (direction != 0 && newDir != direction) { return false; @@ -72,7 +72,7 @@ public class LargeTextMovementMethod extends LinkMovementMethod { this.direction = 0; - ViewGroup root = findScrollableParent(widget); + final ViewGroup root = findScrollableParent(widget); widget.getHitRect(visibleRect); @@ -118,46 +118,46 @@ public class LargeTextMovementMethod extends LinkMovementMethod { } private boolean gotoPrev(final TextView view, final Spannable buffer) { - Layout layout = view.getLayout(); + final Layout layout = view.getLayout(); if (layout == null) { return false; } - View root = findScrollableParent(view); + final View root = findScrollableParent(view); - int rootHeight = root.getHeight(); + final int rootHeight = root.getHeight(); if (visibleRect.top >= 0) { // we fit entirely into the viewport, no need for fancy footwork return false; } - int topExtra = -visibleRect.top; + final int topExtra = -visibleRect.top; - int firstVisibleLineNumber = layout.getLineForVertical(topExtra); + final int firstVisibleLineNumber = layout.getLineForVertical(topExtra); // when deciding whether to pass "focus" to span, account for one more line // this ensures, that focus is never passed to spans partially outside scroll window - int visibleStart = firstVisibleLineNumber == 0 + final int visibleStart = firstVisibleLineNumber == 0 ? 0 : layout.getLineStart(firstVisibleLineNumber - 1); - ClickableSpan[] candidates = buffer.getSpans( + final ClickableSpan[] candidates = buffer.getSpans( visibleStart, buffer.length(), ClickableSpan.class); if (candidates.length != 0) { - int a = Selection.getSelectionStart(buffer); - int b = Selection.getSelectionEnd(buffer); + final int a = Selection.getSelectionStart(buffer); + final int b = Selection.getSelectionEnd(buffer); - int selStart = Math.min(a, b); - int selEnd = Math.max(a, b); + final int selStart = Math.min(a, b); + final int selEnd = Math.max(a, b); int bestStart = -1; int bestEnd = -1; for (int i = 0; i < candidates.length; i++) { - int start = buffer.getSpanStart(candidates[i]); - int end = buffer.getSpanEnd(candidates[i]); + final int start = buffer.getSpanStart(candidates[i]); + final int end = buffer.getSpanEnd(candidates[i]); if ((end < selEnd || selStart == selEnd) && start >= visibleStart) { if (end > bestEnd) { @@ -173,7 +173,7 @@ public class LargeTextMovementMethod extends LinkMovementMethod { } } - float fourLines = view.getTextSize() * 4; + final float fourLines = view.getTextSize() * 4; visibleRect.left = 0; visibleRect.right = view.getWidth(); @@ -184,49 +184,49 @@ public class LargeTextMovementMethod extends LinkMovementMethod { } private boolean gotoNext(final TextView view, final Spannable buffer) { - Layout layout = view.getLayout(); + final Layout layout = view.getLayout(); if (layout == null) { return false; } - View root = findScrollableParent(view); + final View root = findScrollableParent(view); - int rootHeight = root.getHeight(); + final int rootHeight = root.getHeight(); if (visibleRect.bottom <= rootHeight) { // we fit entirely into the viewport, no need for fancy footwork return false; } - int bottomExtra = visibleRect.bottom - rootHeight; + final int bottomExtra = visibleRect.bottom - rootHeight; - int visibleBottomBorder = view.getHeight() - bottomExtra; + final int visibleBottomBorder = view.getHeight() - bottomExtra; - int lineCount = layout.getLineCount(); + final int lineCount = layout.getLineCount(); - int lastVisibleLineNumber = layout.getLineForVertical(visibleBottomBorder); + final int lastVisibleLineNumber = layout.getLineForVertical(visibleBottomBorder); // when deciding whether to pass "focus" to span, account for one more line // this ensures, that focus is never passed to spans partially outside scroll window - int visibleEnd = lastVisibleLineNumber == lineCount - 1 + final int visibleEnd = lastVisibleLineNumber == lineCount - 1 ? buffer.length() : layout.getLineEnd(lastVisibleLineNumber - 1); - ClickableSpan[] candidates = buffer.getSpans(0, visibleEnd, ClickableSpan.class); + final ClickableSpan[] candidates = buffer.getSpans(0, visibleEnd, ClickableSpan.class); if (candidates.length != 0) { - int a = Selection.getSelectionStart(buffer); - int b = Selection.getSelectionEnd(buffer); + final int a = Selection.getSelectionStart(buffer); + final int b = Selection.getSelectionEnd(buffer); - int selStart = Math.min(a, b); - int selEnd = Math.max(a, b); + final int selStart = Math.min(a, b); + final int selEnd = Math.max(a, b); int bestStart = Integer.MAX_VALUE; int bestEnd = Integer.MAX_VALUE; for (int i = 0; i < candidates.length; i++) { - int start = buffer.getSpanStart(candidates[i]); - int end = buffer.getSpanEnd(candidates[i]); + final int start = buffer.getSpanStart(candidates[i]); + final int end = buffer.getSpanEnd(candidates[i]); if ((start > selStart || selStart == selEnd) && end <= visibleEnd) { if (start < bestStart) { @@ -245,7 +245,7 @@ public class LargeTextMovementMethod extends LinkMovementMethod { // there are no links within visible area, but still some text past visible area // scroll visible area further in required direction - float fourLines = view.getTextSize() * 4; + final float fourLines = view.getTextSize() * 4; visibleRect.left = 0; visibleRect.right = view.getWidth(); diff --git a/app/src/main/java/org/schabi/newpipe/views/NewPipeRecyclerView.java b/app/src/main/java/org/schabi/newpipe/views/NewPipeRecyclerView.java index 655b86818..6350f80a5 100644 --- a/app/src/main/java/org/schabi/newpipe/views/NewPipeRecyclerView.java +++ b/app/src/main/java/org/schabi/newpipe/views/NewPipeRecyclerView.java @@ -104,14 +104,14 @@ public class NewPipeRecyclerView extends RecyclerView { // can mess with focused View by moving it off-screen and detaching) if (focused != null) { - View focusedItem = findContainingItemView(focused); + final View focusedItem = findContainingItemView(focused); if (focusedItem != null) { focusedItem.getHitRect(focusRect); } } // call focusSearch() to initiate layout, but disregard returned View for now - View adapterResult = super.focusSearch(focused, direction); + final View adapterResult = super.focusSearch(focused, direction); if (adapterResult != null && !isOutside(adapterResult)) { adapterResult.requestFocus(direction); return true; @@ -148,16 +148,16 @@ public class NewPipeRecyclerView extends RecyclerView { return false; } - FocusFinder finder = FocusFinder.getInstance(); + final FocusFinder finder = FocusFinder.getInstance(); // try to use FocusFinder instead of adapter - ViewGroup root = (ViewGroup) getRootView(); + final ViewGroup root = (ViewGroup) getRootView(); tempFocus.set(focusRect); root.offsetDescendantRectToMyCoords(this, tempFocus); - View focusFinderResult = finder.findNextFocusFromRect(root, tempFocus, direction); + final View focusFinderResult = finder.findNextFocusFromRect(root, tempFocus, direction); if (focusFinderResult != null && !isOutside(focusFinderResult)) { focusFinderResult.requestFocus(direction); return true; @@ -172,7 +172,7 @@ public class NewPipeRecyclerView extends RecyclerView { parent.offsetDescendantRectToMyCoords(this, tempFocus); - View candidate = finder.findNextFocusFromRect(parent, tempFocus, direction); + final View candidate = finder.findNextFocusFromRect(parent, tempFocus, direction); if (candidate != null && candidate.requestFocus(direction)) { return true; } diff --git a/app/src/main/java/org/schabi/newpipe/views/ScrollableTabLayout.java b/app/src/main/java/org/schabi/newpipe/views/ScrollableTabLayout.java index 48e8ef81c..fb21a8083 100644 --- a/app/src/main/java/org/schabi/newpipe/views/ScrollableTabLayout.java +++ b/app/src/main/java/org/schabi/newpipe/views/ScrollableTabLayout.java @@ -118,7 +118,7 @@ public class ScrollableTabLayout extends TabLayout { final int count = getTabCount(); int contentWidth = 0; for (int i = 0; i < count; i++) { - View child = getTabAt(i).view; + final View child = getTabAt(i).view; if (child.getVisibility() == View.VISIBLE) { // Use tab's minimum requested width should actual content be too small contentWidth += Math.max(child.getMinimumWidth(), child.getMeasuredWidth()); diff --git a/app/src/main/java/org/schabi/newpipe/views/SuperScrollLayoutManager.java b/app/src/main/java/org/schabi/newpipe/views/SuperScrollLayoutManager.java index 6c4d20603..62465d2a4 100644 --- a/app/src/main/java/org/schabi/newpipe/views/SuperScrollLayoutManager.java +++ b/app/src/main/java/org/schabi/newpipe/views/SuperScrollLayoutManager.java @@ -64,12 +64,12 @@ public final class SuperScrollLayoutManager extends LinearLayoutManager { @Nullable @Override public View onInterceptFocusSearch(@NonNull final View focused, final int direction) { - View focusedItem = findContainingItemView(focused); + final View focusedItem = findContainingItemView(focused); if (focusedItem == null) { return super.onInterceptFocusSearch(focused, direction); } - int listDirection = getAbsoluteDirection(direction); + final int listDirection = getAbsoluteDirection(direction); if (listDirection == 0) { return super.onInterceptFocusSearch(focused, direction); } @@ -82,9 +82,9 @@ public final class SuperScrollLayoutManager extends LinearLayoutManager { // Fortunately we can intercept focus search and implement our own logic, based purely // on position along the LinearLayoutManager axis - ViewGroup recycler = (ViewGroup) focusedItem.getParent(); + final ViewGroup recycler = (ViewGroup) focusedItem.getParent(); - int sourcePosition = getPosition(focusedItem); + final int sourcePosition = getPosition(focusedItem); if (sourcePosition == 0 && listDirection < 0) { return super.onInterceptFocusSearch(focused, direction); } @@ -100,7 +100,7 @@ public final class SuperScrollLayoutManager extends LinearLayoutManager { : View.FOCUSABLES_ALL); try { - for (View view : focusables) { + for (final View view : focusables) { if (view == focused || view == recycler) { continue; } @@ -111,7 +111,7 @@ public final class SuperScrollLayoutManager extends LinearLayoutManager { continue; } - int candidate = getDistance(sourcePosition, view, listDirection); + final int candidate = getDistance(sourcePosition, view, listDirection); if (candidate < 0) { continue; } @@ -162,12 +162,12 @@ public final class SuperScrollLayoutManager extends LinearLayoutManager { } private int getDistance(final int sourcePosition, final View candidate, final int direction) { - View itemView = findContainingItemView(candidate); + final View itemView = findContainingItemView(candidate); if (itemView == null) { return -1; } - int position = getPosition(itemView); + final int position = getPosition(itemView); return direction * (position - sourcePosition); } diff --git a/app/src/test/java/org/schabi/newpipe/local/subscription/services/ImportExportJsonHelperTest.java b/app/src/test/java/org/schabi/newpipe/local/subscription/services/ImportExportJsonHelperTest.java index ca42a5607..d3d1fa419 100644 --- a/app/src/test/java/org/schabi/newpipe/local/subscription/services/ImportExportJsonHelperTest.java +++ b/app/src/test/java/org/schabi/newpipe/local/subscription/services/ImportExportJsonHelperTest.java @@ -20,35 +20,35 @@ import static org.junit.Assert.fail; public class ImportExportJsonHelperTest { @Test public void testEmptySource() throws Exception { - String emptySource = + final String emptySource = "{\"app_version\":\"0.11.6\",\"app_version_int\": 47,\"subscriptions\":[]}"; - List items = ImportExportJsonHelper.readFrom(new ByteArrayInputStream( - emptySource.getBytes(StandardCharsets.UTF_8)), null); + final List items = ImportExportJsonHelper.readFrom( + new ByteArrayInputStream(emptySource.getBytes(StandardCharsets.UTF_8)), null); assertTrue(items.isEmpty()); } @Test public void testInvalidSource() { - List invalidList = Arrays.asList( + final List invalidList = Arrays.asList( "{}", "", null, "gibberish"); - for (String invalidContent : invalidList) { + for (final String invalidContent : invalidList) { try { if (invalidContent != null) { - byte[] bytes = invalidContent.getBytes(StandardCharsets.UTF_8); + final byte[] bytes = invalidContent.getBytes(StandardCharsets.UTF_8); ImportExportJsonHelper.readFrom((new ByteArrayInputStream(bytes)), null); } else { ImportExportJsonHelper.readFrom(null, null); } fail("didn't throw exception"); - } catch (Exception e) { - boolean isExpectedException = e - instanceof SubscriptionExtractor.InvalidSourceException; + } catch (final Exception e) { + final boolean isExpectedException + = e instanceof SubscriptionExtractor.InvalidSourceException; assertTrue("\"" + e.getClass().getSimpleName() + "\" is not the expected exception", isExpectedException); } diff --git a/app/src/test/java/org/schabi/newpipe/settings/tabs/TabTest.java b/app/src/test/java/org/schabi/newpipe/settings/tabs/TabTest.java index 61a0daeec..23fdc0152 100644 --- a/app/src/test/java/org/schabi/newpipe/settings/tabs/TabTest.java +++ b/app/src/test/java/org/schabi/newpipe/settings/tabs/TabTest.java @@ -12,7 +12,7 @@ public class TabTest { public void checkIdDuplication() { final Set usedIds = new HashSet<>(); - for (Tab.Type type : Tab.Type.values()) { + for (final Tab.Type type : Tab.Type.values()) { final boolean added = usedIds.add(type.getTabId()); assertTrue("Id was already used: " + type.getTabId(), added); } diff --git a/app/src/test/java/org/schabi/newpipe/settings/tabs/TabsJsonHelperTest.java b/app/src/test/java/org/schabi/newpipe/settings/tabs/TabsJsonHelperTest.java index 68cee9b0d..886f00584 100644 --- a/app/src/test/java/org/schabi/newpipe/settings/tabs/TabsJsonHelperTest.java +++ b/app/src/test/java/org/schabi/newpipe/settings/tabs/TabsJsonHelperTest.java @@ -53,13 +53,14 @@ public class TabsJsonHelperTest { "{}" ); - for (String invalidContent : invalidList) { + for (final String invalidContent : invalidList) { try { TabsJsonHelper.getTabsFromJson(invalidContent); fail("didn't throw exception"); - } catch (Exception e) { - boolean isExpectedException = e instanceof TabsJsonHelper.InvalidJsonException; + } catch (final Exception e) { + final boolean isExpectedException + = e instanceof TabsJsonHelper.InvalidJsonException; assertTrue("\"" + e.getClass().getSimpleName() + "\" is not the expected exception", isExpectedException); } @@ -78,7 +79,7 @@ public class TabsJsonHelperTest { } private boolean isTabsArrayEmpty(final String returnedJson) throws JsonParserException { - JsonObject jsonObject = JsonParser.object().from(returnedJson); + final JsonObject jsonObject = JsonParser.object().from(returnedJson); assertTrue(jsonObject.containsKey(JSON_TABS_ARRAY_KEY)); return jsonObject.getArray(JSON_TABS_ARRAY_KEY).size() == 0; } diff --git a/app/src/test/java/org/schabi/newpipe/util/ListHelperTest.java b/app/src/test/java/org/schabi/newpipe/util/ListHelperTest.java index 0baa2a167..8cd99cc04 100644 --- a/app/src/test/java/org/schabi/newpipe/util/ListHelperTest.java +++ b/app/src/test/java/org/schabi/newpipe/util/ListHelperTest.java @@ -82,9 +82,9 @@ public class ListHelperTest { // Don't show Higher resolutions // ////////////////////////////////// - List result = ListHelper.getSortedStreamVideosList(MediaFormat.MPEG_4, + final List result = ListHelper.getSortedStreamVideosList(MediaFormat.MPEG_4, false, VIDEO_STREAMS_TEST_LIST, VIDEO_ONLY_STREAMS_TEST_LIST, false); - List expected = Arrays.asList( + final List expected = Arrays.asList( "1080p60", "1080p", "720p60", "720p", "480p", "360p", "240p", "144p"); assertEquals(result.size(), expected.size()); for (int i = 0; i < result.size(); i++) { @@ -94,7 +94,7 @@ public class ListHelperTest { @Test public void getDefaultResolutionTest() { - List testList = Arrays.asList( + final List testList = Arrays.asList( new VideoStream("", MediaFormat.MPEG_4, /**/ "720p"), new VideoStream("", MediaFormat.v3GPP, /**/ "240p"), new VideoStream("", MediaFormat.WEBM, /**/ "480p"), @@ -290,7 +290,7 @@ public class ListHelperTest { @Test public void getVideoDefaultStreamIndexCombinations() { - List testList = Arrays.asList( + final List testList = Arrays.asList( new VideoStream("", MediaFormat.MPEG_4, /**/ "1080p"), new VideoStream("", MediaFormat.MPEG_4, /**/ "720p60"), new VideoStream("", MediaFormat.MPEG_4, /**/ "720p"), diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index 7c4a7a935..9728c6b8c 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -13,7 +13,7 @@ + lines="280,312"/>