Merge pull request #1805 from domingos86/typos

code cleanup (perhaps to an extreme level)
This commit is contained in:
Martin Fietz 2016-03-22 20:16:42 +01:00
commit c2a1644d07
121 changed files with 810 additions and 1306 deletions

View File

@ -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"

View File

@ -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("%", "&#37;");
webViewData =

View File

@ -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 -> {

View File

@ -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);
}
};
}

View File

@ -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);
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();
if (sendToDownloadRequester) {
if (BuildConfig.DEBUG) Log.d(TAG, "Sending request to DownloadRequester");
DownloadRequester.getInstance().download(DownloadAuthenticationActivity.this, request);
}
finish();
});
}

View File

@ -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();

View File

@ -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() {

View File

@ -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 -> {

View File

@ -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)));
}
}

View File

@ -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";

View File

@ -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";

View File

@ -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;

View File

@ -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);

View File

@ -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);

View File

@ -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);
});
}

View File

@ -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);
}

View File

@ -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)

View File

@ -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)

View File

@ -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]));

View File

@ -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;

View File

@ -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;

View File

@ -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);
}
}

View File

@ -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);
}

View File

@ -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)

View File

@ -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);

View File

@ -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;

View File

@ -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());

View File

@ -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 {

View File

@ -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";

View File

@ -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;

View File

@ -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();
});
}

View File

@ -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);
}

View File

@ -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());

View File

@ -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;

View File

@ -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
}

View File

@ -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;
}
}

View File

@ -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();

View File

@ -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++;
}
}

View File

@ -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;

View File

@ -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();
}
@ -132,12 +127,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();
@ -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();
}
}

View File

@ -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 -> {

View File

@ -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 -> {

View File

@ -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;

View File

@ -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

View File

@ -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 -> {

View File

@ -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 -> {

View File

@ -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 -> {

View File

@ -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 -> {

View File

@ -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 -> {

View File

@ -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;

View File

@ -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();
}
}
}

View File

@ -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();

View File

@ -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()) {

View File

@ -5,5 +5,5 @@ package de.danoeh.antennapod.menuhandler;
*/
public interface NavDrawerActivity {
public boolean isDrawerOpen();
boolean isDrawerOpen();
}

View File

@ -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);
}
}
}

View File

@ -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);
}

View File

@ -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>

View File

@ -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>

View File

@ -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);
}

View File

@ -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();
}

View File

@ -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();
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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;

View File

@ -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();
}
}

View File

@ -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();
}

View File

@ -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();
}

View File

@ -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);
}

View File

@ -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();
}
}

View File

@ -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)

View File

@ -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() {

View File

@ -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;
}
}

View File

@ -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

View File

@ -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;
};
}

View File

@ -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 (item.getContentEncoded() != null) ? item.getContentEncoded() : item.getDescription();
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();
};
}

View File

@ -68,7 +68,7 @@ public class FeedPreferences {
/**
* @return the filter for this feed
*/
public FeedFilter getFilter() {
public @NonNull FeedFilter getFilter() {
return filter;
}

View File

@ -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)) {

View File

@ -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");

View File

@ -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;
}
}

View File

@ -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;

View File

@ -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));

View File

@ -32,7 +32,7 @@ public class MenuItemUtils {
}
}
public static interface UpdateRefreshMenuItemChecker {
public boolean isRefreshing();
public interface UpdateRefreshMenuItemChecker {
boolean isRefreshing();
}
}

View File

@ -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();

View File

@ -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);

View File

@ -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() {

View File

@ -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();
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);
}
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));
dbUpdateFuture = dbService.submit(() -> {
Feed[] savedFeeds = DBTasks.updateFeed(DownloadService.this, getFeeds(results));
for (int i = 0; i < savedFeeds.length; i++) {
Feed savedFeed = savedFeeds[i];
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);
}
// 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);
}
});
}

View File

@ -6,5 +6,5 @@ package de.danoeh.antennapod.core.service.download;
*/
public interface DownloaderCallback {
public void onDownloadCompleted(Downloader downloader);
void onDownloadCompleted(Downloader downloader);
}

View File

@ -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 {

View File

@ -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;

View File

@ -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(

View File

@ -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();
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);
}
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();
}
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();
});
}
@ -657,7 +626,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);
}
@ -670,12 +639,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));
}
/**
@ -761,28 +725,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();
});
}
@ -803,7 +761,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();
@ -1009,20 +967,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();
});
}
@ -1097,100 +1052,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) {

View File

@ -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);
}

View File

@ -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.

View File

@ -33,73 +33,70 @@ public class APDownloadAlgorithm implements AutomaticDownloadAlgorithm {
*/
@Override
public Runnable autoDownloadUndownloadedItems(final Context context) {
return new Runnable() {
@Override
public void run() {
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 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();
// 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) {
// we should only auto download if both network AND power are happy
if (networkShouldAutoDl && powerShouldAutoDl) {
Log.d(TAG, "Performing auto-dl of undownloaded episodes");
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);
}
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);
}
// 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();
}
}
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);
}
FeedItem[] itemsToDownload = candidates.subList(0, episodeSpaceLeft)
.toArray(new FeedItem[episodeSpaceLeft]);
Log.d(TAG, "Enqueueing " + itemsToDownload.length + " items for download");
try {
DBTasks.downloadFeedItems(false, context, itemsToDownload);
} catch (DownloadRequestException e) {
e.printStackTrace();
}
}
// filter items that are not auto downloadable
Iterator<FeedItem> it = candidates.iterator();
while(it.hasNext()) {
FeedItem item = it.next();
if(!item.isAutoDownloadable()) {
it.remove();
}
}
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);
}
FeedItem[] itemsToDownload = candidates.subList(0, episodeSpaceLeft)
.toArray(new FeedItem[episodeSpaceLeft]);
Log.d(TAG, "Enqueueing " + itemsToDownload.length + " items for download");
try {
DBTasks.downloadFeedItems(false, context, itemsToDownload);
} catch (DownloadRequestException e) {
e.printStackTrace();
}
}
};
}

View File

@ -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

View File

@ -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);
}

View File

@ -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,

View File

@ -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));
}
/**

View File

@ -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) {

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