diff options
126 files changed, 832 insertions, 1327 deletions
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7f162e0d8..b20aab7b0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -201,10 +201,6 @@ android:value="de.danoeh.antennapod.activity.PreferenceActivity"/> </activity> - <meta-data - android:name="android.support.PARENT_ACTIVITY" - android:value="de.danoeh.antennapod.activity.PreferenceActivity"/> - <activity android:name=".activity.OnlineFeedViewActivity" android:configChanges="orientation" diff --git a/app/src/main/java/de/danoeh/antennapod/activity/AboutActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/AboutActivity.java index c835f8073..eef2fa4da 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/AboutActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/AboutActivity.java @@ -4,7 +4,7 @@ import android.content.res.TypedArray; import android.graphics.Color; import android.os.Build; import android.os.Bundle; -import android.support.v7.app.ActionBarActivity; +import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; @@ -30,7 +30,7 @@ import rx.schedulers.Schedulers; /** * Displays the 'about' screen */ -public class AboutActivity extends ActionBarActivity { +public class AboutActivity extends AppCompatActivity { private static final String TAG = AboutActivity.class.getSimpleName(); @@ -87,7 +87,7 @@ public class AboutActivity extends ActionBarActivity { res.recycle(); input = getAssets().open(filename); String webViewData = IOUtils.toString(input, Charset.defaultCharset()); - if(false == webViewData.startsWith("<!DOCTYPE html>")) { + if(!webViewData.startsWith("<!DOCTYPE html>")) { //webViewData = webViewData.replace("\n\n", "</p><p>"); webViewData = webViewData.replace("%", "%"); webViewData = diff --git a/app/src/main/java/de/danoeh/antennapod/activity/AudioplayerActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/AudioplayerActivity.java index e90681931..107afcbfe 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/AudioplayerActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/AudioplayerActivity.java @@ -341,11 +341,7 @@ public class AudioplayerActivity extends MediaplayerActivity implements NavDrawe @Override public boolean onOptionsItemSelected(MenuItem item) { - if (drawerToggle != null && drawerToggle.onOptionsItemSelected(item)) { - return true; - } else { - return super.onOptionsItemSelected(item); - } + return drawerToggle != null && drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override @@ -464,7 +460,7 @@ public class AudioplayerActivity extends MediaplayerActivity implements NavDrawe private DBReader.NavDrawerData navDrawerData; private void loadData() { - subscription = Observable.fromCallable(() -> DBReader.getNavDrawerData()) + subscription = Observable.fromCallable(DBReader::getNavDrawerData) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { diff --git a/app/src/main/java/de/danoeh/antennapod/activity/DirectoryChooserActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/DirectoryChooserActivity.java index 62e85120d..5fd69ef6a 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/DirectoryChooserActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/DirectoryChooserActivity.java @@ -243,7 +243,7 @@ public class DirectoryChooserActivity extends AppCompatActivity { @Override public void onEvent(int event, String path) { Log.d(TAG, "FileObserver received event " + event); - runOnUiThread(() -> refreshDirectory()); + runOnUiThread(DirectoryChooserActivity.this::refreshDirectory); } }; } diff --git a/app/src/main/java/de/danoeh/antennapod/activity/DownloadAuthenticationActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/DownloadAuthenticationActivity.java index 365c4216d..41b2debdc 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/DownloadAuthenticationActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/DownloadAuthenticationActivity.java @@ -5,7 +5,6 @@ import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; -import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; @@ -73,31 +72,25 @@ public class DownloadAuthenticationActivity extends ActionBarActivity { txtvDescription.setText(txtvDescription.getText() + ":\n\n" + request.getTitle()); - butCancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - setResult(Activity.RESULT_CANCELED); - finish(); - } + butCancel.setOnClickListener(v -> { + setResult(Activity.RESULT_CANCELED); + finish(); }); - butConfirm.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - String username = etxtUsername.getText().toString(); - String password = etxtPassword.getText().toString(); - request.setUsername(username); - request.setPassword(password); - Intent result = new Intent(); - result.putExtra(RESULT_REQUEST, request); - setResult(Activity.RESULT_OK, result); - - if (sendToDownloadRequester) { - if (BuildConfig.DEBUG) Log.d(TAG, "Sending request to DownloadRequester"); - DownloadRequester.getInstance().download(DownloadAuthenticationActivity.this, request); - } - finish(); + butConfirm.setOnClickListener(v -> { + String username = etxtUsername.getText().toString(); + String password = etxtPassword.getText().toString(); + request.setUsername(username); + request.setPassword(password); + Intent result = new Intent(); + result.putExtra(RESULT_REQUEST, request); + setResult(Activity.RESULT_OK, result); + + if (sendToDownloadRequester) { + if (BuildConfig.DEBUG) Log.d(TAG, "Sending request to DownloadRequester"); + DownloadRequester.getInstance().download(DownloadAuthenticationActivity.this, request); } + finish(); }); } diff --git a/app/src/main/java/de/danoeh/antennapod/activity/FeedInfoActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/FeedInfoActivity.java index 9116decb0..805d82cf9 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/FeedInfoActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/FeedInfoActivity.java @@ -139,20 +139,14 @@ public class FeedInfoActivity extends ActionBarActivity { Log.d(TAG, "Author is " + feed.getAuthor()); Log.d(TAG, "URL is " + feed.getDownload_url()); FeedPreferences prefs = feed.getPreferences(); - imgvCover.post(new Runnable() { - - @Override - public void run() { - Glide.with(FeedInfoActivity.this) - .load(feed.getImageUri()) - .placeholder(R.color.light_gray) - .error(R.color.light_gray) - .diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY) - .fitCenter() - .dontAnimate() - .into(imgvCover); - } - }); + imgvCover.post(() -> Glide.with(FeedInfoActivity.this) + .load(feed.getImageUri()) + .placeholder(R.color.light_gray) + .error(R.color.light_gray) + .diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY) + .fitCenter() + .dontAnimate() + .into(imgvCover)); txtvTitle.setText(feed.getTitle()); String description = feed.getDescription(); diff --git a/app/src/main/java/de/danoeh/antennapod/activity/FlattrAuthActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/FlattrAuthActivity.java index 3b10ba4c3..be1c9f9e6 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/FlattrAuthActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/FlattrAuthActivity.java @@ -9,17 +9,17 @@ import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; -import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; + +import org.shredzone.flattr4j.exception.FlattrException; + import de.danoeh.antennapod.BuildConfig; import de.danoeh.antennapod.R; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.util.flattr.FlattrUtils; import de.danoeh.antennapod.preferences.PreferenceController; -import org.shredzone.flattr4j.exception.FlattrException; - /** Guides the user through the authentication process */ public class FlattrAuthActivity extends ActionBarActivity { @@ -46,25 +46,19 @@ public class FlattrAuthActivity extends ActionBarActivity { butAuthenticate = (Button) findViewById(R.id.but_authenticate); butReturn = (Button) findViewById(R.id.but_return_home); - butReturn.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(FlattrAuthActivity.this, MainActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - } - }); + butReturn.setOnClickListener(v -> { + Intent intent = new Intent(FlattrAuthActivity.this, MainActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent); + }); - butAuthenticate.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - try { - FlattrUtils.startAuthProcess(FlattrAuthActivity.this); - } catch (FlattrException e) { - e.printStackTrace(); - } - } - }); + butAuthenticate.setOnClickListener(v -> { + try { + FlattrUtils.startAuthProcess(FlattrAuthActivity.this); + } catch (FlattrException e) { + e.printStackTrace(); + } + }); } public static FlattrAuthActivity getInstance() { diff --git a/app/src/main/java/de/danoeh/antennapod/activity/MainActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/MainActivity.java index 3ab6a0ab8..9b0733b43 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/MainActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/MainActivity.java @@ -657,7 +657,7 @@ public class MainActivity extends AppCompatActivity implements NavDrawerActivity }; private void loadData() { - subscription = Observable.fromCallable(() -> DBReader.getNavDrawerData()) + subscription = Observable.fromCallable(DBReader::getNavDrawerData) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { diff --git a/app/src/main/java/de/danoeh/antennapod/activity/MediaplayerActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/MediaplayerActivity.java index f02f87d06..50daf163f 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/MediaplayerActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/MediaplayerActivity.java @@ -387,18 +387,11 @@ public abstract class MediaplayerActivity extends AppCompatActivity implements O .getSleepTimerTimeLeft())); stDialog.positiveText(R.string.disable_sleeptimer_label); stDialog.negativeText(R.string.cancel_label); - stDialog.callback(new MaterialDialog.ButtonCallback() { - @Override - public void onPositive(MaterialDialog dialog) { - dialog.dismiss(); - controller.disableSleepTimer(); - } - - @Override - public void onNegative(MaterialDialog dialog) { - dialog.dismiss(); - } + stDialog.onPositive((dialog, which) -> { + dialog.dismiss(); + controller.disableSleepTimer(); }); + stDialog.onNegative((dialog, which) -> dialog.dismiss()); stDialog.build().show(); } break; @@ -464,9 +457,7 @@ public abstract class MediaplayerActivity extends AppCompatActivity implements O txtvPlaybackSpeed.setText(speedStr); } else if(fromUser) { float speed = Float.valueOf(UserPreferences.getPlaybackSpeed()); - barPlaybackSpeed.post(() -> { - barPlaybackSpeed.setProgress((int) (20 * speed) - 10); - }); + barPlaybackSpeed.post(() -> barPlaybackSpeed.setProgress((int) (20 * speed) - 10)); } } @@ -748,9 +739,7 @@ public abstract class MediaplayerActivity extends AppCompatActivity implements O } if (butRev != null) { - butRev.setOnClickListener(v -> { - onRewind(); - }); + butRev.setOnClickListener(v -> onRewind()); butRev.setOnLongClickListener(new View.OnLongClickListener() { int choice; @@ -787,14 +776,10 @@ public abstract class MediaplayerActivity extends AppCompatActivity implements O }); } - butPlay.setOnClickListener(v -> { - onPlayPause(); - }); + butPlay.setOnClickListener(v -> onPlayPause()); if (butFF != null) { - butFF.setOnClickListener(v -> { - onFastForward(); - }); + butFF.setOnClickListener(v -> onFastForward()); butFF.setOnLongClickListener(new View.OnLongClickListener() { int choice; @@ -832,9 +817,7 @@ public abstract class MediaplayerActivity extends AppCompatActivity implements O } if (butSkip != null) { - butSkip.setOnClickListener(v -> { - sendBroadcast(new Intent(PlaybackService.ACTION_SKIP_CURRENT_EPISODE)); - }); + butSkip.setOnClickListener(v -> sendBroadcast(new Intent(PlaybackService.ACTION_SKIP_CURRENT_EPISODE))); } } diff --git a/app/src/main/java/de/danoeh/antennapod/activity/OnlineFeedViewActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/OnlineFeedViewActivity.java index 60d671898..a53f9bdb8 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/OnlineFeedViewActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/OnlineFeedViewActivity.java @@ -7,8 +7,8 @@ import android.content.Intent; import android.os.Bundle; import android.os.Looper; import android.support.v4.app.NavUtils; -import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AlertDialog; +import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; @@ -79,7 +79,7 @@ import rx.schedulers.Schedulers; * If the feed cannot be downloaded or parsed, an error dialog will be displayed * and the activity will finish as soon as the error dialog is closed. */ -public class OnlineFeedViewActivity extends ActionBarActivity { +public class OnlineFeedViewActivity extends AppCompatActivity { private static final String TAG = "OnlineFeedViewActivity"; diff --git a/app/src/main/java/de/danoeh/antennapod/activity/OpmlFeedChooserActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/OpmlFeedChooserActivity.java index bc3e686e5..bc1a40b11 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/OpmlFeedChooserActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/OpmlFeedChooserActivity.java @@ -2,7 +2,7 @@ package de.danoeh.antennapod.activity; import android.content.Intent; import android.os.Bundle; -import android.support.v7.app.ActionBarActivity; +import android.support.v7.app.AppCompatActivity; import android.util.SparseBooleanArray; import android.view.Menu; import android.view.MenuInflater; @@ -22,7 +22,7 @@ import de.danoeh.antennapod.core.preferences.UserPreferences; * Displays the feeds that the OPML-Importer has read and lets the user choose * which feeds he wants to import. */ -public class OpmlFeedChooserActivity extends ActionBarActivity { +public class OpmlFeedChooserActivity extends AppCompatActivity { private static final String TAG = "OpmlFeedChooserActivity"; public static final String EXTRA_SELECTED_ITEMS = "de.danoeh.antennapod.selectedItems"; diff --git a/app/src/main/java/de/danoeh/antennapod/activity/OpmlImportBaseActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/OpmlImportBaseActivity.java index fb145db1f..8726af281 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/OpmlImportBaseActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/OpmlImportBaseActivity.java @@ -6,7 +6,7 @@ import android.net.Uri; import android.os.Environment; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; -import android.support.v7.app.ActionBarActivity; +import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.afollestad.materialdialogs.MaterialDialog; @@ -26,7 +26,7 @@ import de.danoeh.antennapod.core.util.LangUtils; /** * Base activity for Opml Import - e.g. with code what to do afterwards * */ -public class OpmlImportBaseActivity extends ActionBarActivity { +public class OpmlImportBaseActivity extends AppCompatActivity { private static final String TAG = "OpmlImportBaseActivity"; private OpmlImportWorker importWorker; diff --git a/app/src/main/java/de/danoeh/antennapod/activity/OpmlImportFromPathActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/OpmlImportFromPathActivity.java index 15d97cc2c..b781e5141 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/OpmlImportFromPathActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/OpmlImportFromPathActivity.java @@ -53,7 +53,7 @@ public class OpmlImportFromPathActivity extends OpmlImportBaseActivity { intentPickAction = new Intent(Intent.ACTION_PICK); intentPickAction.setData(Uri.parse("file://")); - if(false == IntentUtils.isCallable(getApplicationContext(), intentPickAction)) { + if(!IntentUtils.isCallable(getApplicationContext(), intentPickAction)) { intentPickAction.setData(null); if(false == IntentUtils.isCallable(getApplicationContext(), intentPickAction)) { txtvHeaderExplanation1.setVisibility(View.GONE); @@ -70,7 +70,7 @@ public class OpmlImportFromPathActivity extends OpmlImportBaseActivity { intentGetContentAction = new Intent(Intent.ACTION_GET_CONTENT); intentGetContentAction.addCategory(Intent.CATEGORY_OPENABLE); intentGetContentAction.setType("*/*"); - if(false == IntentUtils.isCallable(getApplicationContext(), intentGetContentAction)) { + if(!IntentUtils.isCallable(getApplicationContext(), intentGetContentAction)) { txtvHeaderExplanation2.setVisibility(View.GONE); txtvExplanation2.setVisibility(View.GONE); findViewById(R.id.divider2).setVisibility(View.GONE); diff --git a/app/src/main/java/de/danoeh/antennapod/activity/PreferenceActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/PreferenceActivity.java index 80ccb7c99..ba22a42b4 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/PreferenceActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/PreferenceActivity.java @@ -8,7 +8,7 @@ import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.v7.app.ActionBar; -import android.support.v7.app.ActionBarActivity; +import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; @@ -24,7 +24,7 @@ import de.danoeh.antennapod.preferences.PreferenceController; * PreferenceActivity for API 11+. In order to change the behavior of the preference UI, see * PreferenceController. */ -public class PreferenceActivity extends ActionBarActivity { +public class PreferenceActivity extends AppCompatActivity { private PreferenceController preferenceController; private MainFragment prefFragment; @@ -49,7 +49,7 @@ public class PreferenceActivity extends ActionBarActivity { protected void onCreate(Bundle savedInstanceState) { // This must be the FIRST thing we do, otherwise other code may not have the // reference it needs - instance = new WeakReference<PreferenceActivity>(this); + instance = new WeakReference<>(this); setTheme(UserPreferences.getTheme()); super.onCreate(savedInstanceState); diff --git a/app/src/main/java/de/danoeh/antennapod/activity/gpoddernet/GpodnetAuthenticationActivity.java b/app/src/main/java/de/danoeh/antennapod/activity/gpoddernet/GpodnetAuthenticationActivity.java index 28c2b7206..e5418c924 100644 --- a/app/src/main/java/de/danoeh/antennapod/activity/gpoddernet/GpodnetAuthenticationActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/activity/gpoddernet/GpodnetAuthenticationActivity.java @@ -5,7 +5,6 @@ import android.content.Intent; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Bundle; -import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.LayoutInflater; @@ -42,7 +41,7 @@ import de.danoeh.antennapod.core.service.GpodnetSyncService; * Step 3: Choose from a list of actions */ public class GpodnetAuthenticationActivity extends ActionBarActivity { - private static final String TAG = "GpodnetAuthenticationActivity"; + private static final String TAG = "GpodnetAuthActivity"; private static final String CURRENT_STEP = "current_step"; @@ -177,7 +176,7 @@ public class GpodnetAuthenticationActivity extends ActionBarActivity { // load device list - final AtomicReference<List<GpodnetDevice>> devices = new AtomicReference<List<GpodnetDevice>>(); + final AtomicReference<List<GpodnetDevice>> devices = new AtomicReference<>(); new AsyncTask<GpodnetService, Void, List<GpodnetDevice>>() { private volatile Exception exception; @@ -194,11 +193,11 @@ public class GpodnetAuthenticationActivity extends ActionBarActivity { protected void onPostExecute(List<GpodnetDevice> gpodnetDevices) { super.onPostExecute(gpodnetDevices); if (gpodnetDevices != null) { - List<String> deviceNames = new ArrayList<String>(); + List<String> deviceNames = new ArrayList<>(); for (GpodnetDevice device : gpodnetDevices) { deviceNames.add(device.getCaption()); } - spinnerDevices.setAdapter(new ArrayAdapter<String>(GpodnetAuthenticationActivity.this, + spinnerDevices.setAdapter(new ArrayAdapter<>(GpodnetAuthenticationActivity.this, android.R.layout.simple_spinner_dropdown_item, deviceNames)); spinnerDevices.setEnabled(true); if (!deviceNames.isEmpty()) { @@ -274,14 +273,11 @@ public class GpodnetAuthenticationActivity extends ActionBarActivity { }); deviceID.setText(generateDeviceID()); - chooseDevice.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - final int position = spinnerDevices.getSelectedItemPosition(); - if (position != AdapterView.INVALID_POSITION) { - selectedDevice = devices.get().get(position); - advance(); - } + chooseDevice.setOnClickListener(v -> { + final int position = spinnerDevices.getSelectedItemPosition(); + if (position != AdapterView.INVALID_POSITION) { + selectedDevice = devices.get().get(position); + advance(); } }); } @@ -325,20 +321,14 @@ public class GpodnetAuthenticationActivity extends ActionBarActivity { final Button sync = (Button) view.findViewById(R.id.butSyncNow); final Button back = (Button) view.findViewById(R.id.butGoMainscreen); - sync.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - GpodnetSyncService.sendSyncIntent(GpodnetAuthenticationActivity.this); - finish(); - } + sync.setOnClickListener(v -> { + GpodnetSyncService.sendSyncIntent(GpodnetAuthenticationActivity.this); + finish(); }); - back.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(GpodnetAuthenticationActivity.this, MainActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - } + back.setOnClickListener(v -> { + Intent intent = new Intent(GpodnetAuthenticationActivity.this, MainActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent); }); } diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/ActionButtonCallback.java b/app/src/main/java/de/danoeh/antennapod/adapter/ActionButtonCallback.java index a75789815..66e6f9a00 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/ActionButtonCallback.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/ActionButtonCallback.java @@ -4,5 +4,5 @@ import de.danoeh.antennapod.core.feed.FeedItem; public interface ActionButtonCallback { /** Is called when the action button of a list item has been pressed. */ - abstract void onActionButtonPressed(FeedItem item); + void onActionButtonPressed(FeedItem item); } diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/AdapterUtils.java b/app/src/main/java/de/danoeh/antennapod/adapter/AdapterUtils.java index 935a0dcd4..8aaf0055a 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/AdapterUtils.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/AdapterUtils.java @@ -50,7 +50,7 @@ public class AdapterUtils { Log.d(TAG, "size: " + media.getSize()); if (media.getSize() > 0) { txtvPos.setText(Converter.byteToString(media.getSize())); - } else if(NetworkUtils.isDownloadAllowed() && false == media.checkedOnSizeButUnknown()) { + } else if(NetworkUtils.isDownloadAllowed() && !media.checkedOnSizeButUnknown()) { txtvPos.setText("{fa-spinner}"); Iconify.addIcons(txtvPos); NetworkUtils.getFeedMediaSizeObservable(media) diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/AllEpisodesRecycleAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/AllEpisodesRecycleAdapter.java index 07f895468..d141e0239 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/AllEpisodesRecycleAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/AllEpisodesRecycleAdapter.java @@ -121,7 +121,7 @@ public class AllEpisodesRecycleAdapter extends RecyclerView.Adapter<AllEpisodesR holder.title.setText(item.getTitle()); String pubDateStr = DateUtils.formatAbbrev(mainActivityRef.get(), item.getPubDate()); holder.pubDate.setText(pubDateStr); - if (showOnlyNewEpisodes || false == item.isNew()) { + if (showOnlyNewEpisodes || !item.isNew()) { holder.statusUnread.setVisibility(View.INVISIBLE); } else { holder.statusUnread.setVisibility(View.VISIBLE); @@ -135,7 +135,7 @@ public class AllEpisodesRecycleAdapter extends RecyclerView.Adapter<AllEpisodesR holder.txtvDuration.setText(Converter.getDurationStringLong(media.getDuration())); } else if (media.getSize() > 0) { holder.txtvDuration.setText(Converter.byteToString(media.getSize())); - } else if(NetworkUtils.isDownloadAllowed() && false == media.checkedOnSizeButUnknown()) { + } else if(NetworkUtils.isDownloadAllowed() && !media.checkedOnSizeButUnknown()) { holder.txtvDuration.setText("{fa-spinner}"); Iconify.addIcons(holder.txtvDuration); NetworkUtils.getFeedMediaSizeObservable(media) diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/ChaptersListAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/ChaptersListAdapter.java index 8bde1097b..37e00ab74 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/ChaptersListAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/ChaptersListAdapter.java @@ -109,7 +109,7 @@ public class ChaptersListAdapter extends ArrayAdapter<Chapter> { if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget); - } else if (action == MotionEvent.ACTION_DOWN) { + } else if (action == MotionEvent.ACTION_DOWN){ Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/DefaultActionButtonCallback.java b/app/src/main/java/de/danoeh/antennapod/adapter/DefaultActionButtonCallback.java index 469a807e1..00ab96f6c 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/DefaultActionButtonCallback.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/DefaultActionButtonCallback.java @@ -1,9 +1,7 @@ package de.danoeh.antennapod.adapter; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; -import android.support.v7.app.AlertDialog; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/DownloadLogAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/DownloadLogAdapter.java index 34999757f..a017983f0 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/DownloadLogAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/DownloadLogAdapter.java @@ -11,7 +11,6 @@ import android.widget.BaseAdapter; import android.widget.TextView; import android.widget.Toast; -import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.widget.IconButton; import com.joanzapata.iconify.widget.IconTextView; diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/DownloadlistAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/DownloadlistAdapter.java index 4a0ff1f12..e1efdaa7b 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/DownloadlistAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/DownloadlistAdapter.java @@ -131,11 +131,11 @@ public class DownloadlistAdapter extends BaseAdapter { } public interface ItemAccess { - public int getCount(); + int getCount(); - public Downloader getItem(int position); + Downloader getItem(int position); - public void onSecondaryActionClick(Downloader downloader); + void onSecondaryActionClick(Downloader downloader); } } diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/FeedItemlistAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/FeedItemlistAdapter.java index 7ca8d6a31..0de1ca1ff 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/FeedItemlistAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/FeedItemlistAdapter.java @@ -189,13 +189,12 @@ public class FeedItemlistAdapter extends BaseAdapter { holder.type.setImageBitmap(null); holder.type.setVisibility(View.GONE); } + typeDrawables.recycle(); if(media.isCurrentlyPlaying()) { - if(media.isCurrentlyPlaying()) { - holder.container.setBackgroundColor(playingBackGroundColor); - } else { - holder.container.setBackgroundColor(normalBackGroundColor); - } + holder.container.setBackgroundColor(playingBackGroundColor); + } else { + holder.container.setBackgroundColor(normalBackGroundColor); } } diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/NavListAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/NavListAdapter.java index 6d7e6dcac..ec1e18ee8 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/NavListAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/NavListAdapter.java @@ -73,7 +73,7 @@ public class NavListAdapter extends BaseAdapter } private void loadItems() { - List<String> newTags = new ArrayList<String>(Arrays.asList(MainActivity.NAV_DRAWER_TAGS)); + List<String> newTags = new ArrayList<>(Arrays.asList(MainActivity.NAV_DRAWER_TAGS)); List<String> hiddenFragments = UserPreferences.getHiddenDrawerItems(); for(String hidden : hiddenFragments) { newTags.remove(hidden); @@ -236,13 +236,13 @@ public class NavListAdapter extends BaseAdapter holder.count.setText("{md-disc-full 150%}"); Iconify.addIcons(holder.count); holder.count.setVisibility(View.VISIBLE); - holder.count.setOnClickListener(v -> { + holder.count.setOnClickListener(v -> new AlertDialog.Builder(context) .setTitle(R.string.episode_cache_full_title) .setMessage(R.string.episode_cache_full_message) .setPositiveButton(android.R.string.ok, (dialog, which) -> {}) - .show(); - }); + .show() + ); } else { holder.count.setVisibility(View.GONE); } diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/QueueRecyclerAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/QueueRecyclerAdapter.java index 6cf61f90b..981d7563a 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/QueueRecyclerAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/QueueRecyclerAdapter.java @@ -258,7 +258,7 @@ public class QueueRecyclerAdapter extends RecyclerView.Adapter<QueueRecyclerAdap } else { if(media.getSize() > 0) { progressLeft.setText(Converter.byteToString(media.getSize())); - } else if(NetworkUtils.isDownloadAllowed() && false == media.checkedOnSizeButUnknown()) { + } else if(NetworkUtils.isDownloadAllowed() && !media.checkedOnSizeButUnknown()) { progressLeft.setText("{fa-spinner}"); Iconify.addIcons(progressLeft); NetworkUtils.getFeedMediaSizeObservable(media) diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/SearchlistAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/SearchlistAdapter.java index 83f5dcb4d..c15dd4ac6 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/SearchlistAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/SearchlistAdapter.java @@ -9,7 +9,6 @@ import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; -import com.bumptech.glide.load.engine.DiskCacheStrategy; import de.danoeh.antennapod.R; import de.danoeh.antennapod.core.feed.Feed; @@ -112,7 +111,7 @@ public class SearchlistAdapter extends BaseAdapter { TextView subtitle; } - public static interface ItemAccess { + public interface ItemAccess { int getCount(); SearchResult getItem(int position); diff --git a/app/src/main/java/de/danoeh/antennapod/adapter/gpodnet/PodcastListAdapter.java b/app/src/main/java/de/danoeh/antennapod/adapter/gpodnet/PodcastListAdapter.java index 743f9fc86..aea3d583f 100644 --- a/app/src/main/java/de/danoeh/antennapod/adapter/gpodnet/PodcastListAdapter.java +++ b/app/src/main/java/de/danoeh/antennapod/adapter/gpodnet/PodcastListAdapter.java @@ -9,7 +9,6 @@ import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; -import com.bumptech.glide.load.engine.DiskCacheStrategy; import org.apache.commons.lang3.StringUtils; diff --git a/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlExportWorker.java b/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlExportWorker.java index 5c24c2822..13abb26ea 100644 --- a/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlExportWorker.java +++ b/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlExportWorker.java @@ -3,7 +3,6 @@ package de.danoeh.antennapod.asynctask; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; @@ -80,14 +79,7 @@ public class OpmlExportWorker extends AsyncTask<Void, Void, Void> { progDialog.dismiss(); AlertDialog.Builder alert = new AlertDialog.Builder(context) .setNeutralButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, - int which) { - dialog.dismiss(); - } - }); + (dialog, which) -> dialog.dismiss()); if (exception != null) { alert.setTitle(R.string.export_error_label); alert.setMessage(exception.getMessage()); diff --git a/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlFeedQueuer.java b/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlFeedQueuer.java index cc27b6c9d..1cb653f01 100644 --- a/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlFeedQueuer.java +++ b/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlFeedQueuer.java @@ -43,9 +43,8 @@ public class OpmlFeedQueuer extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { DownloadRequester requester = DownloadRequester.getInstance(); - for (int idx = 0; idx < selection.length; idx++) { - OpmlElement element = OpmlImportHolder.getReadElements().get( - selection[idx]); + for (int selected : selection) { + OpmlElement element = OpmlImportHolder.getReadElements().get(selected); Feed feed = new Feed(element.getXmlUrl(), null, element.getText()); try { diff --git a/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlImportWorker.java b/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlImportWorker.java index 86636485d..45ec6c5fa 100644 --- a/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlImportWorker.java +++ b/app/src/main/java/de/danoeh/antennapod/asynctask/OpmlImportWorker.java @@ -3,21 +3,20 @@ package de.danoeh.antennapod.asynctask; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import android.util.Log; -import de.danoeh.antennapod.core.BuildConfig; -import de.danoeh.antennapod.core.R; -import de.danoeh.antennapod.core.opml.OpmlElement; -import de.danoeh.antennapod.core.opml.OpmlReader; + import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; +import de.danoeh.antennapod.core.R; +import de.danoeh.antennapod.core.opml.OpmlElement; +import de.danoeh.antennapod.core.opml.OpmlReader; + public class OpmlImportWorker extends AsyncTask<Void, Void, ArrayList<OpmlElement>> { private static final String TAG = "OpmlImportWorker"; diff --git a/app/src/main/java/de/danoeh/antennapod/config/DBTasksCallbacksImpl.java b/app/src/main/java/de/danoeh/antennapod/config/DBTasksCallbacksImpl.java index 9f8af1142..c3f7ae9c8 100644 --- a/app/src/main/java/de/danoeh/antennapod/config/DBTasksCallbacksImpl.java +++ b/app/src/main/java/de/danoeh/antennapod/config/DBTasksCallbacksImpl.java @@ -2,7 +2,6 @@ package de.danoeh.antennapod.config; import de.danoeh.antennapod.core.DBTasksCallbacks; import de.danoeh.antennapod.core.preferences.UserPreferences; -import de.danoeh.antennapod.core.storage.APCleanupAlgorithm; import de.danoeh.antennapod.core.storage.APDownloadAlgorithm; import de.danoeh.antennapod.core.storage.AutomaticDownloadAlgorithm; import de.danoeh.antennapod.core.storage.EpisodeCleanupAlgorithm; diff --git a/app/src/main/java/de/danoeh/antennapod/dialog/AuthenticationDialog.java b/app/src/main/java/de/danoeh/antennapod/dialog/AuthenticationDialog.java index bdb2d68ba..6f9e221ec 100644 --- a/app/src/main/java/de/danoeh/antennapod/dialog/AuthenticationDialog.java +++ b/app/src/main/java/de/danoeh/antennapod/dialog/AuthenticationDialog.java @@ -2,13 +2,13 @@ package de.danoeh.antennapod.dialog; import android.app.Dialog; import android.content.Context; -import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; + import de.danoeh.antennapod.R; /** @@ -58,26 +58,13 @@ public abstract class AuthenticationDialog extends Dialog { if (passwordInitialValue != null) { etxtPassword.setText(passwordInitialValue); } - setOnCancelListener(new OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - onCancelled(); - } - }); - butCancel.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - cancel(); - } - }); - butConfirm.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - onConfirmed(etxtUsername.getText().toString(), - etxtPassword.getText().toString(), - showSaveCredentialsCheckbox && saveUsernamePassword.isChecked()); - dismiss(); - } + setOnCancelListener(dialog -> onCancelled()); + butCancel.setOnClickListener(v -> cancel()); + butConfirm.setOnClickListener(v -> { + onConfirmed(etxtUsername.getText().toString(), + etxtPassword.getText().toString(), + showSaveCredentialsCheckbox && saveUsernamePassword.isChecked()); + dismiss(); }); } diff --git a/app/src/main/java/de/danoeh/antennapod/dialog/AutoFlattrPreferenceDialog.java b/app/src/main/java/de/danoeh/antennapod/dialog/AutoFlattrPreferenceDialog.java index 75b1bc8d2..93425949c 100644 --- a/app/src/main/java/de/danoeh/antennapod/dialog/AutoFlattrPreferenceDialog.java +++ b/app/src/main/java/de/danoeh/antennapod/dialog/AutoFlattrPreferenceDialog.java @@ -3,7 +3,6 @@ package de.danoeh.antennapod.dialog; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; -import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.view.View; import android.widget.CheckBox; @@ -42,12 +41,9 @@ public class AutoFlattrPreferenceDialog { setStatusMsgText(activity, txtvStatus, initialValue); skbPercent.setProgress(initialValue); - chkAutoFlattr.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - skbPercent.setEnabled(chkAutoFlattr.isChecked()); - txtvStatus.setEnabled(chkAutoFlattr.isChecked()); - } + chkAutoFlattr.setOnClickListener(v -> { + skbPercent.setEnabled(chkAutoFlattr.isChecked()); + txtvStatus.setEnabled(chkAutoFlattr.isChecked()); }); skbPercent.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @@ -69,20 +65,14 @@ public class AutoFlattrPreferenceDialog { builder.setTitle(R.string.pref_auto_flattr_title) .setView(view) - .setPositiveButton(R.string.confirm_label, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - float progDouble = ((float) skbPercent.getProgress()) / 100.0f; - callback.onConfirmed(chkAutoFlattr.isChecked(), progDouble); - dialog.dismiss(); - } + .setPositiveButton(R.string.confirm_label, (dialog, which) -> { + float progDouble = ((float) skbPercent.getProgress()) / 100.0f; + callback.onConfirmed(chkAutoFlattr.isChecked(), progDouble); + dialog.dismiss(); }) - .setNegativeButton(R.string.cancel_label, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - callback.onCancelled(); - dialog.dismiss(); - } + .setNegativeButton(R.string.cancel_label, (dialog, which) -> { + callback.onCancelled(); + dialog.dismiss(); }) .setCancelable(false).show(); } @@ -97,10 +87,10 @@ public class AutoFlattrPreferenceDialog { } } - public static interface AutoFlattrPreferenceDialogInterface { - public void onCancelled(); + public interface AutoFlattrPreferenceDialogInterface { + void onCancelled(); - public void onConfirmed(boolean autoFlattrEnabled, float autoFlattrValue); + void onConfirmed(boolean autoFlattrEnabled, float autoFlattrValue); } diff --git a/app/src/main/java/de/danoeh/antennapod/dialog/EpisodesApplyActionFragment.java b/app/src/main/java/de/danoeh/antennapod/dialog/EpisodesApplyActionFragment.java index ac7a9efee..577a3ecbe 100644 --- a/app/src/main/java/de/danoeh/antennapod/dialog/EpisodesApplyActionFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/dialog/EpisodesApplyActionFragment.java @@ -54,7 +54,7 @@ public class EpisodesApplyActionFragment extends Fragment { private final Map<Long,FeedItem> idMap = new ArrayMap<>(); private final List<FeedItem> episodes = new ArrayList<>(); private int actions; - private final List<String> titles = new ArrayList(); + private final List<String> titles = new ArrayList<>(); private final LongList checkedIds = new LongList(); private MenuItem mSelectToggle; @@ -285,9 +285,9 @@ public class EpisodesApplyActionFragment extends Fragment { private void sortByDuration(final boolean reverse) { Collections.sort(episodes, (lhs, rhs) -> { int ordering; - if (false == lhs.hasMedia()) { + if (!lhs.hasMedia()) { ordering = 1; - } else if (false == rhs.hasMedia()) { + } else if (!rhs.hasMedia()) { ordering = -1; } else { ordering = lhs.getMedia().getDuration() - rhs.getMedia().getDuration(); @@ -304,7 +304,7 @@ public class EpisodesApplyActionFragment extends Fragment { private void checkAll() { for (FeedItem episode : episodes) { - if(false == checkedIds.contains(episode.getId())) { + if(!checkedIds.contains(episode.getId())) { checkedIds.add(episode.getId()); } } @@ -391,14 +391,14 @@ public class EpisodesApplyActionFragment extends Fragment { private void downloadChecked() { // download the check episodes in the same order as they are currently displayed - List<FeedItem> toDownload = new ArrayList<FeedItem>(checkedIds.size()); + List<FeedItem> toDownload = new ArrayList<>(checkedIds.size()); for(FeedItem episode : episodes) { if(checkedIds.contains(episode.getId())) { toDownload.add(episode); } } try { - DBTasks.downloadFeedItems(getActivity(), toDownload.toArray(new FeedItem[0])); + DBTasks.downloadFeedItems(getActivity(), toDownload.toArray(new FeedItem[toDownload.size()])); } catch (DownloadRequestException e) { e.printStackTrace(); DownloadRequestErrorDialogCreator.newRequestErrorDialog(getActivity(), e.getMessage()); diff --git a/app/src/main/java/de/danoeh/antennapod/dialog/GpodnetSetHostnameDialog.java b/app/src/main/java/de/danoeh/antennapod/dialog/GpodnetSetHostnameDialog.java index 5f531e88f..b50e21d15 100644 --- a/app/src/main/java/de/danoeh/antennapod/dialog/GpodnetSetHostnameDialog.java +++ b/app/src/main/java/de/danoeh/antennapod/dialog/GpodnetSetHostnameDialog.java @@ -1,7 +1,6 @@ package de.danoeh.antennapod.dialog; import android.content.Context; -import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.text.Editable; import android.text.InputType; diff --git a/app/src/main/java/de/danoeh/antennapod/dialog/ProxyDialog.java b/app/src/main/java/de/danoeh/antennapod/dialog/ProxyDialog.java index d745bb51c..98a4b5356 100644 --- a/app/src/main/java/de/danoeh/antennapod/dialog/ProxyDialog.java +++ b/app/src/main/java/de/danoeh/antennapod/dialog/ProxyDialog.java @@ -98,9 +98,7 @@ public class ProxyDialog { AntennapodHttpClient.reinit(); dialog.dismiss(); }) - .onNegative((dialog1, which) -> { - dialog1.dismiss(); - }) + .onNegative((dialog1, which) -> dialog1.dismiss()) .autoDismiss(false) .build(); View view = dialog.getCustomView(); @@ -208,8 +206,7 @@ public class ProxyDialog { String port = etPort.getText().toString(); if(port.length() > 0) { try { - int portValue = Integer.parseInt(port); - return portValue; + return Integer.parseInt(port); } catch(NumberFormatException e) { // ignore } diff --git a/app/src/main/java/de/danoeh/antennapod/dialog/RatingDialog.java b/app/src/main/java/de/danoeh/antennapod/dialog/RatingDialog.java index ed0db92a4..64fc1fda4 100644 --- a/app/src/main/java/de/danoeh/antennapod/dialog/RatingDialog.java +++ b/app/src/main/java/de/danoeh/antennapod/dialog/RatingDialog.java @@ -94,11 +94,7 @@ public class RatingDialog { long firstDate = mPreferences.getLong(KEY_FIRST_START_DATE, now); long diff = now - firstDate; long diffDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); - if (diffDays >= AFTER_DAYS) { - return true; - } else { - return false; - } + return diffDays >= AFTER_DAYS; } @Nullable @@ -107,30 +103,16 @@ public class RatingDialog { if(context == null) { return null; } - MaterialDialog dialog = new MaterialDialog.Builder(context) + return new MaterialDialog.Builder(context) .title(R.string.rating_title) .content(R.string.rating_message) .positiveText(R.string.rating_now_label) .negativeText(R.string.rating_never_label) .neutralText(R.string.rating_later_label) - .callback(new MaterialDialog.ButtonCallback() { - @Override - public void onPositive(MaterialDialog dialog) { - rateNow(); - } - - @Override - public void onNegative(MaterialDialog dialog) { - saveRated(); - } - - @Override - public void onNeutral(MaterialDialog dialog) { - resetStartDate(); - } - }) + .onPositive((dialog, which) -> rateNow()) + .onNegative((dialog, which) -> saveRated()) + .onNeutral((dialog, which) -> resetStartDate()) .cancelListener(dialog1 -> resetStartDate()) .build(); - return dialog; } } diff --git a/app/src/main/java/de/danoeh/antennapod/dialog/SleepTimerDialog.java b/app/src/main/java/de/danoeh/antennapod/dialog/SleepTimerDialog.java index 89e24f882..8a13a75d9 100644 --- a/app/src/main/java/de/danoeh/antennapod/dialog/SleepTimerDialog.java +++ b/app/src/main/java/de/danoeh/antennapod/dialog/SleepTimerDialog.java @@ -1,17 +1,13 @@ package de.danoeh.antennapod.dialog; -import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; -import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; -import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; -import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; @@ -58,14 +54,8 @@ public abstract class SleepTimerDialog { builder.customView(R.layout.time_dialog, false); builder.positiveText(R.string.set_sleeptimer_label); builder.negativeText(R.string.cancel_label); - builder.callback(new MaterialDialog.ButtonCallback() { - @Override - public void onNegative(MaterialDialog dialog) { - dialog.dismiss(); - } - - @Override - public void onPositive(MaterialDialog dialog) { + builder.onNegative((dialog, which) -> dialog.dismiss()); + builder.onPositive((dialog, which) -> { try { savePreferences(); long input = readTimeMillis(); @@ -77,8 +67,7 @@ public abstract class SleepTimerDialog { Toast.LENGTH_LONG); toast.show(); } - } - }); + }); dialog = builder.build(); View view = dialog.getView(); diff --git a/app/src/main/java/de/danoeh/antennapod/dialog/VariableSpeedDialog.java b/app/src/main/java/de/danoeh/antennapod/dialog/VariableSpeedDialog.java index 3ed82b9bd..2bf9c4e7a 100644 --- a/app/src/main/java/de/danoeh/antennapod/dialog/VariableSpeedDialog.java +++ b/app/src/main/java/de/danoeh/antennapod/dialog/VariableSpeedDialog.java @@ -102,8 +102,8 @@ public class VariableSpeedDialog { builder.setPositiveButton(android.R.string.ok, (dialog, which) -> { int choiceCount = 0; - for (int i = 0; i < speedChecked.length; i++) { - if (speedChecked[i]) { + for (boolean checked : speedChecked) { + if (checked) { choiceCount++; } } diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/AddFeedFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/AddFeedFragment.java index d979dc382..45364ca07 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/AddFeedFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/AddFeedFragment.java @@ -47,36 +47,18 @@ public class AddFeedFragment extends Fragment { final MainActivity activity = (MainActivity) getActivity(); activity.getSupportActionBar().setTitle(R.string.add_feed_label); - butSearchITunes.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - activity.loadChildFragment(new ItunesSearchFragment()); - } - }); + butSearchITunes.setOnClickListener(v -> activity.loadChildFragment(new ItunesSearchFragment())); - butBrowserGpoddernet.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - activity.loadChildFragment(new GpodnetMainFragment()); - } - }); + butBrowserGpoddernet.setOnClickListener(v -> activity.loadChildFragment(new GpodnetMainFragment())); - butOpmlImport.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - startActivity(new Intent(getActivity(), - OpmlImportFromPathActivity.class)); - } - }); + butOpmlImport.setOnClickListener(v -> startActivity(new Intent(getActivity(), + OpmlImportFromPathActivity.class))); - butConfirm.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getActivity(), OnlineFeedViewActivity.class); - intent.putExtra(OnlineFeedViewActivity.ARG_FEEDURL, etxtFeedurl.getText().toString()); - intent.putExtra(OnlineFeedViewActivity.ARG_TITLE, getString(R.string.add_feed_label)); - startActivity(intent); - } + butConfirm.setOnClickListener(v -> { + Intent intent = new Intent(getActivity(), OnlineFeedViewActivity.class); + intent.putExtra(OnlineFeedViewActivity.ARG_FEEDURL, etxtFeedurl.getText().toString()); + intent.putExtra(OnlineFeedViewActivity.ARG_TITLE, getString(R.string.add_feed_label)); + startActivity(intent); }); return root; diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/AllEpisodesFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/AllEpisodesFragment.java index aa2879330..335cf5414 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/AllEpisodesFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/AllEpisodesFragment.java @@ -1,6 +1,5 @@ package de.danoeh.antennapod.fragment; -import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; @@ -24,7 +23,6 @@ import android.widget.Toast; import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration; import java.util.List; -import java.util.concurrent.atomic.AtomicReference; import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.MainActivity; @@ -81,8 +79,6 @@ public class AllEpisodesFragment extends Fragment { private boolean itemsLoaded = false; private boolean viewsCreated = false; - private AtomicReference<MainActivity> activity = new AtomicReference<MainActivity>(); - private boolean isUpdatingFeeds; protected Subscription subscription; @@ -101,7 +97,6 @@ public class AllEpisodesFragment extends Fragment { public void onStart() { super.onStart(); EventDistributor.getInstance().register(contentUpdate); - this.activity.set((MainActivity) getActivity()); if (viewsCreated && itemsLoaded) { onFragmentLoaded(); } @@ -133,12 +128,6 @@ public class AllEpisodesFragment extends Fragment { } @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - this.activity.set((MainActivity) getActivity()); - } - - @Override public void onDestroyView() { super.onDestroyView(); resetViewState(); @@ -176,18 +165,13 @@ public class AllEpisodesFragment extends Fragment { } protected void resetViewState() { - listAdapter = null; - activity.set(null); viewsCreated = false; + listAdapter = null; } - private final MenuItemUtils.UpdateRefreshMenuItemChecker updateRefreshMenuItemChecker = new MenuItemUtils.UpdateRefreshMenuItemChecker() { - @Override - public boolean isRefreshing() { - return DownloadService.isRunning && DownloadRequester.getInstance().isDownloadingFeeds(); - } - }; + private final MenuItemUtils.UpdateRefreshMenuItemChecker updateRefreshMenuItemChecker = + () -> DownloadService.isRunning && DownloadRequester.getInstance().isDownloadingFeeds(); @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { @@ -325,7 +309,7 @@ public class AllEpisodesFragment extends Fragment { viewsCreated = true; - if (itemsLoaded && activity.get() != null) { + if (itemsLoaded) { onFragmentLoaded(); } @@ -334,7 +318,7 @@ public class AllEpisodesFragment extends Fragment { private void onFragmentLoaded() { if (listAdapter == null) { - MainActivity mainActivity = activity.get(); + MainActivity mainActivity = (MainActivity) getActivity(); listAdapter = new AllEpisodesRecycleAdapter(mainActivity, itemAccess, new DefaultActionButtonCallback(mainActivity), showOnlyNewEpisodes()); listAdapter.setHasStableIds(true); @@ -379,10 +363,7 @@ public class AllEpisodesFragment extends Fragment { @Override public boolean isInQueue(FeedItem item) { - if (item != null) { - return item.isTagged(FeedItem.TAG_QUEUE); - } - return false; + return item != null && item.isTagged(FeedItem.TAG_QUEUE); } @Override @@ -471,7 +452,7 @@ public class AllEpisodesFragment extends Fragment { recyclerView.setVisibility(View.GONE); progLoading.setVisibility(View.VISIBLE); } - subscription = Observable.fromCallable(() -> loadData()) + subscription = Observable.fromCallable(this::loadData) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(data -> { @@ -480,7 +461,7 @@ public class AllEpisodesFragment extends Fragment { if (data != null) { episodes = data; itemsLoaded = true; - if (viewsCreated && activity.get() != null) { + if (viewsCreated) { onFragmentLoaded(); } } diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/CompletedDownloadsFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/CompletedDownloadsFragment.java index a53c85f1c..261974f2f 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/CompletedDownloadsFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/CompletedDownloadsFragment.java @@ -205,7 +205,7 @@ public class CompletedDownloadsFragment extends ListFragment { if (items == null && viewCreated) { setListShown(false); } - subscription = Observable.fromCallable(() -> DBReader.getDownloadedItems()) + subscription = Observable.fromCallable(DBReader::getDownloadedItems) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/DownloadLogFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/DownloadLogFragment.java index b470d379a..93527b149 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/DownloadLogFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/DownloadLogFragment.java @@ -154,7 +154,7 @@ public class DownloadLogFragment extends ListFragment { if(subscription != null) { subscription.unsubscribe(); } - subscription = Observable.fromCallable(() -> DBReader.getDownloadLog()) + subscription = Observable.fromCallable(DBReader::getDownloadLog) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/ExternalPlayerFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/ExternalPlayerFragment.java index 3fd69214d..ca60e7bf2 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/ExternalPlayerFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/ExternalPlayerFragment.java @@ -5,7 +5,6 @@ import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; -import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; @@ -53,16 +52,12 @@ public class ExternalPlayerFragment extends Fragment { mFeedName = (TextView) root.findViewById(R.id.txtvAuthor); mProgressBar = (ProgressBar) root.findViewById(R.id.episodeProgress); - fragmentLayout.setOnClickListener(new OnClickListener() { + fragmentLayout.setOnClickListener(v -> { + Log.d(TAG, "layoutInfo was clicked"); - @Override - public void onClick(View v) { - Log.d(TAG, "layoutInfo was clicked"); - - if (controller != null && controller.getMedia() != null) { - startActivity(PlaybackService.getPlayerActivityIntent( - getActivity(), controller.getMedia())); - } + if (controller != null && controller.getMedia() != null) { + startActivity(PlaybackService.getPlayerActivityIntent( + getActivity(), controller.getMedia())); } }); return root; diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/ItemDescriptionFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/ItemDescriptionFragment.java index 4a93bac7e..5b301333e 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/ItemDescriptionFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/ItemDescriptionFragment.java @@ -148,7 +148,7 @@ public class ItemDescriptionFragment extends Fragment implements AudioplayerCont super.onPageFinished(view, url); Log.d(TAG, "Page finished"); // Restoring the scroll position might not always work - view.postDelayed(() -> restoreFromPreference(), 50); + view.postDelayed(ItemDescriptionFragment.this::restoreFromPreference, 50); } }); @@ -318,8 +318,7 @@ public class ItemDescriptionFragment extends Fragment implements AudioplayerCont private String loadData() { Timeline timeline = new Timeline(getActivity(), shownotesProvider); - String data = timeline.processShownotes(highlightTimecodes); - return data; + return timeline.processShownotes(highlightTimecodes); } @Override diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/ItemFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/ItemFragment.java index 0f5aa06ca..92f4a9f7c 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/ItemFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/ItemFragment.java @@ -507,7 +507,7 @@ public class ItemFragment extends Fragment { if(subscription != null) { subscription.unsubscribe(); } - subscription = Observable.fromCallable(() -> loadInBackground()) + subscription = Observable.fromCallable(this::loadInBackground) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/ItemlistFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/ItemlistFragment.java index 303d273bc..4faa7be2d 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/ItemlistFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/ItemlistFragment.java @@ -185,11 +185,7 @@ public class ItemlistFragment extends ListFragment { private final MenuItemUtils.UpdateRefreshMenuItemChecker updateRefreshMenuItemChecker = new MenuItemUtils.UpdateRefreshMenuItemChecker() { @Override public boolean isRefreshing() { - if (feed != null && DownloadService.isRunning && DownloadRequester.getInstance().isDownloadingFile(feed)) { - return true; - } else { - return false; - } + return feed != null && DownloadService.isRunning && DownloadRequester.getInstance().isDownloadingFile(feed); } }; @@ -405,7 +401,6 @@ public class ItemlistFragment extends ListFragment { public void onEventMainThread(FeedItemEvent event) { Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]"); - boolean queueChanged = false; if(feed == null || feed.getItems() == null || adapter == null) { return; } @@ -628,7 +623,7 @@ public class ItemlistFragment extends ListFragment { if(subscription != null) { subscription.unsubscribe(); } - subscription = Observable.fromCallable(() -> loadData()) + subscription = Observable.fromCallable(this::loadData) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/PlaybackHistoryFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/PlaybackHistoryFragment.java index c5b77fae2..f6cb71af5 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/PlaybackHistoryFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/PlaybackHistoryFragment.java @@ -220,7 +220,7 @@ public class PlaybackHistoryFragment extends ListFragment { private FeedItemlistAdapter.ItemAccess itemAccess = new FeedItemlistAdapter.ItemAccess() { @Override public boolean isInQueue(FeedItem item) { - return (queue != null) ? queue.contains(item.getId()) : false; + return (queue != null) && queue.contains(item.getId()); } @Override @@ -255,7 +255,7 @@ public class PlaybackHistoryFragment extends ListFragment { if(subscription != null) { subscription.unsubscribe(); } - subscription = Observable.fromCallable(() -> loadData()) + subscription = Observable.fromCallable(this::loadData) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/QueueFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/QueueFragment.java index e5bb1d895..4bfc3c9da 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/QueueFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/QueueFragment.java @@ -230,9 +230,8 @@ public class QueueFragment extends Fragment { resetViewState(); } - private final MenuItemUtils.UpdateRefreshMenuItemChecker updateRefreshMenuItemChecker = () -> { - return DownloadService.isRunning && DownloadRequester.getInstance().isDownloadingFeeds(); - }; + private final MenuItemUtils.UpdateRefreshMenuItemChecker updateRefreshMenuItemChecker = + () -> DownloadService.isRunning && DownloadRequester.getInstance().isDownloadingFeeds(); @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { @@ -415,7 +414,7 @@ public class QueueFragment extends Fragment { Snackbar snackbar = Snackbar.make(root, getString(R.string.marked_as_read_label), Snackbar.LENGTH_LONG); snackbar.setAction(getString(R.string.undo), v -> { DBWriter.addQueueItemAt(getActivity(), item.getId(), position, false); - if(false == isRead) { + if(!isRead) { DBWriter.markItemPlayed(FeedItem.UNPLAYED, item.getId()); } }); @@ -424,12 +423,12 @@ public class QueueFragment extends Fragment { @Override public boolean isLongPressDragEnabled() { - return false == UserPreferences.isQueueLocked(); + return !UserPreferences.isQueueLocked(); } @Override public boolean isItemViewSwipeEnabled() { - return false == UserPreferences.isQueueLocked(); + return !UserPreferences.isQueueLocked(); } @Override @@ -608,7 +607,7 @@ public class QueueFragment extends Fragment { txtvEmpty.setVisibility(View.GONE); progLoading.setVisibility(View.VISIBLE); } - subscription = Observable.fromCallable(() -> DBReader.getQueue()) + subscription = Observable.fromCallable(DBReader::getQueue) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(items -> { diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/SearchFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/SearchFragment.java index dbd18163c..510909379 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/SearchFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/SearchFragment.java @@ -208,7 +208,7 @@ public class SearchFragment extends ListFragment { if (viewCreated && !itemsLoaded) { setListShown(false); } - subscription = Observable.fromCallable(() -> performSearch()) + subscription = Observable.fromCallable(this::performSearch) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/PodcastListFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/PodcastListFragment.java index 204f36956..15e9c9943 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/PodcastListFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/PodcastListFragment.java @@ -14,7 +14,6 @@ import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; -import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ProgressBar; @@ -84,18 +83,9 @@ public abstract class PodcastListFragment extends Fragment { txtvError = (TextView) root.findViewById(R.id.txtvError); butRetry = (Button) root.findViewById(R.id.butRetry); - gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView<?> parent, View view, int position, long id) { - onPodcastSelected((GpodnetPodcast) gridView.getAdapter().getItem(position)); - } - }); - butRetry.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - loadData(); - } - }); + gridView.setOnItemClickListener((parent, view, position, id) -> + onPodcastSelected((GpodnetPodcast) gridView.getAdapter().getItem(position))); + butRetry.setOnClickListener(v -> loadData()); loadData(); return root; diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/SuggestionListFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/SuggestionListFragment.java index 133bb0281..1b1b61efb 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/SuggestionListFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/SuggestionListFragment.java @@ -1,13 +1,13 @@ package de.danoeh.antennapod.fragment.gpodnet; +import java.util.Collections; +import java.util.List; + import de.danoeh.antennapod.core.gpoddernet.GpodnetService; import de.danoeh.antennapod.core.gpoddernet.GpodnetServiceException; import de.danoeh.antennapod.core.gpoddernet.model.GpodnetPodcast; import de.danoeh.antennapod.core.preferences.GpodnetPreferences; -import java.util.ArrayList; -import java.util.List; - /** * Displays suggestions from gpodder.net */ @@ -20,7 +20,7 @@ public class SuggestionListFragment extends PodcastListFragment { service.authenticate(GpodnetPreferences.getUsername(), GpodnetPreferences.getPassword()); return service.getSuggestions(SUGGESTIONS_COUNT); } else { - return new ArrayList<GpodnetPodcast>(); + return Collections.emptyList(); } } } diff --git a/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/TagListFragment.java b/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/TagListFragment.java index 338f02e61..d2c7f32dd 100644 --- a/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/TagListFragment.java +++ b/app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/TagListFragment.java @@ -11,7 +11,6 @@ import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; -import android.widget.AdapterView; import android.widget.TextView; import java.util.List; @@ -65,13 +64,10 @@ public class TagListFragment extends ListFragment { public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView<?> parent, View view, int position, long id) { - GpodnetTag tag = (GpodnetTag) getListAdapter().getItem(position); - MainActivity activity = (MainActivity) getActivity(); - activity.loadChildFragment(TagFragment.newInstance(tag)); - } + getListView().setOnItemClickListener((parent, view1, position, id) -> { + GpodnetTag tag = (GpodnetTag) getListAdapter().getItem(position); + MainActivity activity = (MainActivity) getActivity(); + activity.loadChildFragment(TagFragment.newInstance(tag)); }); startLoadTask(); diff --git a/app/src/main/java/de/danoeh/antennapod/menuhandler/FeedItemMenuHandler.java b/app/src/main/java/de/danoeh/antennapod/menuhandler/FeedItemMenuHandler.java index 58fe8afbf..c1f94acc5 100644 --- a/app/src/main/java/de/danoeh/antennapod/menuhandler/FeedItemMenuHandler.java +++ b/app/src/main/java/de/danoeh/antennapod/menuhandler/FeedItemMenuHandler.java @@ -41,7 +41,7 @@ public class FeedItemMenuHandler { * menu-object and call setVisibility(visibility) on the returned * MenuItem object. */ - abstract void setItemVisibility(int id, boolean visible); + void setItemVisibility(int id, boolean visible); } /** @@ -98,7 +98,7 @@ public class FeedItemMenuHandler { mi.setItemVisibility(R.id.share_download_url_item, false); mi.setItemVisibility(R.id.share_download_url_with_position_item, false); } - if(false == hasMedia || selectedItem.getMedia().getPosition() <= 0) { + if(!hasMedia || selectedItem.getMedia().getPosition() <= 0) { mi.setItemVisibility(R.id.share_link_with_position_item, false); mi.setItemVisibility(R.id.share_download_url_with_position_item, false); } @@ -113,7 +113,7 @@ public class FeedItemMenuHandler { mi.setItemVisibility(R.id.reset_position, false); } - if(false == UserPreferences.isEnableAutodownload()) { + if(!UserPreferences.isEnableAutodownload()) { mi.setItemVisibility(R.id.activate_auto_download, false); mi.setItemVisibility(R.id.deactivate_auto_download, false); } else if(selectedItem.getAutoDownload()) { @@ -224,7 +224,7 @@ public class FeedItemMenuHandler { context.startActivity(intent); } else { Toast.makeText(context, context.getString(R.string.download_error_malformed_url), - Toast.LENGTH_SHORT); + Toast.LENGTH_SHORT).show(); } break; case R.id.support_item: diff --git a/app/src/main/java/de/danoeh/antennapod/menuhandler/FeedMenuHandler.java b/app/src/main/java/de/danoeh/antennapod/menuhandler/FeedMenuHandler.java index 38030f4ea..ab7d0e7c6 100644 --- a/app/src/main/java/de/danoeh/antennapod/menuhandler/FeedMenuHandler.java +++ b/app/src/main/java/de/danoeh/antennapod/menuhandler/FeedMenuHandler.java @@ -92,7 +92,7 @@ public class FeedMenuHandler { context.startActivity(intent); } else { Toast.makeText(context, context.getString(R.string.download_error_malformed_url), - Toast.LENGTH_SHORT); + Toast.LENGTH_SHORT).show(); } break; case R.id.support_item: diff --git a/app/src/main/java/de/danoeh/antennapod/menuhandler/MenuItemUtils.java b/app/src/main/java/de/danoeh/antennapod/menuhandler/MenuItemUtils.java index 0d2ff8a75..4c28b197d 100644 --- a/app/src/main/java/de/danoeh/antennapod/menuhandler/MenuItemUtils.java +++ b/app/src/main/java/de/danoeh/antennapod/menuhandler/MenuItemUtils.java @@ -39,6 +39,7 @@ public class MenuItemUtils extends de.danoeh.antennapod.core.menuhandler.MenuIte queueLock.setTitle(de.danoeh.antennapod.R.string.lock_queue); queueLock.setIcon(ta.getDrawable(1)); } + ta.recycle(); } } diff --git a/app/src/main/java/de/danoeh/antennapod/menuhandler/NavDrawerActivity.java b/app/src/main/java/de/danoeh/antennapod/menuhandler/NavDrawerActivity.java index 6ceaaada4..c973990c9 100644 --- a/app/src/main/java/de/danoeh/antennapod/menuhandler/NavDrawerActivity.java +++ b/app/src/main/java/de/danoeh/antennapod/menuhandler/NavDrawerActivity.java @@ -5,5 +5,5 @@ package de.danoeh.antennapod.menuhandler; */ public interface NavDrawerActivity { - public boolean isDrawerOpen(); + boolean isDrawerOpen(); } diff --git a/app/src/main/java/de/danoeh/antennapod/preferences/PreferenceController.java b/app/src/main/java/de/danoeh/antennapod/preferences/PreferenceController.java index d8d263313..9dad49145 100644 --- a/app/src/main/java/de/danoeh/antennapod/preferences/PreferenceController.java +++ b/app/src/main/java/de/danoeh/antennapod/preferences/PreferenceController.java @@ -184,20 +184,17 @@ public class PreferenceController implements SharedPreferences.OnSharedPreferenc ); ui.findPreference(PreferenceController.PREF_CHOOSE_DATA_DIR) .setOnPreferenceClickListener( - new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - if (Build.VERSION.SDK_INT >= 19) { - showChooseDataFolderDialog(); - } else { - Intent intent = new Intent(activity, DirectoryChooserActivity.class); - activity.startActivityForResult(intent, - DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED); - } - return true; + preference -> { + if (Build.VERSION.SDK_INT >= 19) { + showChooseDataFolderDialog(); + } else { + Intent intent = new Intent(activity, DirectoryChooserActivity.class); + activity.startActivityForResult(intent, + DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED); } - } - ); + return true; + } + ); ui.findPreference(UserPreferences.PREF_THEME) .setOnPreferenceChangeListener( (preference, newValue) -> { @@ -630,7 +627,7 @@ public class PreferenceController implements SharedPreferences.OnSharedPreferenc Preference.OnPreferenceClickListener clickListener = preference -> { if (preference instanceof CheckBoxPreference) { String key = preference.getKey(); - ArrayList<String> prefValuesList = new ArrayList<String>( + List<String> prefValuesList = new ArrayList<>( Arrays.asList(UserPreferences .getAutodownloadSelectedNetworks()) ); @@ -639,10 +636,10 @@ public class PreferenceController implements SharedPreferences.OnSharedPreferenc Log.d(TAG, "Selected network " + key + ". New state: " + newValue); int index = prefValuesList.indexOf(key); - if (index >= 0 && newValue == false) { + if (index >= 0 && !newValue) { // remove network prefValuesList.remove(index); - } else if (index < 0 && newValue == true) { + } else if (index < 0 && newValue) { prefValuesList.add(key); } @@ -678,9 +675,9 @@ public class PreferenceController implements SharedPreferences.OnSharedPreferenc if (selectedNetworks != null) { PreferenceScreen prefScreen = (PreferenceScreen) ui.findPreference(PreferenceController.AUTO_DL_PREF_SCREEN); - for (int i = 0; i < selectedNetworks.length; i++) { - if (selectedNetworks[i] != null) { - prefScreen.removePreference(selectedNetworks[i]); + for (CheckBoxPreference network : selectedNetworks) { + if (network != null) { + prefScreen.removePreference(network); } } } diff --git a/app/src/main/java/de/danoeh/antennapod/receiver/PlayerWidget.java b/app/src/main/java/de/danoeh/antennapod/receiver/PlayerWidget.java index cf9866097..f0d4014ed 100644 --- a/app/src/main/java/de/danoeh/antennapod/receiver/PlayerWidget.java +++ b/app/src/main/java/de/danoeh/antennapod/receiver/PlayerWidget.java @@ -53,7 +53,7 @@ public class PlayerWidget extends AppWidgetProvider { @Override public void onDisabled(Context context) { super.onDisabled(context); - Log.d(TAG, "Widet disabled"); + Log.d(TAG, "Widget disabled"); setEnabled(context, false); stopUpdate(context); } diff --git a/app/src/main/res/layout/external_player_fragment.xml b/app/src/main/res/layout/external_player_fragment.xml index ac55b4c40..e6fd21241 100644 --- a/app/src/main/res/layout/external_player_fragment.xml +++ b/app/src/main/res/layout/external_player_fragment.xml @@ -79,10 +79,10 @@ android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_below="@id/episodeProgress" - android:layout_centerVertical="true" - android:contentDescription="@string/pause_label" - android:background="?attr/selectableItemBackground" - tools:src="@drawable/ic_play_arrow_white_36dp"/> + android:layout_centerVertical="true" + android:contentDescription="@string/pause_label" + android:background="?attr/selectableItemBackground" + tools:src="@drawable/ic_play_arrow_white_36dp"/> </RelativeLayout> diff --git a/app/src/main/res/layout/videoplayer_activity.xml b/app/src/main/res/layout/videoplayer_activity.xml index 2e1097fb8..4db663e19 100644 --- a/app/src/main/res/layout/videoplayer_activity.xml +++ b/app/src/main/res/layout/videoplayer_activity.xml @@ -32,7 +32,7 @@ android:layout_height="wrap_content" android:layout_margin="8dp" android:background="@drawable/overlay_button_circle_background" - android:contentDescription="@string/pause_label" + android:contentDescription="@string/rewind_label" android:src="@drawable/ic_av_rewind_80dp" /> <ImageButton @@ -50,7 +50,7 @@ android:layout_height="wrap_content" android:layout_margin="8dp" android:background="@drawable/overlay_button_circle_background" - android:contentDescription="@string/pause_label" + android:contentDescription="@string/fast_forward_label" android:src="@drawable/ic_av_fast_forward_80dp" /> </LinearLayout> diff --git a/core/src/main/java/de/danoeh/antennapod/core/ApplicationCallbacks.java b/core/src/main/java/de/danoeh/antennapod/core/ApplicationCallbacks.java index 1064e98ac..3acc84e3b 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/ApplicationCallbacks.java +++ b/core/src/main/java/de/danoeh/antennapod/core/ApplicationCallbacks.java @@ -12,12 +12,12 @@ public interface ApplicationCallbacks { /** * Returns a non-null instance of the application class */ - public Application getApplicationInstance(); + Application getApplicationInstance(); /** * Returns a non-null intent that starts the storage error * activity. */ - public Intent getStorageErrorActivity(Context context); + Intent getStorageErrorActivity(Context context); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/DBTasksCallbacks.java b/core/src/main/java/de/danoeh/antennapod/core/DBTasksCallbacks.java index edf3e3199..11a6b2c9f 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/DBTasksCallbacks.java +++ b/core/src/main/java/de/danoeh/antennapod/core/DBTasksCallbacks.java @@ -11,10 +11,10 @@ public interface DBTasksCallbacks { /** * Returns the client's implementation of the AutomaticDownloadAlgorithm interface. */ - public AutomaticDownloadAlgorithm getAutomaticDownloadAlgorithm(); + AutomaticDownloadAlgorithm getAutomaticDownloadAlgorithm(); /** * Returns the client's implementation of the EpisodeCacheCleanupAlgorithm interface. */ - public EpisodeCleanupAlgorithm getEpisodeCacheCleanupAlgorithm(); + EpisodeCleanupAlgorithm getEpisodeCacheCleanupAlgorithm(); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/DownloadServiceCallbacks.java b/core/src/main/java/de/danoeh/antennapod/core/DownloadServiceCallbacks.java index 286e830c5..e56445489 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/DownloadServiceCallbacks.java +++ b/core/src/main/java/de/danoeh/antennapod/core/DownloadServiceCallbacks.java @@ -19,7 +19,7 @@ public interface DownloadServiceCallbacks { * * @return A non-null PendingIntent for the notification. */ - public PendingIntent getNotificationContentIntent(Context context); + PendingIntent getNotificationContentIntent(Context context); /** * Returns a PendingIntent for a notification that tells the user to enter a username @@ -30,7 +30,7 @@ public interface DownloadServiceCallbacks { * * @return A non-null PendingIntent for the notification. */ - public PendingIntent getAuthentificationNotificationContentIntent(Context context, DownloadRequest request); + PendingIntent getAuthentificationNotificationContentIntent(Context context, DownloadRequest request); /** * Returns a PendingIntent for notification that notifies the user about the completion of downloads @@ -40,19 +40,19 @@ public interface DownloadServiceCallbacks { * * @return A non-null PendingIntent for the notification or null if shouldCreateReport()==false */ - public PendingIntent getReportNotificationContentIntent(Context context); + PendingIntent getReportNotificationContentIntent(Context context); /** * Called by the FeedSyncThread after a feed has been downloaded and parsed. * * @param feed The non-null feed that has been parsed. */ - public void onFeedParsed(Context context, Feed feed); + void onFeedParsed(Context context, Feed feed); /** * Returns true if the DownloadService should create a report that shows the number of failed * downloads when the service shuts down. * */ - public boolean shouldCreateReport(); + boolean shouldCreateReport(); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/FlattrCallbacks.java b/core/src/main/java/de/danoeh/antennapod/core/FlattrCallbacks.java index cee1029d8..5fa6faa13 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/FlattrCallbacks.java +++ b/core/src/main/java/de/danoeh/antennapod/core/FlattrCallbacks.java @@ -15,7 +15,7 @@ public interface FlattrCallbacks { * Returns if true if the flattr integration should be activated, * false otherwise. */ - public boolean flattrEnabled(); + boolean flattrEnabled(); /** * Returns an intent that starts the activity that is responsible for @@ -24,13 +24,13 @@ public interface FlattrCallbacks { * @return The intent that starts the authentication activity or null * if flattr integration is disabled (i.e. flattrEnabled() == false). */ - public Intent getFlattrAuthenticationActivityIntent(Context context); + Intent getFlattrAuthenticationActivityIntent(Context context); - public PendingIntent getFlattrFailedNotificationContentIntent(Context context); + PendingIntent getFlattrFailedNotificationContentIntent(Context context); - public String getFlattrAppKey(); + String getFlattrAppKey(); - public String getFlattrAppSecret(); + String getFlattrAppSecret(); - public void handleFlattrAuthenticationSuccess(AccessToken token); + void handleFlattrAuthenticationSuccess(AccessToken token); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/GpodnetCallbacks.java b/core/src/main/java/de/danoeh/antennapod/core/GpodnetCallbacks.java index 6174bce29..10797ecfb 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/GpodnetCallbacks.java +++ b/core/src/main/java/de/danoeh/antennapod/core/GpodnetCallbacks.java @@ -13,7 +13,7 @@ public interface GpodnetCallbacks { * Returns if true if the gpodder.net integration should be activated, * false otherwise. */ - public boolean gpodnetEnabled(); + boolean gpodnetEnabled(); /** * Returns a PendingIntent for the error notification of the GpodnetSyncService. @@ -23,5 +23,5 @@ public interface GpodnetCallbacks { * @return A PendingIntent for the notification or null if gpodder.net integration * has been disabled (i.e. gpodnetEnabled() == false). */ - public PendingIntent getGpodnetSyncServiceErrorNotificationPendingIntent(Context context); + PendingIntent getGpodnetSyncServiceErrorNotificationPendingIntent(Context context); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/PlaybackServiceCallbacks.java b/core/src/main/java/de/danoeh/antennapod/core/PlaybackServiceCallbacks.java index fb01fa703..08ccb6d71 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/PlaybackServiceCallbacks.java +++ b/core/src/main/java/de/danoeh/antennapod/core/PlaybackServiceCallbacks.java @@ -17,17 +17,17 @@ public interface PlaybackServiceCallbacks { * @param mediaType The type of media that is being played. * @return A non-null activity intent. */ - public Intent getPlayerActivityIntent(Context context, MediaType mediaType); + Intent getPlayerActivityIntent(Context context, MediaType mediaType); /** * Returns true if the PlaybackService should load new episodes from the queue when playback ends * and false if the PlaybackService should ignore the queue and load no more episodes when playback * finishes. */ - public boolean useQueue(); + boolean useQueue(); /** * Returns a drawable resource that is used for the notification of the playback service. */ - public int getNotificationIconResource(Context context); + int getNotificationIconResource(Context context); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/asynctask/FeedRemover.java b/core/src/main/java/de/danoeh/antennapod/core/asynctask/FeedRemover.java index 7ff622f34..e475e696c 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/asynctask/FeedRemover.java +++ b/core/src/main/java/de/danoeh/antennapod/core/asynctask/FeedRemover.java @@ -30,9 +30,7 @@ public class FeedRemover extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... params) { try { DBWriter.deleteFeed(context, feed.getId()).get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return null; diff --git a/core/src/main/java/de/danoeh/antennapod/core/asynctask/FlattrClickWorker.java b/core/src/main/java/de/danoeh/antennapod/core/asynctask/FlattrClickWorker.java index c0ec8d08a..3ddaba52e 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/asynctask/FlattrClickWorker.java +++ b/core/src/main/java/de/danoeh/antennapod/core/asynctask/FlattrClickWorker.java @@ -45,7 +45,7 @@ public class FlattrClickWorker extends AsyncTask<Void, Integer, FlattrClickWorke private final Context context; - public static enum ExitCode {EXIT_NORMAL, NO_TOKEN, NO_NETWORK, NO_THINGS} + public enum ExitCode {EXIT_NORMAL, NO_TOKEN, NO_NETWORK, NO_THINGS} private final AtomicInteger countFailed = new AtomicInteger(); private final AtomicInteger countSuccess = new AtomicInteger(); @@ -106,7 +106,7 @@ public class FlattrClickWorker extends AsyncTask<Void, Integer, FlattrClickWorke return ExitCode.NO_THINGS; } - List<Future> dbFutures = new LinkedList<Future>(); + List<Future> dbFutures = new LinkedList<>(); for (FlattrThing thing : flattrQueue) { if (BuildConfig.DEBUG) Log.d(TAG, "Processing " + thing.getTitle()); @@ -134,9 +134,7 @@ public class FlattrClickWorker extends AsyncTask<Void, Integer, FlattrClickWorke for (Future f : dbFutures) { try { f.get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } diff --git a/core/src/main/java/de/danoeh/antennapod/core/asynctask/FlattrStatusFetcher.java b/core/src/main/java/de/danoeh/antennapod/core/asynctask/FlattrStatusFetcher.java index 888591e89..4c084eaaf 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/asynctask/FlattrStatusFetcher.java +++ b/core/src/main/java/de/danoeh/antennapod/core/asynctask/FlattrStatusFetcher.java @@ -2,15 +2,17 @@ package de.danoeh.antennapod.core.asynctask; import android.content.Context; import android.util.Log; -import de.danoeh.antennapod.core.BuildConfig; -import de.danoeh.antennapod.core.storage.DBWriter; -import de.danoeh.antennapod.core.util.flattr.FlattrUtils; + import org.shredzone.flattr4j.exception.FlattrException; import org.shredzone.flattr4j.model.Flattr; import java.util.List; import java.util.concurrent.ExecutionException; +import de.danoeh.antennapod.core.BuildConfig; +import de.danoeh.antennapod.core.storage.DBWriter; +import de.danoeh.antennapod.core.util.flattr.FlattrUtils; + /** * Fetch list of flattred things and flattr status in database in a background thread. */ @@ -36,9 +38,7 @@ public class FlattrStatusFetcher extends Thread { } catch (FlattrException e) { e.printStackTrace(); Log.d(TAG, "flattrQueue exception retrieving list with flattred items " + e.getMessage()); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/asynctask/ImageResource.java b/core/src/main/java/de/danoeh/antennapod/core/asynctask/ImageResource.java index edd69f15b..992321441 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/asynctask/ImageResource.java +++ b/core/src/main/java/de/danoeh/antennapod/core/asynctask/ImageResource.java @@ -16,13 +16,13 @@ public interface ImageResource { * <p/> * For example implementations, see FeedMedia or ExternalMedia. */ - public static final String SCHEME_MEDIA = "media"; + String SCHEME_MEDIA = "media"; /** * Parameter key for an encoded fallback Uri. This Uri MUST point to a local image file */ - public static final String PARAM_FALLBACK = "fallback"; + String PARAM_FALLBACK = "fallback"; /** * Returns a Uri to the image or null if no image is available. @@ -33,5 +33,5 @@ public interface ImageResource { * The Uri can also have an optional fallback-URL if loading the default URL * failed (see PARAM_FALLBACK). */ - public Uri getImageUri(); + Uri getImageUri(); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/backup/OpmlBackupAgent.java b/core/src/main/java/de/danoeh/antennapod/core/backup/OpmlBackupAgent.java index 690fbdfc6..982015314 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/backup/OpmlBackupAgent.java +++ b/core/src/main/java/de/danoeh/antennapod/core/backup/OpmlBackupAgent.java @@ -8,7 +8,6 @@ import android.content.Context; import android.os.ParcelFileDescriptor; import android.util.Log; -import de.danoeh.antennapod.core.BuildConfig; import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayOutputStream; @@ -26,8 +25,8 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Date; +import de.danoeh.antennapod.core.BuildConfig; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.opml.OpmlElement; import de.danoeh.antennapod.core.opml.OpmlReader; @@ -45,13 +44,13 @@ public class OpmlBackupAgent extends BackupAgentHelper { addHelper(OPML_BACKUP_KEY, new OpmlBackupHelper(this)); } - private static final void LOGD(String tag, String msg) { + private static void LOGD(String tag, String msg) { if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, msg); } } - private static final void LOGD(String tag, String msg, Throwable tr) { + private static void LOGD(String tag, String msg, Throwable tr) { if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, msg, tr); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/dialog/ConfirmationDialog.java b/core/src/main/java/de/danoeh/antennapod/core/dialog/ConfirmationDialog.java index abb75e5e7..266526d82 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/dialog/ConfirmationDialog.java +++ b/core/src/main/java/de/danoeh/antennapod/core/dialog/ConfirmationDialog.java @@ -49,28 +49,10 @@ public abstract class ConfirmationDialog { builder.setTitle(titleId); builder.setMessage(messageId); builder.setPositiveButton(positiveText != 0 ? positiveText : R.string.confirm_label, - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - onConfirmButtonPressed(dialog); - } - }); + (dialog, which) -> onConfirmButtonPressed(dialog)); builder.setNegativeButton(negativeText != 0 ? negativeText : R.string.cancel_label, - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - onCancelButtonPressed(dialog); - } - }); - builder.setOnCancelListener(new DialogInterface.OnCancelListener() { - - @Override - public void onCancel(DialogInterface dialog) { - onCancelButtonPressed(dialog); - } - }); + (dialog, which) -> onCancelButtonPressed(dialog)); + builder.setOnCancelListener(ConfirmationDialog.this::onCancelButtonPressed); return builder.create(); } } diff --git a/core/src/main/java/de/danoeh/antennapod/core/dialog/DownloadRequestErrorDialogCreator.java b/core/src/main/java/de/danoeh/antennapod/core/dialog/DownloadRequestErrorDialogCreator.java index b7e79431d..b1beac315 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/dialog/DownloadRequestErrorDialogCreator.java +++ b/core/src/main/java/de/danoeh/antennapod/core/dialog/DownloadRequestErrorDialogCreator.java @@ -1,7 +1,6 @@ package de.danoeh.antennapod.core.dialog; import android.content.Context; -import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import de.danoeh.antennapod.core.R; @@ -15,13 +14,7 @@ public class DownloadRequestErrorDialogCreator { String errorMessage) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setNeutralButton(android.R.string.ok, - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }) + (dialog, which) -> dialog.dismiss()) .setTitle(R.string.download_error_request_error) .setMessage( context.getString(R.string.download_request_error_dialog_message_prefix) diff --git a/core/src/main/java/de/danoeh/antennapod/core/feed/EventDistributor.java b/core/src/main/java/de/danoeh/antennapod/core/feed/EventDistributor.java index 7ccb742fb..dbad084c7 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/feed/EventDistributor.java +++ b/core/src/main/java/de/danoeh/antennapod/core/feed/EventDistributor.java @@ -34,7 +34,7 @@ public class EventDistributor extends Observable { private EventDistributor() { this.handler = new Handler(); - events = new ConcurrentLinkedQueue<Integer>(); + events = new ConcurrentLinkedQueue<>(); } public static synchronized EventDistributor getInstance() { @@ -54,13 +54,7 @@ public class EventDistributor extends Observable { public void addEvent(Integer i) { events.offer(i); - handler.post(new Runnable() { - - @Override - public void run() { - processEventQueue(); - } - }); + handler.post(EventDistributor.this::processEventQueue); } private void processEventQueue() { diff --git a/core/src/main/java/de/danoeh/antennapod/core/feed/Feed.java b/core/src/main/java/de/danoeh/antennapod/core/feed/Feed.java index dfcc71658..67ac2d280 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/feed/Feed.java +++ b/core/src/main/java/de/danoeh/antennapod/core/feed/Feed.java @@ -112,7 +112,7 @@ public class Feed extends FeedFile implements FlattrThing, ImageResource { this.flattrStatus = status; this.paged = paged; this.nextPageLink = nextPageLink; - this.items = new ArrayList<FeedItem>(); + this.items = new ArrayList<>(); if(filter != null) { this.itemfilter = new FeedItemFilter(filter); } else { @@ -235,7 +235,7 @@ public class Feed extends FeedFile implements FlattrThing, ImageResource { */ public boolean hasUnplayedItems() { for (FeedItem item : items) { - if (false == item.isNew() && false == item.isPlayed()) { + if (!item.isNew() && !item.isPlayed()) { return true; } } diff --git a/core/src/main/java/de/danoeh/antennapod/core/feed/FeedComponent.java b/core/src/main/java/de/danoeh/antennapod/core/feed/FeedComponent.java index 05115c1ea..90b5e50b7 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/feed/FeedComponent.java +++ b/core/src/main/java/de/danoeh/antennapod/core/feed/FeedComponent.java @@ -54,9 +54,8 @@ public abstract class FeedComponent { FeedComponent that = (FeedComponent) o; - if (id != that.id) return false; + return id == that.id; - return true; } @Override diff --git a/core/src/main/java/de/danoeh/antennapod/core/feed/FeedItem.java b/core/src/main/java/de/danoeh/antennapod/core/feed/FeedItem.java index d8c32f55e..b2192c66f 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/feed/FeedItem.java +++ b/core/src/main/java/de/danoeh/antennapod/core/feed/FeedItem.java @@ -171,9 +171,8 @@ public class FeedItem extends FeedComponent implements ShownotesProvider, Flattr String itemIdentifier = cursor.getString(indexItemIdentifier); long autoDownload = cursor.getLong(indexAutoDownload); - FeedItem item = new FeedItem(id, title, link, pubDate, paymentLink, feedId, flattrStatus, + return new FeedItem(id, title, link, pubDate, paymentLink, feedId, flattrStatus, hasChapters, null, state, itemIdentifier, autoDownload); - return item; } public void updateFromOther(FeedItem other) { @@ -359,24 +358,16 @@ public class FeedItem extends FeedComponent implements ShownotesProvider, Flattr } private boolean isPlaying() { - if (media != null) { - return media.isPlaying(); - } - return false; + return media != null && media.isPlaying(); } @Override public Callable<String> loadShownotes() { - return new Callable<String>() { - @Override - public String call() throws Exception { - - if (contentEncoded == null || description == null) { - DBReader.loadExtraInformationOfFeedItem(FeedItem.this); - - } - return (contentEncoded != null) ? contentEncoded : description; + return () -> { + if (contentEncoded == null || description == null) { + DBReader.loadExtraInformationOfFeedItem(FeedItem.this); } + return (contentEncoded != null) ? contentEncoded : description; }; } diff --git a/core/src/main/java/de/danoeh/antennapod/core/feed/FeedMedia.java b/core/src/main/java/de/danoeh/antennapod/core/feed/FeedMedia.java index 6b11e162e..8a04e65ec 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/feed/FeedMedia.java +++ b/core/src/main/java/de/danoeh/antennapod/core/feed/FeedMedia.java @@ -499,20 +499,17 @@ public class FeedMedia extends FeedFile implements Playable { @Override public Callable<String> loadShownotes() { - return new Callable<String>() { - @Override - public String call() throws Exception { - if (item == null) { - item = DBReader.getFeedItem( - itemID); - } - if (item.getContentEncoded() == null || item.getDescription() == null) { - DBReader.loadExtraInformationOfFeedItem( - item); + return () -> { + if (item == null) { + item = DBReader.getFeedItem( + itemID); + } + if (item.getContentEncoded() == null || item.getDescription() == null) { + DBReader.loadExtraInformationOfFeedItem( + item); - } - return (item.getContentEncoded() != null) ? item.getContentEncoded() : item.getDescription(); } + return (item.getContentEncoded() != null) ? item.getContentEncoded() : item.getDescription(); }; } diff --git a/core/src/main/java/de/danoeh/antennapod/core/feed/FeedPreferences.java b/core/src/main/java/de/danoeh/antennapod/core/feed/FeedPreferences.java index 019001da7..e2b5dd7c2 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/feed/FeedPreferences.java +++ b/core/src/main/java/de/danoeh/antennapod/core/feed/FeedPreferences.java @@ -68,7 +68,7 @@ public class FeedPreferences { /** * @return the filter for this feed */ - public FeedFilter getFilter() { + public @NonNull FeedFilter getFilter() { return filter; } diff --git a/core/src/main/java/de/danoeh/antennapod/core/glide/ApOkHttpUrlLoader.java b/core/src/main/java/de/danoeh/antennapod/core/glide/ApOkHttpUrlLoader.java index 86baa459c..513264a05 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/glide/ApOkHttpUrlLoader.java +++ b/core/src/main/java/de/danoeh/antennapod/core/glide/ApOkHttpUrlLoader.java @@ -18,7 +18,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; -import de.danoeh.antennapod.core.ClientConfig; import de.danoeh.antennapod.core.service.download.AntennapodHttpClient; import de.danoeh.antennapod.core.service.download.HttpDownloader; import de.danoeh.antennapod.core.storage.DBReader; @@ -107,7 +106,6 @@ public class ApOkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> { public Response intercept(Chain chain) throws IOException { com.squareup.okhttp.Request request = chain.request(); String url = request.urlString(); - Context context = ClientConfig.applicationCallbacks.getApplicationInstance(); String authentication = DBReader.getImageAuthentication(url); if(TextUtils.isEmpty(authentication)) { diff --git a/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/GpodnetService.java b/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/GpodnetService.java index 48f234917..9f716e546 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/GpodnetService.java +++ b/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/GpodnetService.java @@ -80,7 +80,7 @@ public class GpodnetService { String response = executeRequest(request); try { JSONArray jsonTagList = new JSONArray(response); - List<GpodnetTag> tagList = new ArrayList<GpodnetTag>( + List<GpodnetTag> tagList = new ArrayList<>( jsonTagList.length()); for (int i = 0; i < jsonTagList.length(); i++) { JSONObject jObj = jsonTagList.getJSONObject(i); @@ -318,8 +318,7 @@ public class GpodnetService { URL url = new URI(BASE_SCHEME, BASE_HOST, String.format( "/subscriptions/%s.opml", username), null).toURL(); Request.Builder request = new Request.Builder().url(url); - String response = executeRequest(request); - return response; + return executeRequest(request); } catch (MalformedURLException | URISyntaxException e) { e.printStackTrace(); throw new GpodnetServiceException(e); @@ -660,7 +659,7 @@ public class GpodnetService { private List<GpodnetPodcast> readPodcastListFromJSONArray(@NonNull JSONArray array) throws JSONException { - List<GpodnetPodcast> result = new ArrayList<GpodnetPodcast>( + List<GpodnetPodcast> result = new ArrayList<>( array.length()); for (int i = 0; i < array.length(); i++) { result.add(readPodcastFromJSONObject(array.getJSONObject(i))); @@ -712,7 +711,7 @@ public class GpodnetService { private List<GpodnetDevice> readDeviceListFromJSONArray(@NonNull JSONArray array) throws JSONException { - List<GpodnetDevice> result = new ArrayList<GpodnetDevice>( + List<GpodnetDevice> result = new ArrayList<>( array.length()); for (int i = 0; i < array.length(); i++) { result.add(readDeviceFromJSONObject(array.getJSONObject(i))); @@ -732,7 +731,7 @@ public class GpodnetService { private GpodnetSubscriptionChange readSubscriptionChangesFromJSONObject( @NonNull JSONObject object) throws JSONException { - List<String> added = new LinkedList<String>(); + List<String> added = new LinkedList<>(); JSONArray jsonAdded = object.getJSONArray("add"); for (int i = 0; i < jsonAdded.length(); i++) { String addedUrl = jsonAdded.getString(i); @@ -741,7 +740,7 @@ public class GpodnetService { added.add(addedUrl); } - List<String> removed = new LinkedList<String>(); + List<String> removed = new LinkedList<>(); JSONArray jsonRemoved = object.getJSONArray("remove"); for (int i = 0; i < jsonRemoved.length(); i++) { String removedUrl = jsonRemoved.getString(i); @@ -757,7 +756,7 @@ public class GpodnetService { private GpodnetEpisodeActionGetResponse readEpisodeActionsFromJSONObject( @NonNull JSONObject object) throws JSONException { - List<GpodnetEpisodeAction> episodeActions = new ArrayList<GpodnetEpisodeAction>(); + List<GpodnetEpisodeAction> episodeActions = new ArrayList<>(); long timestamp = object.getLong("timestamp"); JSONArray jsonActions = object.getJSONArray("actions"); diff --git a/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetDevice.java b/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetDevice.java index 2d49c170a..79eb33cb5 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetDevice.java +++ b/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetDevice.java @@ -25,7 +25,7 @@ public class GpodnetDevice { + type + ", subscriptions=" + subscriptions + "]"; } - public static enum DeviceType { + public enum DeviceType { DESKTOP, LAPTOP, MOBILE, SERVER, OTHER; static DeviceType fromString(String s) { @@ -33,16 +33,17 @@ public class GpodnetDevice { return OTHER; } - if (s.equals("desktop")) { - return DESKTOP; - } else if (s.equals("laptop")) { - return LAPTOP; - } else if (s.equals("mobile")) { - return MOBILE; - } else if (s.equals("server")) { - return SERVER; - } else { - return OTHER; + switch (s) { + case "desktop": + return DESKTOP; + case "laptop": + return LAPTOP; + case "mobile": + return MOBILE; + case "server": + return SERVER; + default: + return OTHER; } } diff --git a/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetEpisodeAction.java b/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetEpisodeAction.java index 01c888d6b..9627ecae6 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetEpisodeAction.java +++ b/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetEpisodeAction.java @@ -61,14 +61,13 @@ public class GpodnetEpisodeAction { String deviceId = fields[2]; try { Action action = Action.valueOf(fields[3]); - GpodnetEpisodeAction result = new Builder(podcast, episode, action) + return new Builder(podcast, episode, action) .deviceId(deviceId) .timestamp(new Date(Long.parseLong(fields[4]))) .started(Integer.parseInt(fields[5])) .position(Integer.parseInt(fields[6])) .total(Integer.parseInt(fields[7])) .build(); - return result; } catch(IllegalArgumentException e) { Log.e(TAG, "readFromString(" + s + "): " + e.getMessage()); return null; diff --git a/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetEpisodeActionPostResponse.java b/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetEpisodeActionPostResponse.java index 5f096db14..03c33c9a1 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetEpisodeActionPostResponse.java +++ b/core/src/main/java/de/danoeh/antennapod/core/gpoddernet/model/GpodnetEpisodeActionPostResponse.java @@ -38,7 +38,7 @@ public class GpodnetEpisodeActionPostResponse { final JSONObject object = new JSONObject(objectString); final long timestamp = object.getLong("timestamp"); JSONArray urls = object.getJSONArray("update_urls"); - Map<String, String> updatedUrls = new ArrayMap<String, String>(urls.length()); + Map<String, String> updatedUrls = new ArrayMap<>(urls.length()); for (int i = 0; i < urls.length(); i++) { JSONArray urlPair = urls.getJSONArray(i); updatedUrls.put(urlPair.getString(0), urlPair.getString(1)); diff --git a/core/src/main/java/de/danoeh/antennapod/core/menuhandler/MenuItemUtils.java b/core/src/main/java/de/danoeh/antennapod/core/menuhandler/MenuItemUtils.java index b8d17bcce..f63c9aeb0 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/menuhandler/MenuItemUtils.java +++ b/core/src/main/java/de/danoeh/antennapod/core/menuhandler/MenuItemUtils.java @@ -32,7 +32,7 @@ public class MenuItemUtils { } } - public static interface UpdateRefreshMenuItemChecker { - public boolean isRefreshing(); + public interface UpdateRefreshMenuItemChecker { + boolean isRefreshing(); } } diff --git a/core/src/main/java/de/danoeh/antennapod/core/opml/OpmlReader.java b/core/src/main/java/de/danoeh/antennapod/core/opml/OpmlReader.java index 775129d09..17afc7904 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/opml/OpmlReader.java +++ b/core/src/main/java/de/danoeh/antennapod/core/opml/OpmlReader.java @@ -1,7 +1,7 @@ package de.danoeh.antennapod.core.opml; import android.util.Log; -import de.danoeh.antennapod.core.BuildConfig; + import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; @@ -10,6 +10,8 @@ import java.io.IOException; import java.io.Reader; import java.util.ArrayList; +import de.danoeh.antennapod.core.BuildConfig; + /** Reads OPML documents. */ public class OpmlReader { private static final String TAG = "OpmlReader"; @@ -27,7 +29,7 @@ public class OpmlReader { */ public ArrayList<OpmlElement> readDocument(Reader reader) throws XmlPullParserException, IOException { - elementList = new ArrayList<OpmlElement>(); + elementList = new ArrayList<>(); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); diff --git a/core/src/main/java/de/danoeh/antennapod/core/preferences/GpodnetPreferences.java b/core/src/main/java/de/danoeh/antennapod/core/preferences/GpodnetPreferences.java index edd7b807a..6d4d3baa6 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/preferences/GpodnetPreferences.java +++ b/core/src/main/java/de/danoeh/antennapod/core/preferences/GpodnetPreferences.java @@ -189,7 +189,7 @@ public class GpodnetPreferences { public static Set<String> getAddedFeedsCopy() { ensurePreferencesLoaded(); - Set<String> copy = new HashSet<String>(); + Set<String> copy = new HashSet<>(); feedListLock.lock(); copy.addAll(addedFeeds); feedListLock.unlock(); @@ -206,7 +206,7 @@ public class GpodnetPreferences { public static Set<String> getRemovedFeedsCopy() { ensurePreferencesLoaded(); - Set<String> copy = new HashSet<String>(); + Set<String> copy = new HashSet<>(); feedListLock.lock(); copy.addAll(removedFeeds); feedListLock.unlock(); @@ -232,7 +232,7 @@ public class GpodnetPreferences { public static List<GpodnetEpisodeAction> getQueuedEpisodeActions() { ensurePreferencesLoaded(); - List<GpodnetEpisodeAction> copy = new ArrayList(); + List<GpodnetEpisodeAction> copy = new ArrayList<>(); feedListLock.lock(); copy.addAll(queuedEpisodeActions); feedListLock.unlock(); @@ -272,7 +272,7 @@ public class GpodnetPreferences { } private static Set<String> readListFromString(String s) { - Set<String> result = new HashSet<String>(); + Set<String> result = new HashSet<>(); for (String item : s.split(" ")) { result.add(item); } @@ -290,7 +290,7 @@ public class GpodnetPreferences { private static List<GpodnetEpisodeAction> readEpisodeActionsFromString(String s) { String[] lines = s.split("\n"); - List<GpodnetEpisodeAction> result = new ArrayList<GpodnetEpisodeAction>(lines.length); + List<GpodnetEpisodeAction> result = new ArrayList<>(lines.length); for(String line : lines) { if(TextUtils.isEmpty(line)) { GpodnetEpisodeAction action = GpodnetEpisodeAction.readFromString(line); diff --git a/core/src/main/java/de/danoeh/antennapod/core/preferences/UserPreferences.java b/core/src/main/java/de/danoeh/antennapod/core/preferences/UserPreferences.java index f9613cc3d..2541a27aa 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/preferences/UserPreferences.java +++ b/core/src/main/java/de/danoeh/antennapod/core/preferences/UserPreferences.java @@ -292,7 +292,7 @@ public class UserPreferences { public static long getUpdateInterval() { String updateInterval = prefs.getString(PREF_UPDATE_INTERVAL, "0"); - if(false == updateInterval.contains(":")) { + if(!updateInterval.contains(":")) { return readUpdateInterval(updateInterval); } else { return 0; @@ -411,8 +411,7 @@ public class UserPreferences { int port = prefs.getInt(PREF_PROXY_PORT, 0); String username = prefs.getString(PREF_PROXY_USER, null); String password = prefs.getString(PREF_PROXY_PASSWORD, null); - ProxyConfig config = new ProxyConfig(type, host, port, username, password); - return config; + return new ProxyConfig(type, host, port, username, password); } public static boolean shouldResumeAfterCall() { diff --git a/core/src/main/java/de/danoeh/antennapod/core/service/download/DownloadService.java b/core/src/main/java/de/danoeh/antennapod/core/service/download/DownloadService.java index be6cd88cb..3f0112b56 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/service/download/DownloadService.java +++ b/core/src/main/java/de/danoeh/antennapod/core/service/download/DownloadService.java @@ -41,11 +41,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -252,54 +249,35 @@ public class DownloadService extends Service { Log.d(TAG, "Service started"); isRunning = true; handler = new Handler(); - reportQueue = Collections.synchronizedList(new ArrayList<DownloadStatus>()); - downloads = Collections.synchronizedList(new ArrayList<Downloader>()); + reportQueue = Collections.synchronizedList(new ArrayList<>()); + downloads = Collections.synchronizedList(new ArrayList<>()); numberOfDownloads = new AtomicInteger(0); IntentFilter cancelDownloadReceiverFilter = new IntentFilter(); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_ALL_DOWNLOADS); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_DOWNLOAD); registerReceiver(cancelDownloadReceiver, cancelDownloadReceiverFilter); - syncExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { - - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setPriority(Thread.MIN_PRIORITY); - return t; - } + syncExecutor = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r); + t.setPriority(Thread.MIN_PRIORITY); + return t; }); Log.d(TAG, "parallel downloads: " + UserPreferences.getParallelDownloads()); - downloadExecutor = new ExecutorCompletionService<Downloader>( + downloadExecutor = new ExecutorCompletionService<>( Executors.newFixedThreadPool(UserPreferences.getParallelDownloads(), - new ThreadFactory() { - - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setPriority(Thread.MIN_PRIORITY); - return t; - } + r -> { + Thread t = new Thread(r); + t.setPriority(Thread.MIN_PRIORITY); + return t; } ) ); schedExecutor = new ScheduledThreadPoolExecutor(SCHED_EX_POOL_SIZE, - new ThreadFactory() { - - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setPriority(Thread.MIN_PRIORITY); - return t; - } - }, new RejectedExecutionHandler() { - - @Override - public void rejectedExecution(Runnable r, - ThreadPoolExecutor executor) { - Log.w(TAG, "SchedEx rejected submission of new task"); - } - } + r -> { + Thread t = new Thread(r); + t.setPriority(Thread.MIN_PRIORITY); + return t; + }, (r, executor) -> Log.w(TAG, "SchedEx rejected submission of new task") ); downloadCompletionThread.start(); feedSyncThread = new FeedSyncThread(); @@ -383,16 +361,16 @@ public class DownloadService extends Service { if (i > 0) { bigText.append("\n"); } - bigText.append("\u2022 " + request.getTitle()); + bigText.append("\u2022 ").append(request.getTitle()); } } else if (request.getFeedfileType() == FeedMedia.FEEDFILETYPE_FEEDMEDIA) { if (request.getTitle() != null) { if (i > 0) { bigText.append("\n"); } - bigText.append("\u2022 " + request.getTitle() - + " (" + request.getProgressPercent() - + "%)"); + bigText.append("\u2022 ").append(request.getTitle()) + .append(" (").append(request.getProgressPercent()) + .append("%)"); } } @@ -489,16 +467,13 @@ public class DownloadService extends Service { * DownloadService list. */ private void removeDownload(final Downloader d) { - handler.post(new Runnable() { - @Override - public void run() { - Log.d(TAG, "Removing downloader: " - + d.getDownloadRequest().getSource()); - boolean rc = downloads.remove(d); - Log.d(TAG, "Result of downloads.remove: " + rc); - DownloadRequester.getInstance().removeDownload(d.getDownloadRequest()); - postDownloaders(); - } + handler.post(() -> { + Log.d(TAG, "Removing downloader: " + + d.getDownloadRequest().getSource()); + boolean rc = downloads.remove(d); + Log.d(TAG, "Result of downloads.remove: " + rc); + DownloadRequester.getInstance().removeDownload(d.getDownloadRequest()); + postDownloaders(); }); } @@ -574,12 +549,7 @@ public class DownloadService extends Service { * used from a thread other than the main thread. */ void queryDownloadsAsync() { - handler.post(new Runnable() { - public void run() { - queryDownloads(); - ; - } - }); + handler.post(DownloadService.this::queryDownloads); } /** @@ -598,27 +568,24 @@ public class DownloadService extends Service { } private void postAuthenticationNotification(final DownloadRequest downloadRequest) { - handler.post(new Runnable() { - @Override - public void run() { - final String resourceTitle = (downloadRequest.getTitle() != null) - ? downloadRequest.getTitle() : downloadRequest.getSource(); - - NotificationCompat.Builder builder = new NotificationCompat.Builder(DownloadService.this); - builder.setTicker(getText(R.string.authentication_notification_title)) - .setContentTitle(getText(R.string.authentication_notification_title)) - .setContentText(getText(R.string.authentication_notification_msg)) - .setStyle(new NotificationCompat.BigTextStyle().bigText(getText(R.string.authentication_notification_msg) - + ": " + resourceTitle)) - .setSmallIcon(R.drawable.ic_stat_authentication) - .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_authentication)) - .setAutoCancel(true) - .setContentIntent(ClientConfig.downloadServiceCallbacks.getAuthentificationNotificationContentIntent(DownloadService.this, downloadRequest)) - .setVisibility(Notification.VISIBILITY_PUBLIC); - Notification n = builder.build(); - NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - nm.notify(downloadRequest.getSource().hashCode(), n); - } + handler.post(() -> { + final String resourceTitle = (downloadRequest.getTitle() != null) + ? downloadRequest.getTitle() : downloadRequest.getSource(); + + NotificationCompat.Builder builder = new NotificationCompat.Builder(DownloadService.this); + builder.setTicker(getText(R.string.authentication_notification_title)) + .setContentTitle(getText(R.string.authentication_notification_title)) + .setContentText(getText(R.string.authentication_notification_msg)) + .setStyle(new NotificationCompat.BigTextStyle().bigText(getText(R.string.authentication_notification_msg) + + ": " + resourceTitle)) + .setSmallIcon(R.drawable.ic_stat_authentication) + .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_authentication)) + .setAutoCancel(true) + .setContentIntent(ClientConfig.downloadServiceCallbacks.getAuthentificationNotificationContentIntent(DownloadService.this, downloadRequest)) + .setVisibility(Notification.VISIBILITY_PUBLIC); + Notification n = builder.build(); + NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(downloadRequest.getSource().hashCode(), n); }); } @@ -651,8 +618,8 @@ public class DownloadService extends Service { class FeedSyncThread extends Thread { private static final String TAG = "FeedSyncThread"; - private BlockingQueue<DownloadRequest> completedRequests = new LinkedBlockingDeque<DownloadRequest>(); - private CompletionService<Pair<DownloadRequest, FeedHandlerResult>> parserService = new ExecutorCompletionService<Pair<DownloadRequest, FeedHandlerResult>>(Executors.newSingleThreadExecutor()); + private BlockingQueue<DownloadRequest> completedRequests = new LinkedBlockingDeque<>(); + private CompletionService<Pair<DownloadRequest, FeedHandlerResult>> parserService = new ExecutorCompletionService<>(Executors.newSingleThreadExecutor()); private ExecutorService dbService = Executors.newSingleThreadExecutor(); private Future<?> dbUpdateFuture; private volatile boolean isActive = true; @@ -668,7 +635,7 @@ public class DownloadService extends Service { * @return Collected feeds or null if the method has been interrupted during the first waiting period. */ private List<Pair<DownloadRequest, FeedHandlerResult>> collectCompletedRequests() { - List<Pair<DownloadRequest, FeedHandlerResult>> results = new LinkedList<Pair<DownloadRequest, FeedHandlerResult>>(); + List<Pair<DownloadRequest, FeedHandlerResult>> results = new LinkedList<>(); DownloadRequester requester = DownloadRequester.getInstance(); int tasks = 0; @@ -712,11 +679,9 @@ public class DownloadService extends Service { if (result != null) { results.add(result); } - } catch (InterruptedException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); } } @@ -751,41 +716,36 @@ public class DownloadService extends Service { if (dbUpdateFuture != null) { try { dbUpdateFuture.get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } - dbUpdateFuture = dbService.submit(new Runnable() { - @Override - public void run() { - Feed[] savedFeeds = DBTasks.updateFeed(DownloadService.this, getFeeds(results)); - - for (int i = 0; i < savedFeeds.length; i++) { - Feed savedFeed = savedFeeds[i]; - - // If loadAllPages=true, check if another page is available and queue it for download - final boolean loadAllPages = results.get(i).first.getArguments().getBoolean(DownloadRequester.REQUEST_ARG_LOAD_ALL_PAGES); - final Feed feed = results.get(i).second.feed; - if (loadAllPages && feed.getNextPageLink() != null) { - try { - feed.setId(savedFeed.getId()); - DBTasks.loadNextPageOfFeed(DownloadService.this, savedFeed, true); - } catch (DownloadRequestException e) { - Log.e(TAG, "Error trying to load next page", e); - } + dbUpdateFuture = dbService.submit(() -> { + Feed[] savedFeeds = DBTasks.updateFeed(DownloadService.this, getFeeds(results)); + + for (int i = 0; i < savedFeeds.length; i++) { + Feed savedFeed = savedFeeds[i]; + + // If loadAllPages=true, check if another page is available and queue it for download + final boolean loadAllPages = results.get(i).first.getArguments().getBoolean(DownloadRequester.REQUEST_ARG_LOAD_ALL_PAGES); + final Feed feed = results.get(i).second.feed; + if (loadAllPages && feed.getNextPageLink() != null) { + try { + feed.setId(savedFeed.getId()); + DBTasks.loadNextPageOfFeed(DownloadService.this, savedFeed, true); + } catch (DownloadRequestException e) { + Log.e(TAG, "Error trying to load next page", e); } - - ClientConfig.downloadServiceCallbacks.onFeedParsed(DownloadService.this, - savedFeed); - - numberOfDownloads.decrementAndGet(); } - queryDownloadsAsync(); + ClientConfig.downloadServiceCallbacks.onFeedParsed(DownloadService.this, + savedFeed); + + numberOfDownloads.decrementAndGet(); } + + queryDownloadsAsync(); }); } @@ -847,21 +807,11 @@ public class DownloadService extends Service { try { result = feedHandler.parseFeed(feed); Log.d(TAG, feed.getTitle() + " parsed"); - if (checkFeedData(feed) == false) { + if (!checkFeedData(feed)) { throw new InvalidFeedException(); } - } catch (SAXException e) { - successful = false; - e.printStackTrace(); - reason = DownloadError.ERROR_PARSER_EXCEPTION; - reasonDetailed = e.getMessage(); - } catch (IOException e) { - successful = false; - e.printStackTrace(); - reason = DownloadError.ERROR_PARSER_EXCEPTION; - reasonDetailed = e.getMessage(); - } catch (ParserConfigurationException e) { + } catch (SAXException | IOException | ParserConfigurationException e) { successful = false; e.printStackTrace(); reason = DownloadError.ERROR_PARSER_EXCEPTION; @@ -884,7 +834,7 @@ public class DownloadService extends Service { if (successful) { // we create a 'successful' download log if the feed's last refresh failed List<DownloadStatus> log = DBReader.getFeedDownloadLog(feed); - if(log.size() > 0 && log.get(0).isSuccessful() == false) { + if(log.size() > 0 && !log.get(0).isSuccessful()) { saveDownloadStatus(new DownloadStatus(feed, feed.getHumanReadableIdentifier(), DownloadError.SUCCESS, successful, reasonDetailed)); @@ -1017,9 +967,7 @@ public class DownloadService extends Service { media.setFile_url(request.getDestination()); try { DBWriter.setFeedMedia(media).get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } @@ -1087,10 +1035,7 @@ public class DownloadService extends Service { if (item != null && !DBTasks.isInQueue(DownloadService.this, item.getId())) { DBWriter.addQueueItem(DownloadService.this, item).get(); } - } catch (ExecutionException e) { - e.printStackTrace(); - status = new DownloadStatus(media, media.getEpisodeTitle(), DownloadError.ERROR_DB_ACCESS_ERROR, false, e.getMessage()); - } catch (InterruptedException e) { + } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); status = new DownloadStatus(media, media.getEpisodeTitle(), DownloadError.ERROR_DB_ACCESS_ERROR, false, e.getMessage()); } @@ -1134,14 +1079,11 @@ public class DownloadService extends Service { private class NotificationUpdater implements Runnable { public void run() { - handler.post(new Runnable() { - @Override - public void run() { - Notification n = updateNotifications(); - if (n != null) { - NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - nm.notify(NOTIFICATION_ID, n); - } + handler.post(() -> { + Notification n = updateNotifications(); + if (n != null) { + NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(NOTIFICATION_ID, n); } }); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/service/download/DownloaderCallback.java b/core/src/main/java/de/danoeh/antennapod/core/service/download/DownloaderCallback.java index 2d9347b0a..b0829f084 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/service/download/DownloaderCallback.java +++ b/core/src/main/java/de/danoeh/antennapod/core/service/download/DownloaderCallback.java @@ -6,5 +6,5 @@ package de.danoeh.antennapod.core.service.download; */ public interface DownloaderCallback { - public void onDownloadCompleted(Downloader downloader); + void onDownloadCompleted(Downloader downloader); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/service/download/HttpDownloader.java b/core/src/main/java/de/danoeh/antennapod/core/service/download/HttpDownloader.java index 2b26f58c0..f79cf9685 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/service/download/HttpDownloader.java +++ b/core/src/main/java/de/danoeh/antennapod/core/service/download/HttpDownloader.java @@ -21,7 +21,7 @@ import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URI; import java.net.UnknownHostException; -import java.util.Arrays; +import java.util.Collections; import java.util.Date; import de.danoeh.antennapod.core.ClientConfig; @@ -84,9 +84,8 @@ public class HttpDownloader extends Downloader { httpReq.addHeader("If-Modified-Since", lastModified); } } else { - String eTag = lastModified; - Log.d(TAG, "addHeader(\"If-None-Match\", \"" + eTag + "\")"); - httpReq.addHeader("If-None-Match", eTag); + Log.d(TAG, "addHeader(\"If-None-Match\", \"" + lastModified + "\")"); + httpReq.addHeader("If-None-Match", lastModified); } } @@ -111,13 +110,13 @@ public class HttpDownloader extends Downloader { Log.d(TAG, "Adding range header: " + request.getSoFar()); } - Response response = null; + Response response; try { response = httpClient.newCall(httpReq.build()).execute(); } catch(IOException e) { Log.e(TAG, e.toString()); if(e.getMessage().contains("PROTOCOL_ERROR")) { - httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); + httpClient.setProtocols(Collections.singletonList(Protocol.HTTP_1_1)); response = httpClient.newCall(httpReq.build()).execute(); } else { diff --git a/core/src/main/java/de/danoeh/antennapod/core/service/download/ProxyConfig.java b/core/src/main/java/de/danoeh/antennapod/core/service/download/ProxyConfig.java index e886932f2..6eb1f4118 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/service/download/ProxyConfig.java +++ b/core/src/main/java/de/danoeh/antennapod/core/service/download/ProxyConfig.java @@ -8,7 +8,7 @@ public class ProxyConfig { public final Proxy.Type type; @Nullable public final String host; - @Nullable public final int port; + public final int port; @Nullable public final String username; @Nullable public final String password; diff --git a/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackService.java b/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackService.java index 2be075a92..9ca05d1f7 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackService.java +++ b/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackService.java @@ -835,7 +835,7 @@ public class PlaybackService extends Service { if (!Thread.currentThread().isInterrupted() && started && info.playable != null) { String contentText = info.playable.getEpisodeTitle(); String contentTitle = info.playable.getFeedTitle(); - Notification notification = null; + Notification notification; // Builder is v7, even if some not overwritten methods return its parent's v4 interface NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder( diff --git a/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackServiceMediaPlayer.java b/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackServiceMediaPlayer.java index 3c41fc0a4..3ab26eb22 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackServiceMediaPlayer.java +++ b/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackServiceMediaPlayer.java @@ -99,7 +99,7 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); this.playerLock = new ReentrantLock(); this.startWhenPrepared = new AtomicBoolean(false); - executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.MINUTES, new LinkedBlockingDeque<Runnable>(), + executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.MINUTES, new LinkedBlockingDeque<>(), new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { @@ -175,18 +175,15 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre */ public void playMediaObject(@NonNull final Playable playable, final boolean stream, final boolean startWhenPrepared, final boolean prepareImmediately) { Log.d(TAG, "playMediaObject(...)"); - executor.submit(new Runnable() { - @Override - public void run() { - playerLock.lock(); - try { - playMediaObject(playable, false, stream, startWhenPrepared, prepareImmediately); - } catch (RuntimeException e) { - e.printStackTrace(); - throw e; - } finally { - playerLock.unlock(); - } + executor.submit(() -> { + playerLock.lock(); + try { + playMediaObject(playable, false, stream, startWhenPrepared, prepareImmediately); + } catch (RuntimeException e) { + e.printStackTrace(); + throw e; + } finally { + playerLock.unlock(); } }); } @@ -258,24 +255,13 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre } setPlayerStatus(PlayerStatus.INITIALIZED, media); - if (mediaType == MediaType.VIDEO) { - VideoPlayer vp = (VideoPlayer) mediaPlayer; - // vp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT); - } - if (prepareImmediately) { setPlayerStatus(PlayerStatus.PREPARING, media); mediaPlayer.prepare(); onPrepared(startWhenPrepared); } - } catch (Playable.PlayableException e) { - e.printStackTrace(); - setPlayerStatus(PlayerStatus.ERROR, null); - } catch (IOException e) { - e.printStackTrace(); - setPlayerStatus(PlayerStatus.ERROR, null); - } catch (IllegalStateException e) { + } catch (Playable.PlayableException | IOException | IllegalStateException e) { e.printStackTrace(); setPlayerStatus(PlayerStatus.ERROR, null); } @@ -379,58 +365,52 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre * file is being streamed */ public void pause(final boolean abandonFocus, final boolean reinit) { - executor.submit(new Runnable() { - @Override - public void run() { - playerLock.lock(); - releaseWifiLockIfNecessary(); - if (playerStatus == PlayerStatus.PLAYING) { - Log.d(TAG, "Pausing playback."); - mediaPlayer.pause(); - setPlayerStatus(PlayerStatus.PAUSED, media); + executor.submit(() -> { + playerLock.lock(); + releaseWifiLockIfNecessary(); + if (playerStatus == PlayerStatus.PLAYING) { + Log.d(TAG, "Pausing playback."); + mediaPlayer.pause(); + setPlayerStatus(PlayerStatus.PAUSED, media); - if (abandonFocus) { - audioManager.abandonAudioFocus(audioFocusChangeListener); - pausedBecauseOfTransientAudiofocusLoss = false; - } - if (stream && reinit) { - reinit(); - } - } else { - Log.d(TAG, "Ignoring call to pause: Player is in " + playerStatus + " state"); + if (abandonFocus) { + audioManager.abandonAudioFocus(audioFocusChangeListener); + pausedBecauseOfTransientAudiofocusLoss = false; } - - playerLock.unlock(); + if (stream && reinit) { + reinit(); + } + } else { + Log.d(TAG, "Ignoring call to pause: Player is in " + playerStatus + " state"); } + + playerLock.unlock(); }); } /** - * Prepared media player for playback if the service is in the INITALIZED + * Prepares media player for playback if the service is in the INITALIZED * state. * <p/> * This method is executed on an internal executor service. */ public void prepare() { - executor.submit(new Runnable() { - @Override - public void run() { - playerLock.lock(); - - if (playerStatus == PlayerStatus.INITIALIZED) { - Log.d(TAG, "Preparing media player"); - setPlayerStatus(PlayerStatus.PREPARING, media); - try { - mediaPlayer.prepare(); - onPrepared(startWhenPrepared.get()); - } catch (IOException e) { - e.printStackTrace(); - setPlayerStatus(PlayerStatus.ERROR, null); - } - } - playerLock.unlock(); + executor.submit(() -> { + playerLock.lock(); + if (playerStatus == PlayerStatus.INITIALIZED) { + Log.d(TAG, "Preparing media player"); + setPlayerStatus(PlayerStatus.PREPARING, media); + try { + mediaPlayer.prepare(); + onPrepared(startWhenPrepared.get()); + } catch (IOException e) { + e.printStackTrace(); + setPlayerStatus(PlayerStatus.ERROR, null); + } } + playerLock.unlock(); + }); } @@ -449,7 +429,7 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre if (mediaType == MediaType.VIDEO) { VideoPlayer vp = (VideoPlayer) mediaPlayer; - videoSize = new Pair<Integer, Integer>(vp.getVideoWidth(), vp.getVideoHeight()); + videoSize = new Pair<>(vp.getVideoWidth(), vp.getVideoHeight()); } if (media.getPosition() > 0) { @@ -475,20 +455,17 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre * This method is executed on an internal executor service. */ public void reinit() { - executor.submit(new Runnable() { - @Override - public void run() { - playerLock.lock(); - releaseWifiLockIfNecessary(); - if (media != null) { - playMediaObject(media, true, stream, startWhenPrepared.get(), false); - } else if (mediaPlayer != null) { - mediaPlayer.reset(); - } else { - Log.d(TAG, "Call to reinit was ignored: media and mediaPlayer were null"); - } - playerLock.unlock(); + executor.submit(() -> { + playerLock.lock(); + releaseWifiLockIfNecessary(); + if (media != null) { + playMediaObject(media, true, stream, startWhenPrepared.get(), false); + } else if (mediaPlayer != null) { + mediaPlayer.reset(); + } else { + Log.d(TAG, "Call to reinit was ignored: media and mediaPlayer were null"); } + playerLock.unlock(); }); } @@ -542,12 +519,7 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre * This method is executed on an internal executor service. */ public void seekTo(final int t) { - executor.submit(new Runnable() { - @Override - public void run() { - seekToSync(t); - } - }); + executor.submit(() -> seekToSync(t)); } /** @@ -556,19 +528,16 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre * @param d offset from current position (positive or negative) */ public void seekDelta(final int d) { - executor.submit(new Runnable() { - @Override - public void run() { - playerLock.lock(); - int currentPosition = getPosition(); - if (currentPosition != INVALID_TIME) { - seekToSync(currentPosition + d); - } else { - Log.e(TAG, "getPosition() returned INVALID_TIME in seekDelta"); - } - - playerLock.unlock(); + executor.submit(() -> { + playerLock.lock(); + int currentPosition = getPosition(); + if (currentPosition != INVALID_TIME) { + seekToSync(currentPosition + d); + } else { + Log.e(TAG, "getPosition() returned INVALID_TIME in seekDelta"); } + + playerLock.unlock(); }); } @@ -655,7 +624,7 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre playerLock.lock(); if (media != null && media.getMediaType() == MediaType.AUDIO) { if (mediaPlayer.canSetSpeed()) { - mediaPlayer.setPlaybackSpeed((float) speed); + mediaPlayer.setPlaybackSpeed(speed); Log.d(TAG, "Playback speed was set to " + speed); callback.playbackSpeedChanged(speed); } @@ -668,12 +637,7 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre * This method is executed on an internal executor service. */ public void setSpeed(final float speed) { - executor.submit(new Runnable() { - @Override - public void run() { - setSpeedSync(speed); - } - }); + executor.submit(() -> setSpeedSync(speed)); } /** @@ -759,28 +723,22 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre } public void setVideoSurface(final SurfaceHolder surface) { - executor.submit(new Runnable() { - @Override - public void run() { - playerLock.lock(); - if (mediaPlayer != null) { - mediaPlayer.setDisplay(surface); - } - playerLock.unlock(); + executor.submit(() -> { + playerLock.lock(); + if (mediaPlayer != null) { + mediaPlayer.setDisplay(surface); } + playerLock.unlock(); }); } public void resetVideoSurface() { - executor.submit(new Runnable() { - @Override - public void run() { - playerLock.lock(); - Log.d(TAG, "Resetting video surface"); - mediaPlayer.setDisplay(null); - reinit(); - playerLock.unlock(); - } + executor.submit(() -> { + playerLock.lock(); + Log.d(TAG, "Resetting video surface"); + mediaPlayer.setDisplay(null); + reinit(); + playerLock.unlock(); }); } @@ -801,7 +759,7 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre res = null; } else { VideoPlayer vp = (VideoPlayer) mediaPlayer; - videoSize = new Pair<Integer, Integer>(vp.getVideoWidth(), vp.getVideoHeight()); + videoSize = new Pair<>(vp.getVideoWidth(), vp.getVideoHeight()); res = videoSize; } playerLock.unlock(); @@ -1007,20 +965,17 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre * abandoning audio focus have to be done with other methods. */ public void stop() { - executor.submit(new Runnable() { - @Override - public void run() { - playerLock.lock(); - releaseWifiLockIfNecessary(); - - if (playerStatus == PlayerStatus.INDETERMINATE) { - setPlayerStatus(PlayerStatus.STOPPED, null); - } else { - Log.d(TAG, "Ignored call to stop: Current player state is: " + playerStatus); - } - playerLock.unlock(); + executor.submit(() -> { + playerLock.lock(); + releaseWifiLockIfNecessary(); + if (playerStatus == PlayerStatus.INDETERMINATE) { + setPlayerStatus(PlayerStatus.STOPPED, null); + } else { + Log.d(TAG, "Ignored call to stop: Current player state is: " + playerStatus); } + playerLock.unlock(); + }); } @@ -1095,100 +1050,59 @@ public class PlaybackServiceMediaPlayer implements SharedPreferences.OnSharedPre return mp; } - private final org.antennapod.audio.MediaPlayer.OnCompletionListener audioCompletionListener = new org.antennapod.audio.MediaPlayer.OnCompletionListener() { - @Override - public void onCompletion(org.antennapod.audio.MediaPlayer mp) { - genericOnCompletion(); - } - }; + private final org.antennapod.audio.MediaPlayer.OnCompletionListener audioCompletionListener = + mp -> genericOnCompletion(); - private final android.media.MediaPlayer.OnCompletionListener videoCompletionListener = new android.media.MediaPlayer.OnCompletionListener() { - @Override - public void onCompletion(android.media.MediaPlayer mp) { - genericOnCompletion(); - } - }; + private final android.media.MediaPlayer.OnCompletionListener videoCompletionListener = + mp -> genericOnCompletion(); private void genericOnCompletion() { endPlayback(false); } - private final org.antennapod.audio.MediaPlayer.OnBufferingUpdateListener audioBufferingUpdateListener = new org.antennapod.audio.MediaPlayer.OnBufferingUpdateListener() { - @Override - public void onBufferingUpdate(org.antennapod.audio.MediaPlayer mp, - int percent) { - genericOnBufferingUpdate(percent); - } - }; + private final org.antennapod.audio.MediaPlayer.OnBufferingUpdateListener audioBufferingUpdateListener = + (mp, percent) -> genericOnBufferingUpdate(percent); - private final android.media.MediaPlayer.OnBufferingUpdateListener videoBufferingUpdateListener = new android.media.MediaPlayer.OnBufferingUpdateListener() { - @Override - public void onBufferingUpdate(android.media.MediaPlayer mp, int percent) { - genericOnBufferingUpdate(percent); - } - }; + private final android.media.MediaPlayer.OnBufferingUpdateListener videoBufferingUpdateListener = + (mp, percent) -> genericOnBufferingUpdate(percent); private void genericOnBufferingUpdate(int percent) { callback.onBufferingUpdate(percent); } - private final org.antennapod.audio.MediaPlayer.OnInfoListener audioInfoListener = new org.antennapod.audio.MediaPlayer.OnInfoListener() { - @Override - public boolean onInfo(org.antennapod.audio.MediaPlayer mp, int what, - int extra) { - return genericInfoListener(what); - } - }; + private final org.antennapod.audio.MediaPlayer.OnInfoListener audioInfoListener = + (mp, what, extra) -> genericInfoListener(what); - private final android.media.MediaPlayer.OnInfoListener videoInfoListener = new android.media.MediaPlayer.OnInfoListener() { - @Override - public boolean onInfo(android.media.MediaPlayer mp, int what, int extra) { - return genericInfoListener(what); - } - }; + private final android.media.MediaPlayer.OnInfoListener videoInfoListener = + (mp, what, extra) -> genericInfoListener(what); private boolean genericInfoListener(int what) { return callback.onMediaPlayerInfo(what); } - private final org.antennapod.audio.MediaPlayer.OnErrorListener audioErrorListener = new org.antennapod.audio.MediaPlayer.OnErrorListener() { - @Override - public boolean onError(org.antennapod.audio.MediaPlayer mp, int what, int extra) { - if(mp.canFallback()) { - mp.fallback(); - return true; - } else { - return genericOnError(mp, what, extra); - } - } - }; + private final org.antennapod.audio.MediaPlayer.OnErrorListener audioErrorListener = + (mp, what, extra) -> { + if(mp.canFallback()) { + mp.fallback(); + return true; + } else { + return genericOnError(mp, what, extra); + } + }; - private final android.media.MediaPlayer.OnErrorListener videoErrorListener = new android.media.MediaPlayer.OnErrorListener() { - @Override - public boolean onError(android.media.MediaPlayer mp, int what, int extra) { - return genericOnError(mp, what, extra); - } - }; + private final android.media.MediaPlayer.OnErrorListener videoErrorListener = this::genericOnError; private boolean genericOnError(Object inObj, int what, int extra) { return callback.onMediaPlayerError(inObj, what, extra); } - private final org.antennapod.audio.MediaPlayer.OnSeekCompleteListener audioSeekCompleteListener = new org.antennapod.audio.MediaPlayer.OnSeekCompleteListener() { - @Override - public void onSeekComplete(org.antennapod.audio.MediaPlayer mp) { - genericSeekCompleteListener(); - } - }; + private final org.antennapod.audio.MediaPlayer.OnSeekCompleteListener audioSeekCompleteListener = + mp -> genericSeekCompleteListener(); - private final android.media.MediaPlayer.OnSeekCompleteListener videoSeekCompleteListener = new android.media.MediaPlayer.OnSeekCompleteListener() { - @Override - public void onSeekComplete(android.media.MediaPlayer mp) { - genericSeekCompleteListener(); - } - }; + private final android.media.MediaPlayer.OnSeekCompleteListener videoSeekCompleteListener = + mp -> genericSeekCompleteListener(); - private final void genericSeekCompleteListener() { + private void genericSeekCompleteListener() { Thread t = new Thread(() -> { Log.d(TAG, "genericSeekCompleteListener"); if(seekLatch != null) { diff --git a/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackServiceTaskManager.java b/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackServiceTaskManager.java index 680fb8777..8a0964d36 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackServiceTaskManager.java +++ b/core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackServiceTaskManager.java @@ -6,12 +6,10 @@ import android.support.annotation.NonNull; import android.util.Log; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import de.danoeh.antennapod.core.event.QueueEvent; @@ -65,13 +63,10 @@ public class PlaybackServiceTaskManager { @NonNull PSTMCallback callback) { this.context = context; this.callback = callback; - schedExecutor = new ScheduledThreadPoolExecutor(SCHED_EX_POOL_SIZE, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setPriority(Thread.MIN_PRIORITY); - return t; - } + schedExecutor = new ScheduledThreadPoolExecutor(SCHED_EX_POOL_SIZE, r -> { + Thread t = new Thread(r); + t.setPriority(Thread.MIN_PRIORITY); + return t; }); loadQueue(); EventBus.getDefault().register(this); @@ -95,12 +90,7 @@ public class PlaybackServiceTaskManager { private synchronized void loadQueue() { if (!isQueueLoaderActive()) { - queueFuture = schedExecutor.submit(new Callable<List<FeedItem>>() { - @Override - public List<FeedItem> call() throws Exception { - return DBReader.getQueue(); - } - }); + queueFuture = schedExecutor.submit(DBReader::getQueue); } } @@ -112,9 +102,7 @@ public class PlaybackServiceTaskManager { if (queueFuture.isDone()) { try { return queueFuture.get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } @@ -137,12 +125,7 @@ public class PlaybackServiceTaskManager { */ public synchronized void startPositionSaver() { if (!isPositionSaverActive()) { - Runnable positionSaver = new Runnable() { - @Override - public void run() { - callback.positionSaverTick(); - } - }; + Runnable positionSaver = callback::positionSaverTick; positionSaverFuture = schedExecutor.scheduleWithFixedDelay(positionSaver, POSITION_SAVER_WAITING_INTERVAL, POSITION_SAVER_WAITING_INTERVAL, TimeUnit.MILLISECONDS); @@ -174,12 +157,7 @@ public class PlaybackServiceTaskManager { */ public synchronized void startWidgetUpdater() { if (!isWidgetUpdaterActive()) { - Runnable widgetUpdater = new Runnable() { - @Override - public void run() { - callback.onWidgetUpdaterTick(); - } - }; + Runnable widgetUpdater = callback::onWidgetUpdaterTick; widgetUpdaterFuture = schedExecutor.scheduleWithFixedDelay(widgetUpdater, WIDGET_UPDATER_NOTIFICATION_INTERVAL, WIDGET_UPDATER_NOTIFICATION_INTERVAL, TimeUnit.MILLISECONDS); @@ -279,18 +257,15 @@ public class PlaybackServiceTaskManager { cancelChapterLoader(); } - Runnable chapterLoader = new Runnable() { - @Override - public void run() { - Log.d(TAG, "Chapter loader started"); - if (media.getChapters() == null) { - media.loadChapterMarks(); - if (!Thread.currentThread().isInterrupted() && media.getChapters() != null) { - callback.onChapterLoaded(media); - } + Runnable chapterLoader = () -> { + Log.d(TAG, "Chapter loader started"); + if (media.getChapters() == null) { + media.loadChapterMarks(); + if (!Thread.currentThread().isInterrupted() && media.getChapters() != null) { + callback.onChapterLoaded(media); } - Log.d(TAG, "Chapter loader stopped"); } + Log.d(TAG, "Chapter loader stopped"); }; chapterLoaderFuture = schedExecutor.submit(chapterLoader); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/APCleanupAlgorithm.java b/core/src/main/java/de/danoeh/antennapod/core/storage/APCleanupAlgorithm.java index 80703e22d..e94874453 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/APCleanupAlgorithm.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/APCleanupAlgorithm.java @@ -13,8 +13,6 @@ import java.util.concurrent.ExecutionException; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; -import de.danoeh.antennapod.core.preferences.UserPreferences; -import de.danoeh.antennapod.core.util.LongList; /** * Implementation of the EpisodeCleanupAlgorithm interface used by AntennaPod. diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/APDownloadAlgorithm.java b/core/src/main/java/de/danoeh/antennapod/core/storage/APDownloadAlgorithm.java index 26dc027bf..aa97b321a 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/APDownloadAlgorithm.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/APDownloadAlgorithm.java @@ -33,73 +33,70 @@ public class APDownloadAlgorithm implements AutomaticDownloadAlgorithm { */ @Override public Runnable autoDownloadUndownloadedItems(final Context context) { - return new Runnable() { - @Override - public void run() { - - // true if we should auto download based on network status - boolean networkShouldAutoDl = NetworkUtils.autodownloadNetworkAvailable() - && UserPreferences.isEnableAutodownload(); - - // true if we should auto download based on power status - boolean powerShouldAutoDl = PowerUtils.deviceCharging(context) - || UserPreferences.isEnableAutodownloadOnBattery(); - - // we should only auto download if both network AND power are happy - if (networkShouldAutoDl && powerShouldAutoDl) { - - Log.d(TAG, "Performing auto-dl of undownloaded episodes"); - - List<FeedItem> candidates; - final List<FeedItem> queue = DBReader.getQueue(); - final List<FeedItem> newItems = DBReader.getNewItemsList(); - candidates = new ArrayList<FeedItem>(queue.size() + newItems.size()); - candidates.addAll(queue); - for(FeedItem newItem : newItems) { - FeedPreferences feedPrefs = newItem.getFeed().getPreferences(); - FeedFilter feedFilter = feedPrefs.getFilter(); - if(candidates.contains(newItem) == false && feedFilter.shouldAutoDownload(newItem)) { - candidates.add(newItem); - } - } - - // filter items that are not auto downloadable - Iterator<FeedItem> it = candidates.iterator(); - while(it.hasNext()) { - FeedItem item = it.next(); - if(item.isAutoDownloadable() == false) { - it.remove(); - } + return () -> { + + // true if we should auto download based on network status + boolean networkShouldAutoDl = NetworkUtils.autodownloadNetworkAvailable() + && UserPreferences.isEnableAutodownload(); + + // true if we should auto download based on power status + boolean powerShouldAutoDl = PowerUtils.deviceCharging(context) + || UserPreferences.isEnableAutodownloadOnBattery(); + + // we should only auto download if both network AND power are happy + if (networkShouldAutoDl && powerShouldAutoDl) { + + Log.d(TAG, "Performing auto-dl of undownloaded episodes"); + + List<FeedItem> candidates; + final List<FeedItem> queue = DBReader.getQueue(); + final List<FeedItem> newItems = DBReader.getNewItemsList(); + candidates = new ArrayList<>(queue.size() + newItems.size()); + candidates.addAll(queue); + for(FeedItem newItem : newItems) { + FeedPreferences feedPrefs = newItem.getFeed().getPreferences(); + FeedFilter feedFilter = feedPrefs.getFilter(); + if(!candidates.contains(newItem) && feedFilter.shouldAutoDownload(newItem)) { + candidates.add(newItem); } + } - int autoDownloadableEpisodes = candidates.size(); - int downloadedEpisodes = DBReader.getNumberOfDownloadedEpisodes(); - int deletedEpisodes = UserPreferences.getEpisodeCleanupAlgorithm() - .makeRoomForEpisodes(context, autoDownloadableEpisodes); - boolean cacheIsUnlimited = UserPreferences.getEpisodeCacheSize() == UserPreferences - .getEpisodeCacheSizeUnlimited(); - int episodeCacheSize = UserPreferences.getEpisodeCacheSize(); - - int episodeSpaceLeft; - if (cacheIsUnlimited || - episodeCacheSize >= downloadedEpisodes + autoDownloadableEpisodes) { - episodeSpaceLeft = autoDownloadableEpisodes; - } else { - episodeSpaceLeft = episodeCacheSize - (downloadedEpisodes - deletedEpisodes); + // filter items that are not auto downloadable + Iterator<FeedItem> it = candidates.iterator(); + while(it.hasNext()) { + FeedItem item = it.next(); + if(!item.isAutoDownloadable()) { + it.remove(); } + } - FeedItem[] itemsToDownload = candidates.subList(0, episodeSpaceLeft) - .toArray(new FeedItem[episodeSpaceLeft]); + int autoDownloadableEpisodes = candidates.size(); + int downloadedEpisodes = DBReader.getNumberOfDownloadedEpisodes(); + int deletedEpisodes = UserPreferences.getEpisodeCleanupAlgorithm() + .makeRoomForEpisodes(context, autoDownloadableEpisodes); + boolean cacheIsUnlimited = UserPreferences.getEpisodeCacheSize() == UserPreferences + .getEpisodeCacheSizeUnlimited(); + int episodeCacheSize = UserPreferences.getEpisodeCacheSize(); + + int episodeSpaceLeft; + if (cacheIsUnlimited || + episodeCacheSize >= downloadedEpisodes + autoDownloadableEpisodes) { + episodeSpaceLeft = autoDownloadableEpisodes; + } else { + episodeSpaceLeft = episodeCacheSize - (downloadedEpisodes - deletedEpisodes); + } - Log.d(TAG, "Enqueueing " + itemsToDownload.length + " items for download"); + FeedItem[] itemsToDownload = candidates.subList(0, episodeSpaceLeft) + .toArray(new FeedItem[episodeSpaceLeft]); - try { - DBTasks.downloadFeedItems(false, context, itemsToDownload); - } catch (DownloadRequestException e) { - e.printStackTrace(); - } + Log.d(TAG, "Enqueueing " + itemsToDownload.length + " items for download"); + try { + DBTasks.downloadFeedItems(false, context, itemsToDownload); + } catch (DownloadRequestException e) { + e.printStackTrace(); } + } }; } diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/APQueueCleanupAlgorithm.java b/core/src/main/java/de/danoeh/antennapod/core/storage/APQueueCleanupAlgorithm.java index baa9a986e..04b200699 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/APQueueCleanupAlgorithm.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/APQueueCleanupAlgorithm.java @@ -5,15 +5,12 @@ import android.support.annotation.NonNull; import android.util.Log; import java.util.ArrayList; -import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutionException; import de.danoeh.antennapod.core.feed.FeedItem; -import de.danoeh.antennapod.core.feed.FeedMedia; -import de.danoeh.antennapod.core.util.LongList; /** * A cleanup algorithm that removes any item that isn't in the queue and isn't a favorite diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/AutomaticDownloadAlgorithm.java b/core/src/main/java/de/danoeh/antennapod/core/storage/AutomaticDownloadAlgorithm.java index 72c68ddb6..dbb77e19c 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/AutomaticDownloadAlgorithm.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/AutomaticDownloadAlgorithm.java @@ -14,5 +14,5 @@ public interface AutomaticDownloadAlgorithm { * @param context Used for accessing the DB. * @return A Runnable that will be submitted to an ExecutorService. */ - public Runnable autoDownloadUndownloadedItems(Context context); + Runnable autoDownloadUndownloadedItems(Context context); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/DBTasks.java b/core/src/main/java/de/danoeh/antennapod/core/storage/DBTasks.java index ed593bb82..47e2d8a26 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/DBTasks.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/DBTasks.java @@ -48,13 +48,10 @@ public final class DBTasks { private static ExecutorService autodownloadExec; static { - autodownloadExec = Executors.newSingleThreadExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setPriority(Thread.MIN_PRIORITY); - return t; - } + autodownloadExec = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r); + t.setPriority(Thread.MIN_PRIORITY); + return t; }); } @@ -85,9 +82,7 @@ public final class DBTasks { if (feedID != 0) { try { DBWriter.deleteFeed(context, feedID).get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } else { @@ -114,7 +109,7 @@ public final class DBTasks { boolean showPlayer, boolean startWhenPrepared, boolean shouldStream) { try { if (!shouldStream) { - if (media.fileExists() == false) { + if (!media.fileExists()) { throw new MediaFileNotFoundException( "No episode was found at " + media.getFile_url(), media); @@ -518,8 +513,8 @@ public final class DBTasks { */ public static synchronized Feed[] updateFeed(final Context context, final Feed... newFeeds) { - List<Feed> newFeedsList = new ArrayList<Feed>(); - List<Feed> updatedFeedsList = new ArrayList<Feed>(); + List<Feed> newFeedsList = new ArrayList<>(); + List<Feed> updatedFeedsList = new ArrayList<>(); Feed[] resultFeeds = new Feed[newFeeds.length]; PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); @@ -611,9 +606,7 @@ public final class DBTasks { try { DBWriter.addNewFeed(context, newFeedsList.toArray(new Feed[newFeedsList.size()])).get(); DBWriter.setCompleteFeed(updatedFeedsList.toArray(new Feed[updatedFeedsList.size()])).get(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } @@ -633,7 +626,7 @@ public final class DBTasks { */ public static FutureTask<List<FeedItem>> searchFeedItemTitle(final Context context, final long feedID, final String query) { - return new FutureTask<List<FeedItem>>(new QueryTask<List<FeedItem>>(context) { + return new FutureTask<>(new QueryTask<List<FeedItem>>(context) { @Override public void execute(PodDBAdapter adapter) { Cursor searchResult = adapter.searchItemTitles(feedID, @@ -657,7 +650,7 @@ public final class DBTasks { */ public static FutureTask<List<FeedItem>> searchFeedItemDescription(final Context context, final long feedID, final String query) { - return new FutureTask<List<FeedItem>>(new QueryTask<List<FeedItem>>(context) { + return new FutureTask<>(new QueryTask<List<FeedItem>>(context) { @Override public void execute(PodDBAdapter adapter) { Cursor searchResult = adapter.searchItemDescriptions(feedID, @@ -681,7 +674,7 @@ public final class DBTasks { */ public static FutureTask<List<FeedItem>> searchFeedItemContentEncoded(final Context context, final long feedID, final String query) { - return new FutureTask<List<FeedItem>>(new QueryTask<List<FeedItem>>(context) { + return new FutureTask<>(new QueryTask<List<FeedItem>>(context) { @Override public void execute(PodDBAdapter adapter) { Cursor searchResult = adapter.searchItemContentEncoded(feedID, @@ -704,7 +697,7 @@ public final class DBTasks { */ public static FutureTask<List<FeedItem>> searchFeedItemChapters(final Context context, final long feedID, final String query) { - return new FutureTask<List<FeedItem>>(new QueryTask<List<FeedItem>>(context) { + return new FutureTask<>(new QueryTask<List<FeedItem>>(context) { @Override public void execute(PodDBAdapter adapter) { Cursor searchResult = adapter.searchItemChapters(feedID, diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/DBWriter.java b/core/src/main/java/de/danoeh/antennapod/core/storage/DBWriter.java index e728abc3b..7dad9cb08 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/DBWriter.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/DBWriter.java @@ -14,7 +14,6 @@ import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; @@ -132,7 +131,7 @@ public class DBWriter { } } Log.d(TAG, "Deleting File. Result: " + result); - EventBus.getDefault().post(FeedItemEvent.deletedMedia(Arrays.asList(media.getItem()))); + EventBus.getDefault().post(FeedItemEvent.deletedMedia(Collections.singletonList(media.getItem()))); EventDistributor.getInstance().sendUnreadItemsUpdateBroadcast(); } }); @@ -372,7 +371,7 @@ public class DBWriter { if (queue != null) { boolean queueModified = false; LongList markAsUnplayedIds = new LongList(); - List<QueueEvent> events = new ArrayList<QueueEvent>(); + List<QueueEvent> events = new ArrayList<>(); for (int i = 0; i < itemIds.length; i++) { if (!itemListContains(queue, itemIds[i])) { final FeedItem item = DBReader.getFeedItem(itemIds[i]); @@ -545,9 +544,7 @@ public class DBWriter { */ public static Future<?> moveQueueItem(final int from, final int to, final boolean broadcastUpdate) { - return dbExec.submit(() -> { - moveQueueItemHelper(from, to, broadcastUpdate); - }); + return dbExec.submit(() -> moveQueueItemHelper(from, to, broadcastUpdate)); } /** diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/DownloadRequester.java b/core/src/main/java/de/danoeh/antennapod/core/storage/DownloadRequester.java index 22c9538ca..04afc504b 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/DownloadRequester.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/DownloadRequester.java @@ -51,7 +51,7 @@ public class DownloadRequester { private Map<String, DownloadRequest> downloads; private DownloadRequester() { - downloads = new ConcurrentHashMap<String, DownloadRequest>(); + downloads = new ConcurrentHashMap<>(); } public static synchronized DownloadRequester getInstance() { @@ -268,10 +268,7 @@ public class DownloadRequester { * Checks if feedfile is in the downloads list */ public synchronized boolean isDownloadingFile(FeedFile item) { - if (item.getDownload_url() != null) { - return downloads.containsKey(item.getDownload_url()); - } - return false; + return item.getDownload_url() != null && downloads.containsKey(item.getDownload_url()); } public synchronized DownloadRequest getDownload(String downloadUrl) { diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/FeedSearcher.java b/core/src/main/java/de/danoeh/antennapod/core/storage/FeedSearcher.java index 3a63685ba..d7c9e9108 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/FeedSearcher.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/FeedSearcher.java @@ -1,10 +1,6 @@ package de.danoeh.antennapod.core.storage; import android.content.Context; -import de.danoeh.antennapod.core.R; -import de.danoeh.antennapod.core.feed.FeedItem; -import de.danoeh.antennapod.core.feed.SearchResult; -import de.danoeh.antennapod.core.util.comparator.SearchResultValueComparator; import java.util.ArrayList; import java.util.Collections; @@ -12,6 +8,11 @@ import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; +import de.danoeh.antennapod.core.R; +import de.danoeh.antennapod.core.feed.FeedItem; +import de.danoeh.antennapod.core.feed.SearchResult; +import de.danoeh.antennapod.core.util.comparator.SearchResultValueComparator; + /** * Performs search on Feeds and FeedItems */ @@ -30,7 +31,7 @@ public class FeedSearcher { context.getString(R.string.found_in_chapters_label), context.getString(R.string.found_in_title_label)}; - List<SearchResult> result = new ArrayList<SearchResult>(); + List<SearchResult> result = new ArrayList<>(); FutureTask<List<FeedItem>>[] tasks = new FutureTask[4]; (tasks[0] = DBTasks.searchFeedItemContentEncoded(context, selectedFeed, query)).run(); @@ -46,9 +47,7 @@ public class FeedSearcher { } } - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } Collections.sort(result, new SearchResultValueComparator()); diff --git a/core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java b/core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java index 5b7f5f720..ffe5b2f24 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java +++ b/core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java @@ -425,7 +425,7 @@ public class PodDBAdapter { */ public long setImage(FeedImage image) { boolean startedTransaction = false; - if(false == db.inTransaction()) { + if(!db.inTransaction()) { db.beginTransaction(); startedTransaction = true; } @@ -972,9 +972,8 @@ public class PodDBAdapter { * @return The cursor of the query */ public final Cursor getAllFeedsCursor() { - Cursor c = db.query(TABLE_NAME_FEEDS, FEED_SEL_STD, null, null, null, null, + return db.query(TABLE_NAME_FEEDS, FEED_SEL_STD, null, null, null, null, KEY_TITLE + " COLLATE NOCASE ASC"); - return c; } public final Cursor getFeedCursorDownloadUrls() { @@ -992,22 +991,19 @@ public class PodDBAdapter { } public final Cursor getAllItemsOfFeedCursor(final long feedId) { - Cursor c = db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_FEED + return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_FEED + "=?", new String[]{String.valueOf(feedId)}, null, null, - null - ); - return c; + null); } /** * Return a cursor with the SEL_FI_EXTRA selection of a single feeditem. */ public final Cursor getExtraInformationOfItem(final FeedItem item) { - Cursor c = db + return db .query(TABLE_NAME_FEED_ITEMS, SEL_FI_EXTRA, KEY_ID + "=?", new String[]{String.valueOf(item.getId())}, null, null, null); - return c; } /** @@ -1017,10 +1013,9 @@ public class PodDBAdapter { * @return The cursor of the query */ public final Cursor getFeedMediaOfItemCursor(final FeedItem item) { - Cursor c = db.query(TABLE_NAME_FEED_MEDIA, null, KEY_ID + "=?", + return db.query(TABLE_NAME_FEED_MEDIA, null, KEY_ID + "=?", new String[]{String.valueOf(item.getMedia().getId())}, null, null, null); - return c; } /** @@ -1065,25 +1060,22 @@ public class PodDBAdapter { } public final Cursor getSimpleChaptersOfFeedItemCursor(final FeedItem item) { - Cursor c = db.query(TABLE_NAME_SIMPLECHAPTERS, null, KEY_FEEDITEM + return db.query(TABLE_NAME_SIMPLECHAPTERS, null, KEY_FEEDITEM + "=?", new String[]{String.valueOf(item.getId())}, null, null, null ); - return c; } public final Cursor getDownloadLog(final int feedFileType, final long feedFileId) { final String query = "SELECT * FROM " + TABLE_NAME_DOWNLOAD_LOG + " WHERE " + KEY_FEEDFILE + "=" + feedFileId + " AND " + KEY_FEEDFILETYPE + "=" + feedFileType + " ORDER BY " + KEY_ID + " DESC"; - Cursor c = db.rawQuery(query, null); - return c; + return db.rawQuery(query, null); } public final Cursor getDownloadLogCursor(final int limit) { - Cursor c = db.query(TABLE_NAME_DOWNLOAD_LOG, null, null, null, null, + return db.query(TABLE_NAME_DOWNLOAD_LOG, null, null, null, null, null, KEY_COMPLETION_DATE + " DESC LIMIT " + limit); - return c; } /** @@ -1099,13 +1091,11 @@ public class PodDBAdapter { TABLE_NAME_QUEUE + "." + KEY_FEEDITEM, TABLE_NAME_QUEUE + "." + KEY_ID }; String query = String.format("SELECT %s FROM %s INNER JOIN %s ON %s=%s ORDER BY %s", args); - Cursor c = db.rawQuery(query, null); - return c; + return db.rawQuery(query, null); } public Cursor getQueueIDCursor() { - Cursor c = db.query(TABLE_NAME_QUEUE, new String[]{KEY_FEEDITEM}, null, null, null, null, KEY_ID + " ASC", null); - return c; + return db.query(TABLE_NAME_QUEUE, new String[]{KEY_FEEDITEM}, null, null, null, null, KEY_ID + " ASC", null); } @@ -1117,8 +1107,7 @@ public class PodDBAdapter { TABLE_NAME_FAVORITES + "." + KEY_FEEDITEM, TABLE_NAME_FEED_ITEMS + "." + KEY_PUBDATE }; String query = String.format("SELECT %s FROM %s INNER JOIN %s ON %s=%s ORDER BY %s DESC", args); - Cursor c = db.rawQuery(query, null); - return c; + return db.rawQuery(query, null); } /** @@ -1126,9 +1115,8 @@ public class PodDBAdapter { * The returned cursor uses the FEEDITEM_SEL_FI_SMALL selection. */ public final Cursor getUnreadItemsCursor() { - Cursor c = db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_READ + return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_READ + "<" + FeedItem.PLAYED, null, null, null, KEY_PUBDATE + " DESC"); - return c; } /** @@ -1141,8 +1129,7 @@ public class PodDBAdapter { + " WHERE " + KEY_FEED + "=" + feedId + " AND " + KEY_READ + "=" + FeedItem.NEW + " ORDER BY " + KEY_PUBDATE + " DESC"; - Cursor c = db.rawQuery(query, null); - return c; + return db.rawQuery(query, null); } /** @@ -1160,13 +1147,11 @@ public class PodDBAdapter { KEY_PUBDATE + " DESC" }; final String query = String.format("SELECT %s FROM %s INNER JOIN %s ON %s WHERE %s ORDER BY %s", args); - Cursor c = db.rawQuery(query, null); - return c; + return db.rawQuery(query, null); } public final Cursor getRecentlyPublishedItemsCursor(int limit) { - Cursor c = db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, null, null, null, null, KEY_PUBDATE + " DESC LIMIT " + limit); - return c; + return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, null, null, null, null, KEY_PUBDATE + " DESC LIMIT " + limit); } public Cursor getDownloadedItemsCursor() { @@ -1175,8 +1160,7 @@ public class PodDBAdapter { + " INNER JOIN " + TABLE_NAME_FEED_MEDIA + " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_ID + "=" + TABLE_NAME_FEED_MEDIA + "." + KEY_FEEDITEM + " WHERE " + TABLE_NAME_FEED_MEDIA + "." + KEY_DOWNLOADED + ">0"; - Cursor c = db.rawQuery(query, null); - return c; + return db.rawQuery(query, null); } /** @@ -1192,10 +1176,9 @@ public class PodDBAdapter { throw new IllegalArgumentException("Limit must be >= 0"); } - Cursor c = db.query(TABLE_NAME_FEED_MEDIA, null, + return db.query(TABLE_NAME_FEED_MEDIA, null, KEY_PLAYBACK_COMPLETION_DATE + " > 0", null, null, null, String.format("%s DESC LIMIT %d", KEY_PLAYBACK_COMPLETION_DATE, limit)); - return c; } public final Cursor getSingleFeedMediaCursor(long id) { @@ -1244,18 +1227,17 @@ public class PodDBAdapter { if (size == 1) { return "(?)"; } - StringBuffer buffer = new StringBuffer("("); + StringBuilder builder = new StringBuilder("("); for (int i = 0; i < size - 1; i++) { - buffer.append("?,"); + builder.append("?,"); } - buffer.append("?)"); - return buffer.toString(); + builder.append("?)"); + return builder.toString(); } public final Cursor getFeedCursor(final long id) { - Cursor c = db.query(TABLE_NAME_FEEDS, FEED_SEL_STD, KEY_ID + "=" + id, null, + return db.query(TABLE_NAME_FEEDS, FEED_SEL_STD, KEY_ID + "=" + id, null, null, null, null); - return c; } public final Cursor getFeedItemCursor(final String id) { diff --git a/core/src/main/java/de/danoeh/antennapod/core/syndication/handler/HandlerState.java b/core/src/main/java/de/danoeh/antennapod/core/syndication/handler/HandlerState.java index 9280db8a3..66513a12e 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/syndication/handler/HandlerState.java +++ b/core/src/main/java/de/danoeh/antennapod/core/syndication/handler/HandlerState.java @@ -47,10 +47,10 @@ public class HandlerState { public HandlerState(Feed feed) { this.feed = feed; alternateUrls = new ArrayMap<>(); - items = new ArrayList<FeedItem>(); - tagstack = new Stack<SyndElement>(); + items = new ArrayList<>(); + tagstack = new Stack<>(); namespaces = new ArrayMap<>(); - defaultNamespaces = new Stack<Namespace>(); + defaultNamespaces = new Stack<>(); tempObjects = new ArrayMap<>(); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/syndication/handler/TypeGetter.java b/core/src/main/java/de/danoeh/antennapod/core/syndication/handler/TypeGetter.java index 4d56e1365..f84d6ee96 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/syndication/handler/TypeGetter.java +++ b/core/src/main/java/de/danoeh/antennapod/core/syndication/handler/TypeGetter.java @@ -41,27 +41,28 @@ public class TypeGetter { while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { String tag = xpp.getName(); - if (tag.equals(ATOM_ROOT)) { - feed.setType(Feed.TYPE_ATOM1); - Log.d(TAG, "Recognized type Atom"); - return Type.ATOM; - } else if (tag.equals(RSS_ROOT)) { - String strVersion = xpp.getAttributeValue(null, "version"); - if (strVersion != null) { - if (strVersion.equals("2.0")) { - feed.setType(Feed.TYPE_RSS2); - Log.d(TAG, "Recognized type RSS 2.0"); - return Type.RSS20; - } else if (strVersion.equals("0.91") - || strVersion.equals("0.92")) { - Log.d(TAG, "Recognized type RSS 0.91/0.92"); - return Type.RSS091; + switch (tag) { + case ATOM_ROOT: + feed.setType(Feed.TYPE_ATOM1); + Log.d(TAG, "Recognized type Atom"); + return Type.ATOM; + case RSS_ROOT: + String strVersion = xpp.getAttributeValue(null, "version"); + if (strVersion != null) { + if (strVersion.equals("2.0")) { + feed.setType(Feed.TYPE_RSS2); + Log.d(TAG, "Recognized type RSS 2.0"); + return Type.RSS20; + } else if (strVersion.equals("0.91") + || strVersion.equals("0.92")) { + Log.d(TAG, "Recognized type RSS 0.91/0.92"); + return Type.RSS091; + } } - } - throw new UnsupportedFeedtypeException(Type.INVALID); - } else { - Log.d(TAG, "Type is invalid"); - throw new UnsupportedFeedtypeException(Type.INVALID, tag); + throw new UnsupportedFeedtypeException(Type.INVALID); + default: + Log.d(TAG, "Type is invalid"); + throw new UnsupportedFeedtypeException(Type.INVALID, tag); } } else { eventType = xpp.next(); diff --git a/core/src/main/java/de/danoeh/antennapod/core/syndication/namespace/NSITunes.java b/core/src/main/java/de/danoeh/antennapod/core/syndication/namespace/NSITunes.java index dfd5cb74f..1c424c6b5 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/syndication/namespace/NSITunes.java +++ b/core/src/main/java/de/danoeh/antennapod/core/syndication/namespace/NSITunes.java @@ -61,26 +61,26 @@ public class NSITunes extends Namespace { state.getFeed().setAuthor(author); } } else if (DURATION.equals(localName)) { - String duration = state.getContentBuf().toString(); - if(TextUtils.isEmpty(duration)) { + String durationStr = state.getContentBuf().toString(); + if(TextUtils.isEmpty(durationStr)) { return; } - String[] parts = duration.trim().split(":"); + String[] parts = durationStr.trim().split(":"); try { int durationMs = 0; if (parts.length == 2) { durationMs += TimeUnit.MINUTES.toMillis(Long.parseLong(parts[0])) + - TimeUnit.SECONDS.toMillis(Long.parseLong(parts[1])); + TimeUnit.SECONDS.toMillis((long)Float.parseFloat(parts[1])); } else if (parts.length >= 3) { durationMs += TimeUnit.HOURS.toMillis(Long.parseLong(parts[0])) + TimeUnit.MINUTES.toMillis(Long.parseLong(parts[1])) + - TimeUnit.SECONDS.toMillis(Long.parseLong(parts[2])); + TimeUnit.SECONDS.toMillis((long)Float.parseFloat(parts[2])); } else { return; } state.getTempObjects().put(DURATION, durationMs); } catch (NumberFormatException e) { - Log.e(NSTAG, Log.getStackTraceString(e)); + Log.e(NSTAG, "Duration \"" + durationStr + "\" could not be parsed"); } } else if (SUBTITLE.equals(localName)) { String subtitle = state.getContentBuf().toString(); diff --git a/core/src/main/java/de/danoeh/antennapod/core/syndication/namespace/NSMedia.java b/core/src/main/java/de/danoeh/antennapod/core/syndication/namespace/NSMedia.java index 39f553818..7a8b2bc03 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/syndication/namespace/NSMedia.java +++ b/core/src/main/java/de/danoeh/antennapod/core/syndication/namespace/NSMedia.java @@ -40,10 +40,11 @@ public class NSMedia extends Namespace { if (state.getCurrentItem() != null && state.getCurrentItem().getMedia() == null && url != null && validType) { long size = 0; + String sizeStr = attributes.getValue(SIZE); try { - size = Long.parseLong(attributes.getValue(SIZE)); + size = Long.parseLong(sizeStr); } catch (NumberFormatException e) { - Log.e(TAG, "Length attribute could not be parsed."); + Log.e(TAG, "Size \"" + sizeStr + "\" could not be parsed."); } int durationMs = 0; @@ -53,7 +54,7 @@ public class NSMedia extends Namespace { long duration = Long.parseLong(durationStr); durationMs = (int) TimeUnit.MILLISECONDS.convert(duration, TimeUnit.SECONDS); } catch (NumberFormatException e) { - Log.e(TAG, "Duration attribute could not be parsed"); + Log.e(TAG, "Duration \"" + durationStr + "\" could not be parsed"); } } FeedMedia media = new FeedMedia(state.getCurrentItem(), url, size, type); diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/ChapterUtils.java b/core/src/main/java/de/danoeh/antennapod/core/util/ChapterUtils.java index 8dd9ffe4b..5169f7e76 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/ChapterUtils.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/ChapterUtils.java @@ -10,7 +10,6 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.List; @@ -63,11 +62,7 @@ public class ChapterUtils { } else { Log.i(TAG, "ChapterReader could not find any ID3 chapters"); } - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ID3ReaderException e) { + } catch (IOException | ID3ReaderException e) { e.printStackTrace(); } finally { if (in != null) { @@ -116,9 +111,7 @@ public class ChapterUtils { Log.i(TAG, "ChapterReader could not find any ID3 chapters"); } - } catch (IOException e) { - e.printStackTrace(); - } catch (ID3ReaderException e) { + } catch (IOException | ID3ReaderException e) { e.printStackTrace(); } finally { if (in != null) { @@ -144,8 +137,6 @@ public class ChapterUtils { if (input != null) { readOggChaptersFromInputStream(media, input); } - } catch (MalformedURLException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/DownloadError.java b/core/src/main/java/de/danoeh/antennapod/core/util/DownloadError.java index d3f6c6b79..4ad88743f 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/DownloadError.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/DownloadError.java @@ -25,7 +25,7 @@ public enum DownloadError { private final int code; private final int resId; - private DownloadError(int code, int resId) { + DownloadError(int code, int resId) { this.code = code; this.resId = resId; } diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/EpisodeFilter.java b/core/src/main/java/de/danoeh/antennapod/core/util/EpisodeFilter.java index 029e7fe84..89edd7dbe 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/EpisodeFilter.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/EpisodeFilter.java @@ -13,7 +13,7 @@ public class EpisodeFilter { /** Return a copy of the itemlist without items which have no media. */ public static ArrayList<FeedItem> getEpisodeList(List<FeedItem> items) { - ArrayList<FeedItem> episodes = new ArrayList<FeedItem>(items); + ArrayList<FeedItem> episodes = new ArrayList<>(items); for (FeedItem item : items) { if (item.getMedia() == null) { episodes.remove(item); diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/IntList.java b/core/src/main/java/de/danoeh/antennapod/core/util/IntList.java index 1cbe7fade..f48b9169b 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/IntList.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/IntList.java @@ -62,7 +62,7 @@ public final class IntList { @Override public String toString() { - StringBuffer sb = new StringBuffer(size * 5 + 10); + StringBuilder sb = new StringBuilder(size * 5 + 10); sb.append("IntList{"); for (int i = 0; i < size; i++) { if (i != 0) { diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/LongList.java b/core/src/main/java/de/danoeh/antennapod/core/util/LongList.java index 6ed8b820e..fdc244517 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/LongList.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/LongList.java @@ -73,7 +73,7 @@ public final class LongList { @Override public String toString() { - StringBuffer sb = new StringBuffer(size * 5 + 10); + StringBuilder sb = new StringBuilder(size * 5 + 10); sb.append("LongList{"); for (int i = 0; i < size; i++) { if (i != 0) { diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/NetworkUtils.java b/core/src/main/java/de/danoeh/antennapod/core/util/NetworkUtils.java index c2cd273b8..927639e69 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/NetworkUtils.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/NetworkUtils.java @@ -96,7 +96,7 @@ public class NetworkUtils { return Observable.create(new Observable.OnSubscribe<Long>() { @Override public void call(Subscriber<? super Long> subscriber) { - if (false == NetworkUtils.isDownloadAllowed()) { + if (!NetworkUtils.isDownloadAllowed()) { subscriber.onNext(0L); subscriber.onCompleted(); return; @@ -107,7 +107,7 @@ public class NetworkUtils { if (mediaFile.exists()) { size = mediaFile.length(); } - } else if (false == media.checkedOnSizeButUnknown()) { + } else if (!media.checkedOnSizeButUnknown()) { // only query the network if we haven't already checked String url = media.getDownload_url(); diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/QueueSorter.java b/core/src/main/java/de/danoeh/antennapod/core/util/QueueSorter.java index 71d6040ba..5dc194dbd 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/QueueSorter.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/QueueSorter.java @@ -2,12 +2,12 @@ package de.danoeh.antennapod.core.util; import android.content.Context; +import java.util.Comparator; + import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; import de.danoeh.antennapod.core.storage.DBWriter; -import java.util.Comparator; - /** * Provides method for sorting the queue according to rules. */ @@ -26,59 +26,39 @@ public class QueueSorter { switch (rule) { case ALPHA_ASC: - comparator = new Comparator<FeedItem>() { - public int compare(FeedItem f1, FeedItem f2) { - return f1.getTitle().compareTo(f2.getTitle()); - } - }; + comparator = (f1, f2) -> f1.getTitle().compareTo(f2.getTitle()); break; case ALPHA_DESC: - comparator = new Comparator<FeedItem>() { - public int compare(FeedItem f1, FeedItem f2) { - return f2.getTitle().compareTo(f1.getTitle()); - } - }; + comparator = (f1, f2) -> f2.getTitle().compareTo(f1.getTitle()); break; case DATE_ASC: - comparator = new Comparator<FeedItem>() { - public int compare(FeedItem f1, FeedItem f2) { - return f1.getPubDate().compareTo(f2.getPubDate()); - } - }; + comparator = (f1, f2) -> f1.getPubDate().compareTo(f2.getPubDate()); break; case DATE_DESC: - comparator = new Comparator<FeedItem>() { - public int compare(FeedItem f1, FeedItem f2) { - return f2.getPubDate().compareTo(f1.getPubDate()); - } - }; + comparator = (f1, f2) -> f2.getPubDate().compareTo(f1.getPubDate()); break; case DURATION_ASC: - comparator = new Comparator<FeedItem>() { - public int compare(FeedItem f1, FeedItem f2) { - FeedMedia f1Media = f1.getMedia(); - FeedMedia f2Media = f2.getMedia(); - int duration1 = f1Media != null ? f1Media.getDuration() : -1; - int duration2 = f2Media != null ? f2Media.getDuration() : -1; + comparator = (f1, f2) -> { + FeedMedia f1Media = f1.getMedia(); + FeedMedia f2Media = f2.getMedia(); + int duration1 = f1Media != null ? f1Media.getDuration() : -1; + int duration2 = f2Media != null ? f2Media.getDuration() : -1; - if (duration1 == -1 || duration2 == -1) - return duration2 - duration1; - else - return duration1 - duration2; - } + if (duration1 == -1 || duration2 == -1) + return duration2 - duration1; + else + return duration1 - duration2; }; break; case DURATION_DESC: - comparator = new Comparator<FeedItem>() { - public int compare(FeedItem f1, FeedItem f2) { + comparator = (f1, f2) -> { FeedMedia f1Media = f1.getMedia(); FeedMedia f2Media = f2.getMedia(); int duration1 = f1Media != null ? f1Media.getDuration() : -1; int duration2 = f2Media != null ? f2Media.getDuration() : -1; return -1 * (duration1 - duration2); - } - }; + }; default: } diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/ShownotesProvider.java b/core/src/main/java/de/danoeh/antennapod/core/util/ShownotesProvider.java index 7e7c6c08b..a4cd83f70 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/ShownotesProvider.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/ShownotesProvider.java @@ -11,6 +11,6 @@ public interface ShownotesProvider { * database, it should be done in a separate thread. After the shownotes * have been loaded, callback.onShownotesLoaded should be called. */ - public Callable<String> loadShownotes(); + Callable<String> loadShownotes(); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/URIUtil.java b/core/src/main/java/de/danoeh/antennapod/core/util/URIUtil.java index 092c06b4a..e093dc766 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/URIUtil.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/URIUtil.java @@ -1,13 +1,14 @@ package de.danoeh.antennapod.core.util; import android.util.Log; -import de.danoeh.antennapod.core.BuildConfig; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import de.danoeh.antennapod.core.BuildConfig; + /** * Utility methods for dealing with URL encoding. */ @@ -26,9 +27,7 @@ public class URIUtil { try { URL url = new URL(source); return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } catch (URISyntaxException e) { + } catch (MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException(e); } } diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/gui/MoreContentListFooterUtil.java b/core/src/main/java/de/danoeh/antennapod/core/util/gui/MoreContentListFooterUtil.java index d56871fd1..386f46724 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/gui/MoreContentListFooterUtil.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/gui/MoreContentListFooterUtil.java @@ -19,12 +19,9 @@ public class MoreContentListFooterUtil { public MoreContentListFooterUtil(View root) { this.root = root; - root.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (listener != null && !loading) { - listener.onClick(); - } + root.setOnClickListener(v -> { + if (listener != null && !loading) { + listener.onClick(); } }); } @@ -46,8 +43,8 @@ public class MoreContentListFooterUtil { listener = l; } - public static interface Listener { - public void onClick(); + public interface Listener { + void onClick(); } public View getRoot() { diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/id3reader/ChapterReader.java b/core/src/main/java/de/danoeh/antennapod/core/util/id3reader/ChapterReader.java index 9f3c4c6d5..1807421b0 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/id3reader/ChapterReader.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/id3reader/ChapterReader.java @@ -1,11 +1,6 @@ package de.danoeh.antennapod.core.util.id3reader; import android.util.Log; -import de.danoeh.antennapod.core.BuildConfig; -import de.danoeh.antennapod.core.feed.Chapter; -import de.danoeh.antennapod.core.feed.ID3Chapter; -import de.danoeh.antennapod.core.util.id3reader.model.FrameHeader; -import de.danoeh.antennapod.core.util.id3reader.model.TagHeader; import java.io.IOException; import java.io.InputStream; @@ -13,6 +8,12 @@ import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; +import de.danoeh.antennapod.core.BuildConfig; +import de.danoeh.antennapod.core.feed.Chapter; +import de.danoeh.antennapod.core.feed.ID3Chapter; +import de.danoeh.antennapod.core.util.id3reader.model.FrameHeader; +import de.danoeh.antennapod.core.util.id3reader.model.TagHeader; + public class ChapterReader extends ID3Reader { private static final String TAG = "ID3ChapterReader"; @@ -25,7 +26,7 @@ public class ChapterReader extends ID3Reader { @Override public int onStartTagHeader(TagHeader header) { - chapters = new ArrayList<Chapter>(); + chapters = new ArrayList<>(); System.out.println(header.toString()); return ID3Reader.ACTION_DONT_SKIP; } @@ -34,49 +35,53 @@ public class ChapterReader extends ID3Reader { public int onStartFrameHeader(FrameHeader header, InputStream input) throws IOException, ID3ReaderException { System.out.println(header.toString()); - if (header.getId().equals(FRAME_ID_CHAPTER)) { - if (currentChapter != null) { - if (!hasId3Chapter(currentChapter)) { - chapters.add(currentChapter); - if (BuildConfig.DEBUG) Log.d(TAG, "Found chapter: " + currentChapter); - currentChapter = null; + switch (header.getId()) { + case FRAME_ID_CHAPTER: + if (currentChapter != null) { + if (!hasId3Chapter(currentChapter)) { + chapters.add(currentChapter); + if (BuildConfig.DEBUG) Log.d(TAG, "Found chapter: " + currentChapter); + currentChapter = null; + } } - } - StringBuffer elementId = new StringBuffer(); - readISOString(elementId, input, Integer.MAX_VALUE); - char[] startTimeSource = readBytes(input, 4); - long startTime = ((int) startTimeSource[0] << 24) - | ((int) startTimeSource[1] << 16) - | ((int) startTimeSource[2] << 8) | startTimeSource[3]; - currentChapter = new ID3Chapter(elementId.toString(), startTime); - skipBytes(input, 12); - return ID3Reader.ACTION_DONT_SKIP; - } else if (header.getId().equals(FRAME_ID_TITLE)) { - if (currentChapter != null && currentChapter.getTitle() == null) { - StringBuffer title = new StringBuffer(); - readString(title, input, header.getSize()); - currentChapter - .setTitle(title.toString()); - if (BuildConfig.DEBUG) Log.d(TAG, "Found title: " + currentChapter.getTitle()); - + StringBuffer elementId = new StringBuffer(); + readISOString(elementId, input, Integer.MAX_VALUE); + char[] startTimeSource = readBytes(input, 4); + long startTime = ((int) startTimeSource[0] << 24) + | ((int) startTimeSource[1] << 16) + | ((int) startTimeSource[2] << 8) | startTimeSource[3]; + currentChapter = new ID3Chapter(elementId.toString(), startTime); + skipBytes(input, 12); return ID3Reader.ACTION_DONT_SKIP; - } - } else if (header.getId().equals(FRAME_ID_LINK)) { - if (currentChapter != null) { - // skip description - int descriptionLength = readString(null, input, header.getSize()); - StringBuffer link = new StringBuffer(); - readISOString(link, input, header.getSize() - descriptionLength); - String decodedLink = URLDecoder.decode(link.toString(), "UTF-8"); - - currentChapter.setLink(decodedLink); - - if (BuildConfig.DEBUG) Log.d(TAG, "Found link: " + currentChapter.getLink()); - return ID3Reader.ACTION_DONT_SKIP; - } - } else if (header.getId().equals("APIC")) { - Log.d(TAG, header.toString()); - } + case FRAME_ID_TITLE: + if (currentChapter != null && currentChapter.getTitle() == null) { + StringBuffer title = new StringBuffer(); + readString(title, input, header.getSize()); + currentChapter + .setTitle(title.toString()); + if (BuildConfig.DEBUG) Log.d(TAG, "Found title: " + currentChapter.getTitle()); + + return ID3Reader.ACTION_DONT_SKIP; + } + break; + case FRAME_ID_LINK: + if (currentChapter != null) { + // skip description + int descriptionLength = readString(null, input, header.getSize()); + StringBuffer link = new StringBuffer(); + readISOString(link, input, header.getSize() - descriptionLength); + String decodedLink = URLDecoder.decode(link.toString(), "UTF-8"); + + currentChapter.setLink(decodedLink); + + if (BuildConfig.DEBUG) Log.d(TAG, "Found link: " + currentChapter.getLink()); + return ID3Reader.ACTION_DONT_SKIP; + } + break; + case "APIC": + Log.d(TAG, header.toString()); + break; + } return super.onStartFrameHeader(header, input); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/playback/ExternalMedia.java b/core/src/main/java/de/danoeh/antennapod/core/util/playback/ExternalMedia.java index ec50dce7c..412a27b95 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/playback/ExternalMedia.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/playback/ExternalMedia.java @@ -6,13 +6,14 @@ import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; -import de.danoeh.antennapod.core.feed.Chapter; -import de.danoeh.antennapod.core.feed.MediaType; -import de.danoeh.antennapod.core.util.ChapterUtils; import java.util.List; import java.util.concurrent.Callable; +import de.danoeh.antennapod.core.feed.Chapter; +import de.danoeh.antennapod.core.feed.MediaType; +import de.danoeh.antennapod.core.util.ChapterUtils; + /** Represents a media file that is stored on the local storage device. */ public class ExternalMedia implements Playable { @@ -106,12 +107,7 @@ public class ExternalMedia implements Playable { @Override public Callable<String> loadShownotes() { - return new Callable<String>() { - @Override - public String call() throws Exception { - return ""; - } - }; + return () -> ""; } @Override diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/playback/Playable.java b/core/src/main/java/de/danoeh/antennapod/core/util/playback/Playable.java index 86ec4fbd0..6459d86ed 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/playback/Playable.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/playback/Playable.java @@ -26,7 +26,7 @@ public interface Playable extends Parcelable, * Implementations must NOT call commit() after they have written the values * to the preferences file. */ - public void writeToPreferences(SharedPreferences.Editor prefEditor); + void writeToPreferences(SharedPreferences.Editor prefEditor); /** * This method is called from a separate thread by the PlaybackService. @@ -34,88 +34,88 @@ public interface Playable extends Parcelable, * should execute as quickly as possible and NOT load chapter marks if no * local file is available. */ - public void loadMetadata() throws PlayableException; + void loadMetadata() throws PlayableException; /** * This method is called from a separate thread by the PlaybackService. * Playable objects should load their chapter marks in this method if no * local file was available when loadMetadata() was called. */ - public void loadChapterMarks(); + void loadChapterMarks(); /** * Returns the title of the episode that this playable represents */ - public String getEpisodeTitle(); + String getEpisodeTitle(); /** * Returns a list of chapter marks or null if this Playable has no chapters. */ - public List<Chapter> getChapters(); + List<Chapter> getChapters(); /** * Returns a link to a website that is meant to be shown in a browser */ - public String getWebsiteLink(); + String getWebsiteLink(); - public String getPaymentLink(); + String getPaymentLink(); /** * Returns the title of the feed this Playable belongs to. */ - public String getFeedTitle(); + String getFeedTitle(); /** * Returns a unique identifier, for example a file url or an ID from a * database. */ - public Object getIdentifier(); + Object getIdentifier(); /** * Return duration of object or 0 if duration is unknown. */ - public int getDuration(); + int getDuration(); /** * Return position of object or 0 if position is unknown. */ - public int getPosition(); + int getPosition(); /** * Returns last time (in ms) when this playable was played or 0 * if last played time is unknown. */ - public long getLastPlayedTime(); + long getLastPlayedTime(); /** * Returns the type of media. This method should return the correct value * BEFORE loadMetadata() is called. */ - public MediaType getMediaType(); + MediaType getMediaType(); /** * Returns an url to a local file that can be played or null if this file * does not exist. */ - public String getLocalMediaUrl(); + String getLocalMediaUrl(); /** * Returns an url to a file that can be streamed by the player or null if * this url is not known. */ - public String getStreamUrl(); + String getStreamUrl(); /** * Returns true if a local file that can be played is available. getFileUrl * MUST return a non-null string if this method returns true. */ - public boolean localFileAvailable(); + boolean localFileAvailable(); /** * Returns true if a streamable file is available. getStreamUrl MUST return * a non-null string if this method returns true. */ - public boolean streamAvailable(); + boolean streamAvailable(); /** * Saves the current position of this object. Implementations can use the @@ -126,40 +126,40 @@ public interface Playable extends Parcelable, * @param newPosition new playback position in ms * @param timestamp current time in ms */ - public void saveCurrentPosition(SharedPreferences pref, int newPosition, long timestamp); + void saveCurrentPosition(SharedPreferences pref, int newPosition, long timestamp); - public void setPosition(int newPosition); + void setPosition(int newPosition); - public void setDuration(int newDuration); + void setDuration(int newDuration); /** * @param lastPlayedTimestamp timestamp in ms */ - public void setLastPlayedTime(long lastPlayedTimestamp); + void setLastPlayedTime(long lastPlayedTimestamp); /** * Is called by the PlaybackService when playback starts. */ - public void onPlaybackStart(); + void onPlaybackStart(); /** * Is called by the PlaybackService when playback is completed. */ - public void onPlaybackCompleted(); + void onPlaybackCompleted(); /** * Returns an integer that must be unique among all Playable classes. The * return value is later used by PlayableUtils to determine the type of the * Playable object that is restored. */ - public int getPlayableType(); + int getPlayableType(); - public void setChapters(List<Chapter> chapters); + void setChapters(List<Chapter> chapters); /** * Provides utility methods for Playable objects. */ - public static class PlayableUtils { + class PlayableUtils { private static final String TAG = "PlayableUtils"; /** @@ -213,7 +213,7 @@ public interface Playable extends Parcelable, } } - public static class PlayableException extends Exception { + class PlayableException extends Exception { private static final long serialVersionUID = 1L; public PlayableException() { diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/playback/PlaybackController.java b/core/src/main/java/de/danoeh/antennapod/core/util/playback/PlaybackController.java index 1a011a90b..016ff9a85 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/playback/PlaybackController.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/playback/PlaybackController.java @@ -237,10 +237,9 @@ public abstract class PlaybackController { private void setupPositionObserver() { - if ((positionObserverFuture != null && positionObserverFuture - .isCancelled()) - || (positionObserverFuture != null && positionObserverFuture - .isDone()) || positionObserverFuture == null) { + if (positionObserverFuture == null || + positionObserverFuture.isCancelled() || + positionObserverFuture.isDone()) { Log.d(TAG, "Setting up position observer"); positionObserver = new MediaPositionObserver(); @@ -360,31 +359,31 @@ public abstract class PlaybackController { } }; - public void setupGUI() {}; + public void setupGUI() {} - public void onPositionObserverUpdate() {}; + public void onPositionObserverUpdate() {} - public void onPlaybackSpeedChange() {}; + public void onPlaybackSpeedChange() {} - public void onShutdownNotification() {}; + public void onShutdownNotification() {} /** * Called when the currently displayed information should be refreshed. */ - public void onReloadNotification(int code) {}; + public void onReloadNotification(int code) {} - public void onBufferStart() {}; + public void onBufferStart() {} - public void onBufferEnd() {}; + public void onBufferEnd() {} - public void onBufferUpdate(float progress) {}; + public void onBufferUpdate(float progress) {} - public void onSleepTimerUpdate() {}; + public void onSleepTimerUpdate() {} - public void handleError(int code) {}; + public void handleError(int code) {} - public void onPlaybackEnd() {}; + public void onPlaybackEnd() {} public void repeatHandleStatus() { if (status != null && playbackService != null) { @@ -484,17 +483,17 @@ public abstract class PlaybackController { public ImageButton getPlayButton() { return null; - }; + } - public void postStatusMsg(int msg) {}; + public void postStatusMsg(int msg) {} - public void clearStatusMsg() {}; + public void clearStatusMsg() {} public boolean loadMediaInfo() { return false; - }; + } - public void onAwaitingVideoSurface() {}; + public void onAwaitingVideoSurface() {} /** * Called when connection to playback service has been established or @@ -528,7 +527,7 @@ public abstract class PlaybackController { } } - public void onServiceQueried() {}; + public void onServiceQueried() {} /** * Should be used by classes which implement the OnSeekBarChanged interface. @@ -591,7 +590,7 @@ public abstract class PlaybackController { playbackService.setStartWhenPrepared(!playbackService .isStartWhenPrepared()); if (reinitOnPause - && playbackService.isStartWhenPrepared() == false) { + && !playbackService.isStartWhenPrepared()) { playbackService.reinit(); } break; @@ -677,12 +676,10 @@ public abstract class PlaybackController { } public boolean canSetPlaybackSpeed() { - if (org.antennapod.audio.MediaPlayer.isPrestoLibraryInstalled(activity.getApplicationContext()) + return org.antennapod.audio.MediaPlayer.isPrestoLibraryInstalled(activity.getApplicationContext()) || UserPreferences.useSonic() - || Build.VERSION.SDK_INT >= 23) { - return true; - } - return playbackService != null && playbackService.canSetSpeed(); + || Build.VERSION.SDK_INT >= 23 + || playbackService != null && playbackService.canSetSpeed(); } public void setPlaybackSpeed(float speed) { @@ -716,10 +713,7 @@ public abstract class PlaybackController { } public boolean isPlayingVideo() { - if (playbackService != null) { - return PlaybackService.getCurrentMediaType() == MediaType.VIDEO; - } - return false; + return playbackService != null && PlaybackService.getCurrentMediaType() == MediaType.VIDEO; } public Pair<Integer, Integer> getVideoSize() { @@ -751,9 +745,9 @@ public abstract class PlaybackController { public void reinitServiceIfPaused() { if (playbackService != null && playbackService.isStreaming() - && (playbackService.getStatus() == PlayerStatus.PAUSED || (playbackService - .getStatus() == PlayerStatus.PREPARING && playbackService - .isStartWhenPrepared() == false))) { + && (playbackService.getStatus() == PlayerStatus.PAUSED || + (playbackService.getStatus() == PlayerStatus.PREPARING && + !playbackService.isStartWhenPrepared()))) { playbackService.reinit(); } } @@ -768,13 +762,7 @@ public abstract class PlaybackController { @Override public void run() { if (playbackService != null && playbackService.getStatus() == PlayerStatus.PLAYING) { - activity.runOnUiThread(new Runnable() { - - @Override - public void run() { - onPositionObserverUpdate(); - } - }); + activity.runOnUiThread(PlaybackController.this::onPositionObserverUpdate); } } } diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/playback/Timeline.java b/core/src/main/java/de/danoeh/antennapod/core/util/playback/Timeline.java index 8d9151396..efdf46a97 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/playback/Timeline.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/playback/Timeline.java @@ -68,7 +68,7 @@ public class Timeline { private static final Pattern TIMECODE_LINK_REGEX = Pattern.compile("antennapod://timecode/((\\d+))"); private static final String TIMECODE_LINK = "<a class=\"timecode\" href=\"antennapod://timecode/%d\">%s</a>"; private static final Pattern TIMECODE_REGEX = Pattern.compile("\\b(?:(?:(([0-9][0-9])):))?(([0-9][0-9])):(([0-9][0-9]))\\b"); - private static final Pattern LINE_BREAK_REGEX = Pattern.compile("<br *\\/?>"); + private static final Pattern LINE_BREAK_REGEX = Pattern.compile("<br */?>"); /** diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/vorbiscommentreader/VorbisCommentChapterReader.java b/core/src/main/java/de/danoeh/antennapod/core/util/vorbiscommentreader/VorbisCommentChapterReader.java index c4961a3ab..6243da5bc 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/vorbiscommentreader/VorbisCommentChapterReader.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/vorbiscommentreader/VorbisCommentChapterReader.java @@ -9,7 +9,7 @@ import java.util.ArrayList; import java.util.List; public class VorbisCommentChapterReader extends VorbisCommentReader { - private static final String TAG = "VorbisCommentChapterReader"; + private static final String TAG = "VorbisCommentChptrReadr"; private static final String CHAPTER_KEY = "chapter\\d\\d\\d.*"; private static final String CHAPTER_ATTRIBUTE_TITLE = "name"; @@ -27,7 +27,7 @@ public class VorbisCommentChapterReader extends VorbisCommentReader { @Override public void onVorbisCommentHeaderFound(VorbisCommentHeader header) { - chapters = new ArrayList<Chapter>(); + chapters = new ArrayList<>(); System.out.println(header.toString()); } diff --git a/core/src/main/java/de/danoeh/antennapod/core/util/vorbiscommentreader/VorbisCommentReader.java b/core/src/main/java/de/danoeh/antennapod/core/util/vorbiscommentreader/VorbisCommentReader.java index 9639b9c42..49ea18721 100644 --- a/core/src/main/java/de/danoeh/antennapod/core/util/vorbiscommentreader/VorbisCommentReader.java +++ b/core/src/main/java/de/danoeh/antennapod/core/util/vorbiscommentreader/VorbisCommentReader.java @@ -180,13 +180,13 @@ public abstract class VorbisCommentReader { private String readContentVectorKey(InputStream input, long vectorLength) throws IOException { - StringBuffer buffer = new StringBuffer(); + StringBuilder builder = new StringBuilder(); for (int i = 0; i < vectorLength; i++) { char c = (char) input.read(); if (c == '=') { - return buffer.toString(); + return builder.toString(); } else { - buffer.append(c); + builder.append(c); } } return null; // no key found |