Utilize var syntax for some local variables in some java files

This commit is contained in:
Yevhen Babiichuk (DustDFG) 2026-01-02 01:31:00 +02:00
parent 1fb2b4a42e
commit 66beedc805
78 changed files with 203 additions and 255 deletions

View File

@ -2,7 +2,6 @@ package org.schabi.newpipe;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.annotation.NonNull;
@ -121,7 +120,7 @@ public class App extends Application {
ServiceHelper.initServices(this);
// Initialize image loader
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final var prefs = PreferenceManager.getDefaultSharedPreferences(this);
PicassoHelper.init(this);
ImageStrategy.setPreferredImageQuality(PreferredImageQuality.fromPreferenceKey(this,
prefs.getString(getString(R.string.image_quality_key),
@ -147,8 +146,7 @@ public class App extends Application {
}
protected void setCookiesToDownloader(final DownloaderImpl downloader) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
getApplicationContext());
final var prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String key = getApplicationContext().getString(R.string.recaptcha_cookies_key);
downloader.setCookie(ReCaptchaActivity.RECAPTCHA_COOKIES_KEY, prefs.getString(key, null));
downloader.updateYoutubeRestrictedModeCookies(getApplicationContext());
@ -178,7 +176,7 @@ public class App extends Application {
errors = List.of(actualThrowable);
}
for (final Throwable error : errors) {
for (final var error : errors) {
if (isThrowableIgnored(error)) {
return;
}

View File

@ -28,7 +28,7 @@ import org.schabi.newpipe.util.NavigationHelper;
public class ExitActivity extends Activity {
public static void exitAndRemoveFromRecentApps(final Activity activity) {
final Intent intent = new Intent(activity, ExitActivity.class);
final var intent = new Intent(activity, ExitActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS

View File

@ -451,14 +451,14 @@ public class MainActivity extends AppCompatActivity {
}
private void enhancePeertubeMenu(final MenuItem menuItem) {
final PeertubeInstance currentInstance = PeertubeHelper.getCurrentInstance();
final var currentInstance = PeertubeHelper.getCurrentInstance();
menuItem.setTitle(currentInstance.getName());
final Spinner spinner = InstanceSpinnerLayoutBinding.inflate(LayoutInflater.from(this))
.getRoot();
final List<PeertubeInstance> instances = PeertubeHelper.getInstanceList(this);
final List<String> items = new ArrayList<>();
int defaultSelect = 0;
for (final PeertubeInstance instance : instances) {
for (final var instance : instances) {
items.add(instance.getName());
if (instance.getUrl().equals(currentInstance.getUrl())) {
defaultSelect = items.size() - 1;
@ -895,7 +895,7 @@ public class MainActivity extends AppCompatActivity {
}
}
};
final IntentFilter intentFilter = new IntentFilter();
final var intentFilter = new IntentFilter();
intentFilter.addAction(VideoDetailFragment.ACTION_PLAYER_STARTED);
ContextCompat.registerReceiver(this, broadcastReceiver, intentFilter,
ContextCompat.RECEIVER_EXPORTED);

View File

@ -2,7 +2,6 @@ package org.schabi.newpipe;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/*
@ -30,7 +29,7 @@ public class PanicResponderActivity extends Activity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
final var 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

View File

@ -30,10 +30,8 @@ public final class QueueItemMenuUtil {
final boolean hideDetails,
final FragmentManager fragmentManager,
final Context context) {
final ContextThemeWrapper themeWrapper =
new ContextThemeWrapper(context, R.style.DarkPopupMenu);
final PopupMenu popupMenu = new PopupMenu(themeWrapper, view);
final var themeWrapper = new ContextThemeWrapper(context, R.style.DarkPopupMenu);
final var popupMenu = new PopupMenu(themeWrapper, view);
popupMenu.inflate(R.menu.menu_play_queue_item);
if (hideDetails) {

View File

@ -8,7 +8,6 @@ import android.app.IntentService;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
@ -263,7 +262,7 @@ public class RouterActivity extends AppCompatActivity {
if (errorInfo.getRecaptchaUrl() != null) {
Toast.makeText(context, R.string.recaptcha_request_toast, Toast.LENGTH_LONG).show();
// Starting ReCaptcha Challenge Activity
final Intent intent = new Intent(context, ReCaptchaActivity.class);
final var intent = new Intent(context, ReCaptchaActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(ReCaptchaActivity.RECAPTCHA_URL_EXTRA, errorInfo.getRecaptchaUrl());
context.startActivity(intent);
@ -281,7 +280,7 @@ public class RouterActivity extends AppCompatActivity {
}
protected void showUnsupportedUrlDialog(final String url) {
final Context context = getThemeWrapperContext();
final var context = getThemeWrapperContext();
new AlertDialog.Builder(context)
.setTitle(R.string.unsupported_url)
.setMessage(R.string.unsupported_url_dialog_message)
@ -296,10 +295,9 @@ public class RouterActivity extends AppCompatActivity {
}
protected void onSuccess() {
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
final var preferences = PreferenceManager.getDefaultSharedPreferences(this);
final ChoiceAvailabilityChecker choiceChecker = new ChoiceAvailabilityChecker(
final var choiceChecker = new ChoiceAvailabilityChecker(
getChoicesForService(currentService, currentLinkType),
preferences.getString(getString(R.string.preferred_open_action_key),
getString(R.string.preferred_open_action_default)));
@ -411,7 +409,7 @@ public class RouterActivity extends AppCompatActivity {
}
private void showDialog(final List<AdapterChoiceItem> choices) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final var preferences = PreferenceManager.getDefaultSharedPreferences(this);
final Context themeWrapperContext = getThemeWrapperContext();
final LayoutInflater layoutInflater = LayoutInflater.from(themeWrapperContext);
@ -564,8 +562,7 @@ public class RouterActivity extends AppCompatActivity {
} else {
// LinkType.NONE is never present because it's filtered out before
// channels and playlist can be played as they contain a list of videos
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
final var preferences = PreferenceManager.getDefaultSharedPreferences(this);
final boolean isExtVideoEnabled = preferences.getBoolean(
getString(R.string.use_external_video_player_key), false);
final boolean isExtAudioEnabled = preferences.getBoolean(
@ -602,7 +599,7 @@ public class RouterActivity extends AppCompatActivity {
private void handleText() {
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);
final var intent = new Intent(getThemeWrapperContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
NavigationHelper.openSearch(getThemeWrapperContext(), serviceId, searchString);
@ -657,8 +654,8 @@ public class RouterActivity extends AppCompatActivity {
return;
}
final Intent intent = new Intent(this, FetcherService.class);
final Choice choice = new Choice(currentService.getServiceId(), currentLinkType,
final var intent = new Intent(this, FetcherService.class);
final var choice = new Choice(currentService.getServiceId(), currentLinkType,
currentUrl, selectedChoiceKey);
intent.putExtra(FetcherService.KEY_CHOICE, choice);
startService(intent);
@ -772,7 +769,7 @@ public class RouterActivity extends AppCompatActivity {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
&& !context.isChangingConfigurations()) {
// try to bring the activity back to front if minimised
final Intent i = new Intent(context, RouterActivity.class);
final var i = new Intent(context, RouterActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
@ -946,7 +943,7 @@ public class RouterActivity extends AppCompatActivity {
if (!(serializable instanceof Choice)) {
return;
}
final Choice playerChoice = (Choice) serializable;
final var playerChoice = (Choice) serializable;
handleChoice(playerChoice);
}
@ -992,8 +989,7 @@ public class RouterActivity extends AppCompatActivity {
final String backgroundPlayerKey = getString(R.string.background_player_key);
final String popupPlayerKey = getString(R.string.popup_player_key);
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
final var preferences = PreferenceManager.getDefaultSharedPreferences(this);
final boolean isExtVideoEnabled = preferences.getBoolean(
getString(R.string.use_external_video_player_key), false);
final boolean isExtAudioEnabled = preferences.getBoolean(

View File

@ -3,7 +3,6 @@ package org.schabi.newpipe.download;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewTreeObserver;
@ -27,7 +26,7 @@ public class DownloadActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
// Service
final Intent i = new Intent();
final var i = new Intent();
i.setClass(this, DownloadManagerService.class);
startService(i);
@ -74,7 +73,7 @@ public class DownloadActivity extends AppCompatActivity {
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
super.onCreateOptionsMenu(menu);
final MenuInflater inflater = getMenuInflater();
final var inflater = getMenuInflater();
inflater.inflate(R.menu.download_menu, menu);

View File

@ -219,7 +219,7 @@ public class DownloadDialog extends DialogFragment
this.subtitleStreamsAdapter = new StreamItemAdapter<>(wrappedSubtitleStreams);
updateSecondaryStreams();
final Intent intent = new Intent(context, DownloadManagerService.class);
final var intent = new Intent(context, DownloadManagerService.class);
context.startService(intent);
context.bindService(intent, new ServiceConnection() {
@ -248,16 +248,16 @@ public class DownloadDialog extends DialogFragment
* Update the displayed video streams based on the selected audio track.
*/
private void updateSecondaryStreams() {
final StreamInfoWrapper<AudioStream> audioStreams = getWrappedAudioStreams();
final var audioStreams = getWrappedAudioStreams();
final var secondaryStreams = new SparseArrayCompat<SecondaryStreamHelper<AudioStream>>(4);
final List<VideoStream> videoStreams = wrappedVideoStreams.getStreamsList();
final var videoStreams = wrappedVideoStreams.getStreamsList();
wrappedVideoStreams.resetInfo();
for (int i = 0; i < videoStreams.size(); i++) {
if (!videoStreams.get(i).isVideoOnly()) {
continue;
}
final AudioStream audioStream = SecondaryStreamHelper.getAudioStreamFor(
final var audioStream = SecondaryStreamHelper.getAudioStreamFor(
context, audioStreams.getStreamsList(), videoStreams.get(i));
if (audioStream != null) {
@ -717,7 +717,7 @@ public class DownloadDialog extends DialogFragment
int candidate = 0;
for (int i = 0; i < streams.size(); i++) {
final Locale streamLocale = streams.get(i).getLocale();
final var streamLocale = streams.get(i).getLocale();
final boolean languageEquals = streamLocale.getLanguage() != null
&& preferredLocalization.getLanguageCode() != null
@ -860,8 +860,7 @@ public class DownloadDialog extends DialogFragment
Toast.makeText(context, getString(R.
string.error_insufficient_storage), Toast.LENGTH_LONG).show();
// move the user to storage setting tab
final Intent storageSettingsIntent = new Intent(Settings.
ACTION_INTERNAL_STORAGE_SETTINGS);
final var storageSettingsIntent = new Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS);
if (storageSettingsIntent.resolveActivity(context.getPackageManager())
!= null) {
startActivity(storageSettingsIntent);

View File

@ -10,7 +10,6 @@ import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.IntentCompat;
@ -85,11 +84,11 @@ public class ErrorActivity extends AppCompatActivity {
activityErrorBinding = ActivityErrorBinding.inflate(getLayoutInflater());
setContentView(activityErrorBinding.getRoot());
final Intent intent = getIntent();
final var intent = getIntent();
setSupportActionBar(activityErrorBinding.toolbarLayout.toolbar);
final ActionBar actionBar = getSupportActionBar();
final var actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.error_report_title);
@ -157,7 +156,7 @@ public class ErrorActivity extends AppCompatActivity {
context.getString(R.string.privacy_policy_url)))
.setPositiveButton(R.string.accept, (dialog, which) -> {
if (action.equals("EMAIL")) { // send on email
final Intent i = new Intent(Intent.ACTION_SENDTO)
final var i = new Intent(Intent.ACTION_SENDTO)
.setData(Uri.parse("mailto:")) // only email apps should handle this
.putExtra(Intent.EXTRA_EMAIL, new String[]{ERROR_EMAIL_ADDRESS})
.putExtra(Intent.EXTRA_SUBJECT, ERROR_EMAIL_SUBJECT

View File

@ -2,7 +2,6 @@ package org.schabi.newpipe.error;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
@ -148,7 +147,7 @@ public class ReCaptchaActivity extends AppCompatActivity {
if (!foundCookies.isEmpty()) {
// save cookies to preferences
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
final var prefs = PreferenceManager.getDefaultSharedPreferences(
getApplicationContext());
final String key = getApplicationContext().getString(R.string.recaptcha_cookies_key);
prefs.edit().putString(key, foundCookies).apply();
@ -161,7 +160,7 @@ public class ReCaptchaActivity extends AppCompatActivity {
// Navigate to blank page (unloads youtube to prevent background playback)
recaptchaBinding.reCaptchaWebView.loadUrl("about:blank");
final Intent intent = new Intent(this, org.schabi.newpipe.MainActivity.class);
final var intent = new Intent(this, org.schabi.newpipe.MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, intent);
}

View File

@ -14,7 +14,7 @@ public class EmptyFragment extends BaseFragment {
private static final String SHOW_MESSAGE = "SHOW_MESSAGE";
public static final EmptyFragment newInstance(final boolean showMessage) {
final EmptyFragment emptyFragment = new EmptyFragment();
final var emptyFragment = new EmptyFragment();
final Bundle bundle = new Bundle(1);
bundle.putBoolean(SHOW_MESSAGE, showMessage);
emptyFragment.setArguments(bundle);

View File

@ -206,7 +206,7 @@ public abstract class BaseDescriptionFragment extends BaseFragment {
itemBinding.metadataTypeView.setText(type);
final SpannableStringBuilder urls = new SpannableStringBuilder();
for (final Image image : images) {
for (final var image : images) {
if (urls.length() != 0) {
urls.append(", ");
}
@ -255,7 +255,7 @@ public abstract class BaseDescriptionFragment extends BaseFragment {
final var itemBinding = ItemMetadataTagsBinding.inflate(inflater, layout, false);
tags.stream().sorted(String.CASE_INSENSITIVE_ORDER).forEach(tag -> {
final Chip chip = (Chip) inflater.inflate(R.layout.chip,
final var chip = (Chip) inflater.inflate(R.layout.chip,
itemBinding.metadataTagsChips, false);
chip.setText(tag);
chip.setOnClickListener(this::onTagClick);

View File

@ -299,13 +299,13 @@ public final class VideoDetailFragment
@Nullable final String url,
@NonNull final String name,
@Nullable final PlayQueue queue) {
final VideoDetailFragment instance = new VideoDetailFragment();
final var instance = new VideoDetailFragment();
instance.setInitialData(serviceId, url, name, queue);
return instance;
}
public static VideoDetailFragment getInstanceInCollapsedState() {
final VideoDetailFragment instance = new VideoDetailFragment();
final var instance = new VideoDetailFragment();
instance.updateBottomSheetState(BottomSheetBehavior.STATE_COLLAPSED);
return instance;
}
@ -319,7 +319,7 @@ public final class VideoDetailFragment
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
final var prefs = PreferenceManager.getDefaultSharedPreferences(activity);
showComments = prefs.getBoolean(getString(R.string.show_comments_key), true);
showRelatedItems = prefs.getBoolean(getString(R.string.show_next_video_key), true);
showDescription = prefs.getBoolean(getString(R.string.show_description_key), true);
@ -851,7 +851,7 @@ public final class VideoDetailFragment
}
private void runWorker(final boolean forceLoad, final boolean addToBackStack) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
final var prefs = PreferenceManager.getDefaultSharedPreferences(activity);
currentWorker = ExtractorHelper.getStreamInfo(serviceId, url, forceLoad)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
@ -1170,7 +1170,7 @@ public final class VideoDetailFragment
tryAddVideoPlayerView();
final Context context = requireContext();
final Intent playerIntent =
final var playerIntent =
NavigationHelper.getPlayerIntent(context, PlayerService.class, queue,
PlayerIntentType.AllOthers)
.putExtra(Player.PLAY_WHEN_READY, autoPlayEnabled)
@ -1430,7 +1430,7 @@ public final class VideoDetailFragment
}
}
};
final IntentFilter intentFilter = new IntentFilter();
final var intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_SHOW_MAIN_PLAYER);
intentFilter.addAction(ACTION_HIDE_MAIN_PLAYER);
intentFilter.addAction(ACTION_PLAYER_STARTED);
@ -1596,7 +1596,7 @@ public final class VideoDetailFragment
if (!info.getErrors().isEmpty()) {
// Bandcamp fan pages are not yet supported and thus a ContentNotAvailableException is
// thrown. This is not an error and thus should not be shown to the user.
for (final Throwable throwable : info.getErrors()) {
for (final var throwable : info.getErrors()) {
if (throwable instanceof ContentNotSupportedException
&& "Fan pages are not supported".equals(throwable.getMessage())) {
info.getErrors().remove(throwable);

View File

@ -104,7 +104,7 @@ public final class VideoDetailPlayerCrasher {
.setNegativeButton(R.string.cancel, null)
.create();
for (final Pair<String, Supplier<ExoPlaybackException>> entry : AVAILABLE_EXCEPTION_TYPES) {
for (final var entry : AVAILABLE_EXCEPTION_TYPES) {
final RadioButton radioButton = ListRadioIconItemBinding.inflate(inflater).getRoot();
radioButton.setText(entry.first);
radioButton.setChecked(false);

View File

@ -5,7 +5,6 @@ import static org.schabi.newpipe.ktx.ViewUtils.animate;
import static org.schabi.newpipe.ktx.ViewUtils.animateBackgroundColor;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
@ -39,7 +38,6 @@ import org.schabi.newpipe.error.ErrorUtil;
import org.schabi.newpipe.error.UserAction;
import org.schabi.newpipe.extractor.channel.ChannelInfo;
import org.schabi.newpipe.extractor.exceptions.ContentNotSupportedException;
import org.schabi.newpipe.extractor.linkhandler.ListLinkHandler;
import org.schabi.newpipe.fragments.BaseStateFragment;
import org.schabi.newpipe.fragments.detail.TabAdapter;
import org.schabi.newpipe.ktx.AnimationType;
@ -104,7 +102,7 @@ public class ChannelFragment extends BaseStateFragment<ChannelInfo>
public static ChannelFragment getInstance(final int serviceId, final String url,
final String name) {
final ChannelFragment instance = new ChannelFragment();
final var instance = new ChannelFragment();
instance.setInitialData(serviceId, url, name);
return instance;
}
@ -358,7 +356,7 @@ public class ChannelFragment extends BaseStateFragment<ChannelInfo>
if (DEBUG) {
Log.d(TAG, "No subscription to this channel!");
}
final SubscriptionEntity channel = new SubscriptionEntity();
final var channel = new SubscriptionEntity();
channel.setServiceId(info.getServiceId());
channel.setUrl(info.getUrl());
channel.setName(info.getName());
@ -470,11 +468,10 @@ public class ChannelFragment extends BaseStateFragment<ChannelInfo>
tabAdapter.clearAllItems();
if (currentInfo != null && !channelContentNotSupported) {
final Context context = requireContext();
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
final var context = requireContext();
final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
for (final ListLinkHandler linkHandler : currentInfo.getTabs()) {
for (final var linkHandler : currentInfo.getTabs()) {
final String tab = linkHandler.getContentFilters().get(0);
if (ChannelTabHelper.showChannelTab(context, preferences, tab)) {
final ChannelTabFragment channelTabFragment =
@ -627,7 +624,7 @@ public class ChannelFragment extends BaseStateFragment<ChannelInfo>
updateRssButton();
channelContentNotSupported = false;
for (final Throwable throwable : result.getErrors()) {
for (final var throwable : result.getErrors()) {
if (throwable instanceof ContentNotSupportedException) {
channelContentNotSupported = true;
showContentNotSupportedIfNeeded();

View File

@ -51,7 +51,7 @@ public class ChannelTabFragment extends BaseListInfoFragment<InfoItem, ChannelTa
public static ChannelTabFragment getInstance(final int serviceId,
final ListLinkHandler tabHandler,
final String channelName) {
final ChannelTabFragment instance = new ChannelTabFragment();
final var instance = new ChannelTabFragment();
instance.serviceId = serviceId;
instance.tabHandler = tabHandler;
instance.channelName = channelName;

View File

@ -31,7 +31,7 @@ public class CommentsFragment extends BaseListInfoFragment<CommentsInfoItem, Com
public static CommentsFragment getInstance(final int serviceId, final String url,
final String name) {
final CommentsFragment instance = new CommentsFragment();
final var instance = new CommentsFragment();
instance.setInitialData(serviceId, url, name);
return instance;
}

View File

@ -75,7 +75,7 @@ public class KioskFragment extends BaseListInfoFragment<StreamInfoItem, KioskInf
public static KioskFragment getInstance(final int serviceId, final String kioskId)
throws ExtractionException {
final KioskFragment instance = new KioskFragment();
final var instance = new KioskFragment();
final StreamingService service = NewPipe.getService(serviceId);
final ListLinkHandlerFactory kioskLinkHandlerFactory = service.getKioskList()
.getListLinkHandlerFactoryByType(kioskId);

View File

@ -94,7 +94,7 @@ public class PlaylistFragment extends BaseListInfoFragment<StreamInfoItem, Playl
public static PlaylistFragment getInstance(final int serviceId, final String url,
final String name) {
final PlaylistFragment instance = new PlaylistFragment();
final var instance = new PlaylistFragment();
instance.setInitialData(serviceId, url, name);
return instance;
}

View File

@ -9,7 +9,6 @@ import static java.util.Arrays.asList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
@ -203,7 +202,7 @@ public class SearchFragment extends BaseListFragment<SearchInfo, ListExtractor.I
public void onAttach(@NonNull final Context context) {
super.onAttach(context);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
final var prefs = PreferenceManager.getDefaultSharedPreferences(activity);
showLocalSuggestions = NewPipeSettings.showLocalSearchSuggestions(activity, prefs);
showRemoteSuggestions = NewPipeSettings.showRemoteSearchSuggestions(activity, prefs);

View File

@ -43,7 +43,7 @@ public class RelatedItemsFragment extends BaseListInfoFragment<InfoItem, Related
private RelatedItemsHeaderBinding headerBinding;
public static RelatedItemsFragment getInstance(final StreamInfo info) {
final RelatedItemsFragment instance = new RelatedItemsFragment();
final var instance = new RelatedItemsFragment();
instance.setInitialData(info);
return instance;
}
@ -78,8 +78,7 @@ public class RelatedItemsFragment extends BaseListInfoFragment<InfoItem, Related
headerBinding = RelatedItemsHeaderBinding
.inflate(activity.getLayoutInflater(), itemsList, false);
final SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(requireContext());
final var pref = PreferenceManager.getDefaultSharedPreferences(requireContext());
final boolean autoplay = pref.getBoolean(getString(R.string.auto_queue_key), false);
headerBinding.autoplaySwitch.setChecked(autoplay);
headerBinding.autoplaySwitch.setOnCheckedChangeListener((compoundButton, b) ->

View File

@ -113,7 +113,7 @@ public abstract class BaseLocalListFragment<I, N> extends BaseStateFragment<I>
int width = resources.getDimensionPixelSize(R.dimen.video_item_grid_thumbnail_image_width);
width += (24 * resources.getDisplayMetrics().density);
final int spanCount = Math.floorDiv(resources.getDisplayMetrics().widthPixels, width);
final GridLayoutManager lm = new GridLayoutManager(activity, spanCount);
final var lm = new GridLayoutManager(activity, spanCount);
lm.setSpanSizeLookup(itemListAdapter.getSpanSizeLookup(spanCount));
return lm;
}

View File

@ -117,10 +117,7 @@ public class HistoryRecordManager {
}
// Update the stream progress to the full duration of the video
final StreamStateEntity entity = new StreamStateEntity(
streamId,
duration * 1000
);
final var entity = new StreamStateEntity(streamId, duration * 1000);
streamStateTable.upsert(entity);
// Add a history entry
@ -194,8 +191,8 @@ public class HistoryRecordManager {
return Maybe.empty();
}
final OffsetDateTime currentTime = OffsetDateTime.now(ZoneOffset.UTC);
final SearchHistoryEntry newEntry = new SearchHistoryEntry(currentTime, serviceId, search);
final var currentTime = OffsetDateTime.now(ZoneOffset.UTC);
final var newEntry = new SearchHistoryEntry(currentTime, serviceId, search);
return Maybe.fromCallable(() -> database.runInTransaction(() -> {
final SearchHistoryEntry latestEntry = searchHistoryTable.getLatestEntry();
@ -283,7 +280,7 @@ public class HistoryRecordManager {
final List<? extends LocalItem> items) {
return Single.fromCallable(() -> {
final List<StreamStateEntity> result = new ArrayList<>(items.size());
for (final LocalItem item : items) {
for (final var item : items) {
final long streamId;
if (item instanceof StreamStatisticsEntry) {
streamId = ((StreamStatisticsEntry) item).getStreamId();

View File

@ -376,7 +376,7 @@ public class StatisticsPlaylistFragment
final List<LocalItem> infoItems = itemListAdapter.getItemsList();
final List<StreamInfoItem> streamInfoItems = new ArrayList<>(infoItems.size());
for (final LocalItem item : infoItems) {
for (final var item : infoItems) {
if (item instanceof StreamStatisticsEntry) {
streamInfoItems.add(((StreamStatisticsEntry) item).toStreamInfoItem());
}

View File

@ -111,7 +111,7 @@ public class LocalPlaylistFragment extends BaseLocalListFragment<List<PlaylistSt
private MainFragment.SelectedTabsPagerAdapter tabsPagerAdapter = null;
public static LocalPlaylistFragment getInstance(final long playlistId, final String name) {
final LocalPlaylistFragment instance = new LocalPlaylistFragment();
final var instance = new LocalPlaylistFragment();
instance.setInitialData(playlistId, name);
return instance;
}
@ -707,7 +707,7 @@ public class LocalPlaylistFragment extends BaseLocalListFragment<List<PlaylistSt
final List<LocalItem> items = itemListAdapter.getItemsList();
final List<Long> streamIds = new ArrayList<>(items.size());
for (final LocalItem item : items) {
for (final var item : items) {
if (item instanceof PlaylistStreamEntry) {
streamIds.add(((PlaylistStreamEntry) item).getStreamId());
}
@ -867,7 +867,7 @@ public class LocalPlaylistFragment extends BaseLocalListFragment<List<PlaylistSt
final List<LocalItem> infoItems = itemListAdapter.getItemsList();
final List<StreamInfoItem> streamInfoItems = new ArrayList<>(infoItems.size());
for (final LocalItem item : infoItems) {
for (final var item : infoItems) {
if (item instanceof PlaylistStreamEntry) {
streamInfoItems.add(((PlaylistStreamEntry) item).toStreamInfoItem());
}

View File

@ -94,14 +94,14 @@ public class LocalPlaylistManager {
public Completable updatePlaylists(final List<PlaylistMetadataEntry> updateItems,
final List<Long> deletedItems) {
final List<PlaylistEntity> items = new ArrayList<>(updateItems.size());
for (final PlaylistMetadataEntry item : updateItems) {
for (final var item : updateItems) {
items.add(new PlaylistEntity(item));
}
return Completable.fromRunnable(() -> database.runInTransaction(() -> {
for (final Long uid : deletedItems) {
playlistTable.deletePlaylist(uid);
}
for (final PlaylistEntity item : items) {
for (final var item : items) {
playlistTable.upsertPlaylist(item);
}
})).subscribeOn(Schedulers.io());

View File

@ -46,7 +46,7 @@ public class RemotePlaylistManager {
for (final Long uid: deletedItems) {
playlistRemoteTable.deletePlaylist(uid);
}
for (final PlaylistRemoteEntity item: updateItems) {
for (final var item: updateItems) {
playlistRemoteTable.upsert(item);
}
})).subscribeOn(Schedulers.io());
@ -54,7 +54,7 @@ public class RemotePlaylistManager {
public Single<Long> onBookmark(final PlaylistInfo playlistInfo) {
return Single.fromCallable(() -> {
final PlaylistRemoteEntity playlist = new PlaylistRemoteEntity(playlistInfo);
final var playlist = new PlaylistRemoteEntity(playlistInfo);
return playlistRemoteTable.upsert(playlist);
}).subscribeOn(Schedulers.io());
}

View File

@ -68,7 +68,7 @@ public class SubscriptionsImportFragment extends BaseFragment {
registerForActivityResult(new StartActivityForResult(), this::requestImportFileResult);
public static SubscriptionsImportFragment getInstance(final int serviceId) {
final SubscriptionsImportFragment instance = new SubscriptionsImportFragment();
final var instance = new SubscriptionsImportFragment();
instance.setInitialData(serviceId);
return instance;
}

View File

@ -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 (final SubscriptionItem item : items) {
for (final var item : items) {
writer.object();
writer.value(JSON_SERVICE_ID_KEY, item.getServiceId());
writer.value(JSON_URL_KEY, item.getUrl());

View File

@ -32,7 +32,6 @@ import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.schabi.newpipe.App;
import org.schabi.newpipe.R;
import org.schabi.newpipe.database.subscription.SubscriptionEntity;
import org.schabi.newpipe.extractor.subscription.SubscriptionItem;
import org.schabi.newpipe.streams.io.SharpOutputStream;
import org.schabi.newpipe.streams.io.StoredFileHelper;
@ -115,7 +114,7 @@ public class SubscriptionsExportService extends BaseImportExportService {
.map(subscriptionEntities -> {
final List<SubscriptionItem> result =
new ArrayList<>(subscriptionEntities.size());
for (final SubscriptionEntity entity : subscriptionEntities) {
for (final var entity : subscriptionEntities) {
result.add(new SubscriptionItem(entity.getServiceId(), entity.getUrl(),
entity.getName()));
}

View File

@ -292,9 +292,9 @@ public class SubscriptionsImportService extends BaseImportExportService {
return notificationList -> {
final List<Pair<ChannelInfo, List<ChannelTabInfo>>> infoList =
new ArrayList<>(notificationList.size());
for (final Notification<Pair<ChannelInfo, List<ChannelTabInfo>>> n : notificationList) {
if (n.isOnNext()) {
infoList.add(n.getValue());
for (final var notification : notificationList) {
if (notification.isOnNext()) {
infoList.add(notification.getValue());
}
}

View File

@ -183,7 +183,7 @@ public final class PlayQueueActivity extends AppCompatActivity
private void bind() {
// Note: this code should not really exist, and PlayerHolder should be used instead, but
// it will be rewritten when NewPlayer will replace the current player.
final Intent bindIntent = new Intent(this, PlayerService.class);
final var bindIntent = new Intent(this, PlayerService.class);
bindIntent.setAction(PlayerService.BIND_PLAYER_HOLDER_ACTION);
final boolean success = bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
if (!success) {

View File

@ -413,7 +413,7 @@ public final class Player implements PlaybackListener, Listener {
.subscribe(info -> {
final @Nullable PlayQueue oldPlayQueue = playQueue;
info.setStartPosition(data.getSeconds());
final PlayQueueItem playQueueItem = new PlayQueueItem(info);
final var playQueueItem = new PlayQueueItem(info);
// If the stream is already playing,
// we can just seek to the appropriate timestamp

View File

@ -154,7 +154,7 @@ public class AudioReactor implements AudioManager.OnAudioFocusChangeListener, An
notifyAudioSessionUpdate(true, audioSessionId);
}
private void notifyAudioSessionUpdate(final boolean active, final int audioSessionId) {
final Intent intent = new Intent(active
final var intent = new Intent(active
? AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION
: AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);

View File

@ -175,7 +175,7 @@ public final class PlayerHelper {
public static PlayQueue autoQueueOf(@NonNull final StreamInfo info,
@NonNull final List<PlayQueueItem> existingItems) {
final Set<String> urls = new HashSet<>(existingItems.size());
for (final PlayQueueItem item : existingItems) {
for (final var item : existingItems) {
urls.add(item.getUrl());
}

View File

@ -134,7 +134,7 @@ public final class PlayerHolder {
// and NullPointerExceptions inside the service because the service will be
// bound twice. Prevent it with unbinding first
unbind(context);
final Intent intent = new Intent(context, PlayerService.class);
final var intent = new Intent(context, PlayerService.class);
intent.putExtra(PlayerService.SHOULD_START_FOREGROUND_EXTRA, true);
ContextCompat.startForegroundService(context, intent);
serviceConnection.doPlayAfterConnect(playAfterConnect);
@ -221,7 +221,7 @@ public final class PlayerHolder {
}
private boolean bind(final Context context, final int flags) {
final Intent serviceIntent = new Intent(context, PlayerService.class);
final var serviceIntent = new Intent(context, PlayerService.class);
serviceIntent.setAction(PlayerService.BIND_PLAYER_HOLDER_ACTION);
return context.bindService(serviceIntent, serviceConnection, flags);
}

View File

@ -273,7 +273,7 @@ public final class NotificationUtil {
return NavigationHelper.getPlayQueueActivityIntent(player.getContext());
} else {
// We are playing in fragment. Don't open another activity just show fragment. That's it
final Intent intent = NavigationHelper.getPlayerIntent(
final var intent = NavigationHelper.getPlayerIntent(
player.getContext(), MainActivity.class, null,
PlayerIntentType.AllOthers);
intent.putExtra(Player.RESUME_PLAYBACK, true);

View File

@ -236,17 +236,17 @@ public class MediaSourceManager {
maybeRenewCurrentIndex();
break;
case REMOVE:
final RemoveEvent removeEvent = (RemoveEvent) event;
final var removeEvent = (RemoveEvent) event;
playlist.remove(removeEvent.getRemoveIndex());
break;
case MOVE:
final MoveEvent moveEvent = (MoveEvent) event;
final var moveEvent = (MoveEvent) event;
playlist.move(moveEvent.getFromIndex(), moveEvent.getToIndex());
break;
case REORDER:
// Need to move to ensure the playing index from play queue matches that of
// the source timeline, and then window correction can take care of the rest
final ReorderEvent reorderEvent = (ReorderEvent) event;
final var reorderEvent = (ReorderEvent) event;
playlist.move(reorderEvent.getFromSelectedIndex(),
reorderEvent.getToSelectedIndex());
break;

View File

@ -105,26 +105,26 @@ public class PlayQueueAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
// Do nothing.
break;
case SELECT:
final SelectEvent selectEvent = (SelectEvent) message;
final var selectEvent = (SelectEvent) message;
notifyItemChanged(selectEvent.getOldIndex());
notifyItemChanged(selectEvent.getNewIndex());
break;
case APPEND:
final AppendEvent appendEvent = (AppendEvent) message;
final var appendEvent = (AppendEvent) message;
notifyItemRangeInserted(playQueue.size(), appendEvent.getAmount());
break;
case ERROR:
final ErrorEvent errorEvent = (ErrorEvent) message;
final var errorEvent = (ErrorEvent) message;
notifyItemChanged(errorEvent.getErrorIndex());
notifyItemChanged(errorEvent.getQueueIndex());
break;
case REMOVE:
final RemoveEvent removeEvent = (RemoveEvent) message;
final var removeEvent = (RemoveEvent) message;
notifyItemRemoved(removeEvent.getRemoveIndex());
notifyItemChanged(removeEvent.getQueueIndex());
break;
case MOVE:
final MoveEvent moveEvent = (MoveEvent) message;
final var moveEvent = (MoveEvent) message;
notifyItemMoved(moveEvent.getFromIndex(), moveEvent.getToIndex());
break;
case INIT:

View File

@ -30,7 +30,7 @@ public final class SinglePlayQueue extends PlayQueue {
private static List<PlayQueueItem> playQueueItemsOf(@NonNull final List<StreamInfoItem> items) {
final List<PlayQueueItem> playQueueItems = new ArrayList<>(items.size());
for (final StreamInfoItem item : items) {
for (final var item : items) {
playQueueItems.add(new PlayQueueItem(item));
}
return playQueueItems;

View File

@ -728,7 +728,7 @@ public abstract class VideoPlayerUi extends PlayerUi implements SeekBar.OnSeekBa
}
protected void showOrHideButtons() {
@Nullable final PlayQueue playQueue = player.getPlayQueue();
@Nullable final var playQueue = player.getPlayQueue();
if (playQueue == null) {
return;
}
@ -1309,7 +1309,7 @@ public abstract class VideoPlayerUi extends PlayerUi implements SeekBar.OnSeekBa
final MediaItemTag.AudioTrack audioTrack =
currentMetadata.getMaybeAudioTrack().get();
final List<AudioStream> availableStreams = audioTrack.getAudioStreams();
final var availableStreams = audioTrack.getAudioStreams();
final int selectedStreamIndex = audioTrack.getSelectedAudioStreamIndex();
if (selectedStreamIndex == menuItemIndex || availableStreams.size() <= menuItemIndex) {
return;

View File

@ -108,9 +108,8 @@ public class BackupRestoreSettingsFragment extends BasePreferenceFragment {
builder.setCancelable(true);
builder.setPositiveButton(R.string.ok, (dialogInterface, i) -> {
// Deletes all shared preferences xml files.
final SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(requireContext());
sharedPreferences.edit().clear().apply();
final var prefs = PreferenceManager.getDefaultSharedPreferences(requireContext());
prefs.edit().clear().apply();
// Restarts the app
if (getActivity() == null) {
return;
@ -160,8 +159,7 @@ public class BackupRestoreSettingsFragment extends BasePreferenceFragment {
//checkpoint before export
executor.submit(NewPipeDatabase::checkpoint).get();
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(requireContext());
final var preferences = PreferenceManager.getDefaultSharedPreferences(requireContext());
manager.exportDatabase(preferences, file);
saveLastImportExportDataUri(exportDataUri); // save export path only on success
@ -206,8 +204,8 @@ public class BackupRestoreSettingsFragment extends BasePreferenceFragment {
})
.setPositiveButton(R.string.ok, (dialog, which) -> {
dialog.dismiss();
final Context context = requireContext();
final SharedPreferences prefs = PreferenceManager
final var context = requireContext();
final var prefs = PreferenceManager
.getDefaultSharedPreferences(context);
try {
if (hasJsonPrefs) {

View File

@ -1,6 +1,5 @@
package org.schabi.newpipe.settings;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
@ -51,7 +50,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
return loc != null ? loc.getDisplayName() : getString(R.string.systems_language);
});
newAppLanguagePref.setOnPreferenceClickListener(preference -> {
final Intent intent = new Intent(Settings.ACTION_APP_LOCALE_SETTINGS)
final var intent = new Intent(Settings.ACTION_APP_LOCALE_SETTINGS)
.setData(Uri.fromParts("package", requireContext().getPackageName(), null));
startActivity(intent);
return true;
@ -89,7 +88,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
@Override
public boolean onPreferenceTreeClick(final Preference preference) {
if (preference.getKey().equals(youtubeRestrictedModeEnabledKey)) {
final Context context = getContext();
final var context = getContext();
if (context != null) {
DownloaderImpl.getInstance().updateYoutubeRestrictedModeCookies(context);
} else {
@ -104,7 +103,7 @@ public class ContentSettingsFragment extends BasePreferenceFragment {
public void onDestroy() {
super.onDestroy();
final Context context = requireContext();
final var context = requireContext();
NewPipe.setupLocalization(
Localization.getPreferredLocalization(context),
Localization.getPreferredContentCountry(context));

View File

@ -1,6 +1,5 @@
package org.schabi.newpipe.settings;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.Nullable;
@ -21,8 +20,7 @@ public class ExoPlayerSettingsFragment extends BasePreferenceFragment {
getString(R.string.disabled_media_tunneling_automatically_key);
final SwitchPreferenceCompat disableMediaTunnelingPref =
(SwitchPreferenceCompat) requirePreference(R.string.disable_media_tunneling_key);
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(requireContext());
final var prefs = PreferenceManager.getDefaultSharedPreferences(requireContext());
final boolean mediaTunnelingAutomaticallyDisabled =
prefs.getInt(disabledMediaTunnelingAutomaticallyKey, -1) == 1;
final String summaryText = getString(R.string.disable_media_tunneling_summary);

View File

@ -80,7 +80,7 @@ public final class NewPipeSettings {
private static void saveDefaultDirectory(final Context context, final int keyID,
final String defaultDirectoryName) {
if (!useStorageAccessFramework(context)) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final var prefs = PreferenceManager.getDefaultSharedPreferences(context);
final String key = context.getString(keyID);
final String downloadPath = prefs.getString(key, null);
if (!isNullOrEmpty(downloadPath)) {
@ -112,7 +112,7 @@ public final class NewPipeSettings {
}
final String key = context.getString(R.string.storage_use_saf);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final var prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean(key, true);
}
@ -143,7 +143,7 @@ public final class NewPipeSettings {
}
private static void disableMediaTunnelingIfNecessary(@NonNull final Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final var prefs = PreferenceManager.getDefaultSharedPreferences(context);
final String disabledTunnelingKey = context.getString(R.string.disable_media_tunneling_key);
final String disabledTunnelingAutomaticallyKey =
context.getString(R.string.disabled_media_tunneling_automatically_key);
@ -170,7 +170,7 @@ public final class NewPipeSettings {
* @param context
*/
public static void setMediaTunneling(@NonNull final Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final var prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (!DeviceUtils.shouldSupportMediaTunneling()) {
prefs.edit()
.putBoolean(context.getString(R.string.disable_media_tunneling_key), true)

View File

@ -206,7 +206,7 @@ public class PeertubeInstanceListFragment extends Fragment {
}
binding.loadingProgressBar.setVisibility(View.VISIBLE);
final Disposable disposable = Single.fromCallable(() -> {
final PeertubeInstance instance = new PeertubeInstance(cleanUrl);
final var instance = new PeertubeInstance(cleanUrl);
instance.fetchInstanceMetaData();
return instance;
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

View File

@ -120,8 +120,7 @@ public class SelectPlaylistFragment extends DialogFragment {
final PlaylistMetadataEntry entry = ((PlaylistMetadataEntry) selectedItem);
onSelectedListener.onLocalPlaylistSelected(entry.getUid(), entry.getOrderingName());
} else if (selectedItem instanceof PlaylistRemoteEntity) {
final PlaylistRemoteEntity entry = ((PlaylistRemoteEntity) selectedItem);
} else if (selectedItem instanceof PlaylistRemoteEntity entry) {
onSelectedListener.onRemotePlaylistSelected(
entry.getServiceId(), entry.getUrl(), entry.getOrderingName());
}

View File

@ -1,6 +1,5 @@
package org.schabi.newpipe.settings;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
@ -92,8 +91,7 @@ public class SettingsActivity extends AppCompatActivity implements
Bridge.restoreInstanceState(this, savedInstanceBundle);
final boolean restored = savedInstanceBundle != null;
final SettingsLayoutBinding settingsLayoutBinding =
SettingsLayoutBinding.inflate(getLayoutInflater());
final var settingsLayoutBinding = SettingsLayoutBinding.inflate(getLayoutInflater());
setContentView(settingsLayoutBinding.getRoot());
initSearch(settingsLayoutBinding, restored);
@ -224,9 +222,9 @@ public class SettingsActivity extends AppCompatActivity implements
// Build search items
final Context searchContext = getApplicationContext();
final PreferenceParser parser = new PreferenceParser(searchContext, config);
final PreferenceSearcher searcher = new PreferenceSearcher(config);
final var searchContext = getApplicationContext();
final var parser = new PreferenceParser(searchContext, config);
final var searcher = new PreferenceSearcher(config);
// Find all searchable SettingsResourceRegistry fragments
SettingsResourceRegistry.getInstance().getAllEntries().stream()

View File

@ -139,7 +139,7 @@ public final class SettingsResourceRegistry {
if (o == null || getClass() != o.getClass()) {
return false;
}
final SettingRegistryEntry that = (SettingRegistryEntry) o;
final var that = (SettingRegistryEntry) o;
return getPreferencesResId() == that.getPreferencesResId()
&& getFragmentClass().equals(that.getFragmentClass());
}

View File

@ -260,7 +260,7 @@ public final class SettingMigrations {
// run migrations
int currentVersion = lastPrefVersion;
for (final Migration currentMigration : SETTING_MIGRATIONS) {
for (final var currentMigration : SETTING_MIGRATIONS) {
try {
if (currentMigration.shouldMigrate(currentVersion)) {
if (DEBUG) {

View File

@ -176,19 +176,19 @@ public class ChooseTabsFragment extends Fragment {
switch (type) {
case KIOSK:
final SelectKioskFragment selectKioskFragment = new SelectKioskFragment();
final var selectKioskFragment = new SelectKioskFragment();
selectKioskFragment.setOnSelectedListener((serviceId, kioskId, kioskName) ->
addTab(new Tab.KioskTab(serviceId, kioskId)));
selectKioskFragment.show(getParentFragmentManager(), "select_kiosk");
return;
case CHANNEL:
final SelectChannelFragment selectChannelFragment = new SelectChannelFragment();
final var selectChannelFragment = new SelectChannelFragment();
selectChannelFragment.setOnSelectedListener((serviceId, url, name) ->
addTab(new Tab.ChannelTab(serviceId, url, name)));
selectChannelFragment.show(getParentFragmentManager(), "select_channel");
return;
case PLAYLIST:
final SelectPlaylistFragment selectPlaylistFragment = new SelectPlaylistFragment();
final var selectPlaylistFragment = new SelectPlaylistFragment();
selectPlaylistFragment.setOnSelectedListener(
new SelectPlaylistFragment.OnSelectedListener() {
@Override
@ -205,8 +205,7 @@ public class ChooseTabsFragment extends Fragment {
selectPlaylistFragment.show(getParentFragmentManager(), "select_playlist");
return;
case FEEDGROUP:
final SelectFeedGroupFragment selectFeedGroupFragment =
new SelectFeedGroupFragment();
final var selectFeedGroupFragment = new SelectFeedGroupFragment();
selectFeedGroupFragment.setOnSelectedListener(
(groupId, name, iconId) ->
addTab(new Tab.FeedGroupTab(groupId, name, iconId)));

View File

@ -165,7 +165,7 @@ public class StoredFileHelper implements Serializable {
return new StoredFileHelper(treeUri, storage.srcName, storage.srcType, storage.tag);
}
final StoredFileHelper instance = new StoredFileHelper(context, treeUri,
final var instance = new StoredFileHelper(context, treeUri,
Uri.parse(storage.source), storage.tag);
// under SAF, if the target document is deleted, conserve the filename and mime

View File

@ -1,7 +1,6 @@
package org.schabi.newpipe.util;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.preference.PreferenceManager;
@ -25,7 +24,7 @@ public final class DependentPreferenceHelper {
* @return returns true if `Resume playback` and `Watch history` are both enabled
*/
public static boolean getResumePlaybackEnabled(final Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final var prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean(context.getString(
R.string.enable_watch_history_key), true)
@ -41,7 +40,7 @@ public final class DependentPreferenceHelper {
* @return returns true if `Positions in lists` and `Watch history` are both enabled
*/
public static boolean getPositionsInListsEnabled(final Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final var prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean(context.getString(
R.string.enable_watch_history_key), true)

View File

@ -172,7 +172,7 @@ public final class DeviceUtils {
public static boolean isDesktopMode(@NonNull final Context context) {
// Adapted from https://stackoverflow.com/a/64615568
// to check for all input devices that have an active cursor
final InputManager im = (InputManager) context.getSystemService(INPUT_SERVICE);
final var im = (InputManager) context.getSystemService(INPUT_SERVICE);
for (final int id : im.getInputDeviceIds()) {
final InputDevice inputDevice = im.getInputDevice(id);
if (inputDevice.supportsSource(InputDevice.SOURCE_BLUETOOTH_STYLUS)

View File

@ -22,7 +22,6 @@ package org.schabi.newpipe.util;
import static org.schabi.newpipe.extractor.utils.Utils.isNullOrEmpty;
import static org.schabi.newpipe.util.text.TextLinkifier.SET_LINK_MOVEMENT_METHOD;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
@ -300,7 +299,7 @@ public final class ExtractorHelper {
final TextView metaInfoTextView,
final View metaInfoSeparator,
final CompositeDisposable disposables) {
final Context context = metaInfoTextView.getContext();
final var context = metaInfoTextView.getContext();
if (metaInfos == null || metaInfos.isEmpty()
|| !PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
context.getString(R.string.show_meta_info_key), true)) {

View File

@ -62,7 +62,7 @@ public class FilePickerActivityHelper extends com.nononsenseapps.filepicker.File
final boolean allowCreateDir,
final boolean allowExistingFile,
final boolean singleClick) {
final CustomFilePickerFragment fragment = new CustomFilePickerFragment();
final var fragment = new CustomFilePickerFragment();
fragment.setArgs(startPath != null ? startPath
: Environment.getExternalStorageDirectory().getPath(),
mode, allowMultiple, allowCreateDir, allowExistingFile, singleClick);

View File

@ -1,7 +1,6 @@
package org.schabi.newpipe.util;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.preference.PreferenceManager;
@ -24,8 +23,7 @@ public final class FilenameUtils {
* @return the filename
*/
public static String createFilename(final Context context, final String title) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final String charsetLd = context.getString(R.string.charset_letters_and_digits_value);
final String charsetMs = context.getString(R.string.charset_most_special_value);

View File

@ -3,7 +3,6 @@ package org.schabi.newpipe.util;
import static org.schabi.newpipe.extractor.ServiceList.YouTube;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.ConnectivityManager;
@ -148,7 +147,7 @@ public final class ListHelper {
@Nullable final String trackId) {
if (trackId != null) {
for (int i = 0; i < audioStreams.size(); i++) {
final AudioStream s = audioStreams.get(i);
final var s = audioStreams.get(i);
if (s.getAudioTrackId() != null
&& s.getAudioTrackId().equals(trackId)) {
return i;
@ -235,8 +234,7 @@ public final class ListHelper {
@Nullable final List<VideoStream> videoOnlyStreams,
final boolean ascendingOrder,
final boolean preferVideoOnlyStreams) {
final SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
final boolean showHigherResolutions = preferences.getBoolean(
context.getString(R.string.show_higher_resolutions_key), false);
@ -301,7 +299,7 @@ public final class ListHelper {
final Comparator<AudioStream> cmp = getAudioFormatComparator(context);
for (final AudioStream stream : audioStreams) {
for (final var stream : audioStreams) {
if (stream.getDeliveryMethod() == DeliveryMethod.TORRENT
|| (stream.getDeliveryMethod() == DeliveryMethod.HLS
&& stream.getFormat() == MediaFormat.OPUS)) {
@ -342,7 +340,7 @@ public final class ListHelper {
final HashMap<String, List<AudioStream>> collectedStreams = new HashMap<>();
for (final AudioStream stream : audioStreams) {
for (final var stream : audioStreams) {
final String trackId = Objects.toString(stream.getAudioTrackId(), "");
if (collectedStreams.containsKey(trackId)) {
collectedStreams.get(trackId).add(stream);
@ -394,8 +392,7 @@ public final class ListHelper {
private static String computeDefaultResolution(@NonNull final Context context, final int key,
final int value) {
final SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
// Load the preferred resolution otherwise the best available
String resolution = preferences != null
@ -488,12 +485,12 @@ public final class ListHelper {
final HashMap<String, VideoStream> hashMap = new HashMap<>();
// Add all to the hashmap
for (final VideoStream videoStream : allInitialStreams) {
for (final var videoStream : allInitialStreams) {
hashMap.put(videoStream.getResolution(), videoStream);
}
// Override the values when the key == resolution, with the defaultFormat
for (final VideoStream videoStream : allInitialStreams) {
for (final var videoStream : allInitialStreams) {
if (videoStream.getFormat() == defaultFormat) {
hashMap.put(videoStream.getResolution(), videoStream);
}
@ -649,8 +646,7 @@ public final class ListHelper {
private static MediaFormat getDefaultFormat(@NonNull final Context context,
@StringRes final int defaultFormatKey,
@StringRes final int defaultFormatValueKey) {
final SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
final String defaultFormat = context.getString(defaultFormatValueKey);
final String defaultFormatString = preferences.getString(
@ -708,8 +704,7 @@ public final class ListHelper {
private static String getResolutionLimit(@NonNull final Context context) {
String resolutionLimit = null;
if (isMeteredNetwork(context)) {
final SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
final var 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);
@ -801,8 +796,7 @@ public final class ListHelper {
*/
private static Comparator<AudioStream> getAudioTrackComparator(
@NonNull final Context context) {
final SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
final Locale preferredLanguage = Localization.getPreferredLocale(context);
final boolean preferOriginalAudio =
preferences.getBoolean(context.getString(R.string.prefer_original_audio_key),

View File

@ -4,7 +4,6 @@ import static org.schabi.newpipe.MainActivity.DEBUG;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.icu.text.CompactDecimalFormat;
import android.os.Build;
@ -411,7 +410,7 @@ public final class Localization {
private static Locale getLocaleFromPrefs(@NonNull final Context context,
@StringRes final int prefKey) {
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
final var sp = PreferenceManager.getDefaultSharedPreferences(context);
final String defaultKey = context.getString(R.string.default_localization_key);
final String languageCode = sp.getString(context.getString(prefKey), defaultKey);
@ -450,7 +449,7 @@ public final class Localization {
// For reference, see
// https://android-developers.googleblog.com/2022/11/per-app-language-preferences-part-1.html
public static void migrateAppLanguageSettingIfNecessary(@NonNull final Context context) {
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
final var sp = PreferenceManager.getDefaultSharedPreferences(context);
final String appLanguageKey = context.getString(R.string.app_language_key);
final String appLanguageValue = sp.getString(appLanguageKey, null);
if (appLanguageValue != null) {

View File

@ -160,7 +160,7 @@ public final class NavigationHelper {
Toast.makeText(context, R.string.background_player_playing_toast, Toast.LENGTH_SHORT)
.show();
final Intent intent = getPlayerIntent(context, PlayerService.class, queue,
final var intent = getPlayerIntent(context, PlayerService.class, queue,
PlayerIntentType.AllOthers)
.putExtra(Player.PLAYER_TYPE, PlayerType.AUDIO)
.putExtra(Player.RESUME_PLAYBACK, resumePlayback);
@ -184,7 +184,7 @@ public final class NavigationHelper {
// slightly different behaviour than the normal play action: the latter resumes playback,
// the former doesn't. (note that enqueue can be triggered when nothing is playing only
// by long pressing the video detail fragment, playlist or channel controls
final Intent intent = getPlayerIntent(context, PlayerService.class, queue,
final var intent = getPlayerIntent(context, PlayerService.class, queue,
PlayerIntentType.Enqueue)
.putExtra(Player.RESUME_PLAYBACK, false)
.putExtra(Player.PLAYER_TYPE, playerType);
@ -307,7 +307,7 @@ public final class NavigationHelper {
mimeType = "";
}
final Intent intent = new Intent();
final var intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(stream.getContent()), mimeType);
intent.putExtra(Intent.EXTRA_TITLE, name);
@ -392,7 +392,7 @@ public final class NavigationHelper {
}
public static void showMiniPlayer(final FragmentManager fragmentManager) {
final VideoDetailFragment instance = VideoDetailFragment.getInstanceInCollapsedState();
final var instance = VideoDetailFragment.getInstanceInCollapsedState();
defaultTransaction(fragmentManager)
.replace(R.id.fragment_player_holder, instance)
.runOnCommit(() -> sendPlayerStartedEvent(instance.requireActivity()))
@ -450,7 +450,7 @@ public final class NavigationHelper {
// stream automatically if it's the first time it is being opened, but then
// onVideoDetailFragmentReady will kick in and start another loading process.
// See VideoDetailFragment.wasCleared() and its usage in doInitialLoadLogic().
final VideoDetailFragment instance = VideoDetailFragment
final var instance = VideoDetailFragment
.getInstance(serviceId, null, title, playQueue);
instance.setAutoPlay(autoPlay);
@ -581,7 +581,7 @@ public final class NavigationHelper {
public static void openSearch(final Context context, final int serviceId,
final String searchString) {
final Intent mIntent = new Intent(context, MainActivity.class);
final var 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);
@ -595,7 +595,7 @@ public final class NavigationHelper {
@Nullable final PlayQueue playQueue,
final boolean switchingPlayers) {
final Intent intent = getStreamIntent(context, serviceId, url, title)
final var intent = getStreamIntent(context, serviceId, url, title)
.putExtra(VideoDetailFragment.KEY_SWITCHING_PLAYERS, switchingPlayers);
if (playQueue != null) {
@ -620,7 +620,7 @@ public final class NavigationHelper {
final int serviceId,
final String url,
@NonNull final String title) {
final Intent intent = getOpenIntent(context, url, serviceId,
final var intent = getOpenIntent(context, url, serviceId,
StreamingService.LinkType.CHANNEL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Constants.KEY_TITLE, title);
@ -629,38 +629,38 @@ public final class NavigationHelper {
}
public static void openMainActivity(final Context context) {
final Intent mIntent = new Intent(context, MainActivity.class);
final var 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) {
final Intent mIntent = new Intent(context, RouterActivity.class);
final var mIntent = new Intent(context, RouterActivity.class);
mIntent.setData(Uri.parse(url));
context.startActivity(mIntent);
}
public static void openAbout(final Context context) {
final Intent intent = new Intent(context, AboutActivity.class);
final var intent = new Intent(context, AboutActivity.class);
context.startActivity(intent);
}
public static void openSettings(final Context context) {
final Intent intent = new Intent(context, SettingsActivity.class);
final var intent = new Intent(context, SettingsActivity.class);
context.startActivity(intent);
}
public static void openDownloads(final Activity activity) {
if (PermissionHelper.checkStoragePermissions(
activity, PermissionHelper.DOWNLOADS_REQUEST_CODE)) {
final Intent intent = new Intent(activity, DownloadActivity.class);
final var intent = new Intent(activity, DownloadActivity.class);
activity.startActivity(intent);
}
}
public static Intent getPlayQueueActivityIntent(final Context context) {
final Intent intent = new Intent(context, PlayQueueActivity.class);
final var intent = new Intent(context, PlayQueueActivity.class);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@ -668,7 +668,7 @@ public final class NavigationHelper {
}
public static void openPlayQueue(final Context context) {
final Intent intent = new Intent(context, PlayQueueActivity.class);
final var intent = new Intent(context, PlayQueueActivity.class);
context.startActivity(intent);
}
@ -678,7 +678,7 @@ public final class NavigationHelper {
private static Intent getOpenIntent(final Context context, final String url,
final int serviceId, final StreamingService.LinkType type) {
final Intent mIntent = new Intent(context, MainActivity.class);
final var 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);

View File

@ -1,7 +1,6 @@
package org.schabi.newpipe.util;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.preference.PreferenceManager;
@ -23,8 +22,7 @@ public final class PeertubeHelper {
private PeertubeHelper() { }
public static List<PeertubeInstance> getInstanceList(final Context context) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final String savedInstanceListKey = context.getString(R.string.peertube_instance_list_key);
final String savedJson = sharedPreferences.getString(savedInstanceListKey, null);
if (null == savedJson) {
@ -50,8 +48,7 @@ public final class PeertubeHelper {
public static PeertubeInstance selectInstance(final PeertubeInstance instance,
final Context context) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final String selectedInstanceKey =
context.getString(R.string.peertube_selected_instance_key);
final JsonStringWriter jsonWriter = JsonWriter.string().object();

View File

@ -120,7 +120,7 @@ public final class PermissionHelper {
public static boolean checkSystemAlertWindowPermission(final Context context) {
if (!Settings.canDrawOverlays(context)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
final Intent i = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
final var i = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
@ -148,7 +148,7 @@ public final class PermissionHelper {
.setMessage(Html.fromHtml(message, Html.FROM_HTML_MODE_COMPACT))
.setPositiveButton("OK", (dialog, which) -> {
// we dont need the package name here, since it wont do anything on >R
final Intent intent =
final var intent =
new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
try {
context.startActivity(intent);

View File

@ -98,8 +98,8 @@ public final class SerializedCache {
@NonNull
private <T extends Serializable> T clone(@NonNull final T item,
@NonNull final Class<T> type) throws Exception {
final ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream();
try (ObjectOutputStream objectOutput = new ObjectOutputStream(bytesOutput)) {
final var bytesOutput = new ByteArrayOutputStream();
try (var objectOutput = new ObjectOutputStream(bytesOutput)) {
objectOutput.writeObject(item);
objectOutput.flush();
}

View File

@ -3,7 +3,6 @@ package org.schabi.newpipe.util;
import static org.schabi.newpipe.extractor.ServiceList.SoundCloud;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
@ -184,8 +183,7 @@ public final class ServiceHelper {
public static void initService(final Context context, final int serviceId) {
if (serviceId == ServiceList.PeerTube.getServiceId()) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final String json = sharedPreferences.getString(context.getString(
R.string.peertube_selected_instance_key), null);
if (null == json) {
@ -198,9 +196,9 @@ public final class ServiceHelper {
} catch (final JsonParserException e) {
return;
}
final String name = jsonObject.getString("name");
final String url = jsonObject.getString("url");
final PeertubeInstance instance = new PeertubeInstance(url, name);
final var name = jsonObject.getString("name");
final var url = jsonObject.getString("url");
final var instance = new PeertubeInstance(url, name);
ServiceList.PeerTube.setInstance(instance);
}
}

View File

@ -30,7 +30,6 @@ import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.content.res.AppCompatResources;
@ -221,7 +220,7 @@ public final class ThemeHelper {
* @return the color
*/
public static int resolveColorFromAttr(final Context context, @AttrRes final int attrColor) {
final TypedValue value = new TypedValue();
final var value = new TypedValue();
context.getTheme().resolveAttribute(attrColor, value, true);
if (value.resourceId != 0) {
@ -240,7 +239,7 @@ public final class ThemeHelper {
*/
public static Drawable resolveDrawable(@NonNull final Context context,
@AttrRes final int attrResId) {
final TypedValue typedValue = new TypedValue();
final var typedValue = new TypedValue();
context.getTheme().resolveAttribute(attrResId, typedValue, true);
return AppCompatResources.getDrawable(context, typedValue.resourceId);
}
@ -286,7 +285,7 @@ public final class ThemeHelper {
public static void setTitleToAppCompatActivity(@Nullable final Activity activity,
final CharSequence title) {
if (activity instanceof AppCompatActivity) {
final ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar();
final var actionBar = ((AppCompatActivity) activity).getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(title);
}

View File

@ -80,12 +80,12 @@ public final class ZipHelper {
final String nameInZip,
final OutputStreamConsumer streamConsumer) throws IOException {
final byte[] bytes;
try (ByteArrayOutputStream byteOutput = new ByteArrayOutputStream()) {
try (var byteOutput = new ByteArrayOutputStream()) {
streamConsumer.acceptStream(byteOutput);
bytes = byteOutput.toByteArray();
}
try (ByteArrayInputStream byteInput = new ByteArrayInputStream(bytes)) {
try (var byteInput = new ByteArrayInputStream(bytes)) {
ZipHelper.addFileToZip(outZip, nameInZip, byteInput);
}
}
@ -101,9 +101,8 @@ public final class ZipHelper {
final String nameInZip,
final InputStream inputStream) throws IOException {
final byte[] data = new byte[BUFFER_SIZE];
try (BufferedInputStream bufferedInputStream =
new BufferedInputStream(inputStream, BUFFER_SIZE)) {
final ZipEntry entry = new ZipEntry(nameInZip);
try (var bufferedInputStream = new BufferedInputStream(inputStream, BUFFER_SIZE)) {
final var entry = new ZipEntry(nameInZip);
outZip.putNextEntry(entry);
int count;
while ((count = bufferedInputStream.read(data, 0, BUFFER_SIZE)) != -1) {
@ -125,7 +124,7 @@ public final class ZipHelper {
final String fileOnDisk) throws IOException {
return extractFileFromZip(zipFile, nameInZip, input -> {
// delete old file first
final File oldFile = new File(fileOnDisk);
final var oldFile = new File(fileOnDisk);
if (oldFile.exists()) {
if (!oldFile.delete()) {
throw new IOException("Could not delete " + fileOnDisk);
@ -133,7 +132,7 @@ public final class ZipHelper {
}
final byte[] data = new byte[BUFFER_SIZE];
try (FileOutputStream outFile = new FileOutputStream(fileOnDisk)) {
try (var outFile = new FileOutputStream(fileOnDisk)) {
int count;
while ((count = input.read(data)) != -1) {
outFile.write(data, 0, count);
@ -154,7 +153,7 @@ public final class ZipHelper {
final String nameInZip,
final InputStreamConsumer streamConsumer)
throws IOException {
try (ZipInputStream inZip = new ZipInputStream(new BufferedInputStream(
try (var inZip = new ZipInputStream(new BufferedInputStream(
new SharpInputStream(zipFile.getStream())))) {
ZipEntry ze;
while ((ze = inZip.getNextEntry()) != null) {
@ -175,7 +174,7 @@ public final class ZipHelper {
*/
public static boolean zipContainsFile(final StoredFileHelper zipFile, final String fileInZip)
throws Exception {
try (ZipInputStream inZip = new ZipInputStream(new BufferedInputStream(
try (var inZip = new ZipInputStream(new BufferedInputStream(
new SharpInputStream(zipFile.getStream())))) {
ZipEntry ze;
@ -189,7 +188,7 @@ public final class ZipHelper {
}
public static boolean isValidZipFile(final StoredFileHelper file) {
try (ZipInputStream ignored = new ZipInputStream(new BufferedInputStream(
try (var ignored = new ZipInputStream(new BufferedInputStream(
new SharpInputStream(file.getStream())))) {
return true;
} catch (final IOException ioe) {

View File

@ -55,7 +55,7 @@ public final class KoreUtils {
* @param streamUrl the url to the stream to play
*/
public static void playWithKore(final Context context, final Uri streamUrl) {
final Intent intent = new Intent(Intent.ACTION_VIEW)
final var intent = new Intent(Intent.ACTION_VIEW)
.setPackage(context.getString(R.string.kore_package))
.setData(streamUrl)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

View File

@ -52,7 +52,7 @@ public final class ShareUtils {
*/
public static void installApp(@NonNull final Context context, final String packageId) {
// Try market scheme
final Intent marketSchemeIntent = new Intent(Intent.ACTION_VIEW,
final var marketSchemeIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + packageId))
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (!tryOpenIntentInApp(context, marketSchemeIntent)) {
@ -80,9 +80,9 @@ public final class ShareUtils {
public static void openUrlInBrowser(@NonNull final Context context, final String url) {
// Target a generic http://, so we are sure to get a browser and not e.g. the yt app.
// Note that this requires the `http` schema to be added to `<queries>` in the manifest.
final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
final var browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
final var intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// See https://stackoverflow.com/a/58801285 and `setSelector` documentation
@ -166,7 +166,7 @@ public final class ShareUtils {
private static void openAppChooser(@NonNull final Context context,
@NonNull final Intent intent,
final boolean setTitleChooser) {
final Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
final var chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, intent);
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (setTitleChooser) {
@ -233,7 +233,7 @@ public final class ShareUtils {
@NonNull final String title,
final String content,
final String imagePreviewUrl) {
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
final var shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, content);
if (!TextUtils.isEmpty(title)) {

View File

@ -229,11 +229,10 @@ public final class TextLinkifier {
@NonNull final CompositeDisposable disposables,
@Nullable final Consumer<TextView> onCompletion) {
disposables.add(Single.fromCallable(() -> {
final Context context = textView.getContext();
final var context = textView.getContext();
// add custom click actions on web links
final SpannableStringBuilder textBlockLinked =
new SpannableStringBuilder(chars);
final var textBlockLinked = new SpannableStringBuilder(chars);
final URLSpan[] urls = textBlockLinked.getSpans(0, chars.length(),
URLSpan.class);

View File

@ -85,8 +85,7 @@ public final class FocusAwareDrawerLayout extends DrawerLayout {
for (int i = 0; i < getChildCount(); ++i) {
final View child = getChildAt(i);
final DrawerLayout.LayoutParams lp =
(DrawerLayout.LayoutParams) child.getLayoutParams();
final var lp = (DrawerLayout.LayoutParams) child.getLayoutParams();
if (lp.gravity == 0) {
content = child;

View File

@ -192,7 +192,7 @@ public final class FocusOverlayView extends Drawable implements
final View decor = window.getDecorView();
decor.getWindowVisibleDisplayFrame(displayRect);
final FocusOverlayView overlay = new FocusOverlayView(dialog.getContext());
final var overlay = new FocusOverlayView(dialog.getContext());
overlay.setBounds(0, 0, displayRect.width(), displayRect.height());
setupOverlay(window, overlay);
@ -205,19 +205,19 @@ public final class FocusOverlayView extends Drawable implements
final View decor = window.getDecorView();
decor.getWindowVisibleDisplayFrame(displayRect);
final FocusOverlayView overlay = new FocusOverlayView(activity);
final var 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) {
final ViewGroup decor = (ViewGroup) window.getDecorView();
final var decor = (ViewGroup) window.getDecorView();
decor.getOverlay().add(overlay);
fixFocusHierarchy(decor);
final ViewTreeObserver observer = decor.getViewTreeObserver();
final var observer = decor.getViewTreeObserver();
observer.addOnScrollChangedListener(overlay);
observer.addOnGlobalFocusChangeListener(overlay);
observer.addOnGlobalLayoutListener(overlay);

View File

@ -148,10 +148,10 @@ public class NewPipeRecyclerView extends RecyclerView {
return false;
}
final FocusFinder finder = FocusFinder.getInstance();
final var finder = FocusFinder.getInstance();
// try to use FocusFinder instead of adapter
final ViewGroup root = (ViewGroup) getRootView();
final var root = (ViewGroup) getRootView();
tempFocus.set(focusRect);
@ -165,7 +165,7 @@ public class NewPipeRecyclerView extends RecyclerView {
// look for focus in our ancestors, increasing search scope with each failure
// this provides much better locality than using FocusFinder with root
ViewGroup parent = (ViewGroup) getParent();
var parent = (ViewGroup) getParent();
while (parent != root) {
tempFocus.set(focusRect);

View File

@ -1,7 +1,6 @@
package org.schabi.newpipe.views;
import android.content.Context;
import android.text.method.MovementMethod;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
@ -42,7 +41,7 @@ public class NewPipeTextView extends AppCompatTextView {
// We need to set again the movement method after a text change because Android resets the
// movement method to the default one in the case where the text cannot be selected and
// text links are clickable (which is the default case in NewPipe).
final MovementMethod movementMethod = this.getMovementMethod();
final var movementMethod = this.getMovementMethod();
super.setText(text, type);
setMovementMethod(movementMethod);
}

View File

@ -82,7 +82,7 @@ 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
final ViewGroup recycler = (ViewGroup) focusedItem.getParent();
final var recycler = (ViewGroup) focusedItem.getParent();
final int sourcePosition = getPosition(focusedItem);
if (sourcePosition == 0 && listDirection < 0) {

View File

@ -132,7 +132,7 @@ public class DownloadMissionRecover extends Thread {
switch (mRecovery.getKind()) {
case 'a':
for (final AudioStream audio : mExtractor.getAudioStreams()) {
for (final var audio : mExtractor.getAudioStreams()) {
if (audio.getAverageBitrate() == mRecovery.getDesiredBitrate()
&& audio.getFormat() == mRecovery.getFormat()
&& audio.getDeliveryMethod() == DeliveryMethod.PROGRESSIVE_HTTP) {
@ -147,7 +147,7 @@ public class DownloadMissionRecover extends Thread {
videoStreams = mExtractor.getVideoOnlyStreams();
else
videoStreams = mExtractor.getVideoStreams();
for (final VideoStream video : videoStreams) {
for (final var video : videoStreams) {
if (video.getResolution().equals(mRecovery.getDesired())
&& video.getFormat() == mRecovery.getFormat()
&& video.getDeliveryMethod() == DeliveryMethod.PROGRESSIVE_HTTP) {

View File

@ -362,7 +362,7 @@ public class DownloadManagerService extends Service {
char kind, int threads, String source, String psName,
String[] psArgs, long nearLength,
ArrayList<MissionRecoveryInfo> recoveryInfo) {
final Intent intent = new Intent(context, DownloadManagerService.class)
final var intent = new Intent(context, DownloadManagerService.class)
.setAction(Intent.ACTION_RUN)
.putExtra(EXTRA_URLS, urls)
.putExtra(EXTRA_KIND, kind)

View File

@ -364,12 +364,12 @@ public class MissionAdapter extends Adapter<ViewHolder> implements Handler.Callb
private void shareFile(Mission mission) {
if (checkInvalidFile(mission)) return;
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
final var shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType(resolveMimeType(mission));
shareIntent.putExtra(Intent.EXTRA_STREAM, resolveShareableUri(mission));
shareIntent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
final Intent intent = createChooser(shareIntent, null);
final var intent = createChooser(shareIntent, null);
// unneeded to set a title to the chooser on Android P and higher because the system
// ignores this title on these versions
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) {

View File

@ -137,7 +137,7 @@ public class ImageStrategyTest {
@Test
public void testChoosePreferredImageMixed() {
for (final ResolutionLevel resolutionLevel : RESOLUTION_LEVELS) {
for (final var resolutionLevel : RESOLUTION_LEVELS) {
assertChoosePreferredImage("d", "b", "c", List.of(
img("a", ResolutionLevel.UNKNOWN),
img("b", 200, 100, resolutionLevel),
@ -146,7 +146,7 @@ public class ImageStrategyTest {
img("e", resolutionLevel)
));
}
for (final ResolutionLevel resolutionLevel : RESOLUTION_LEVELS) {
for (final var resolutionLevel : RESOLUTION_LEVELS) {
assertChoosePreferredImage("b", "b", "b", List.of(
img("a", ResolutionLevel.UNKNOWN),
img("b", 200, 100, resolutionLevel),