diff options
40 files changed, 627 insertions, 863 deletions
diff --git a/app/src/main/java/github/daneren2005/dsub/activity/EditPlayActionActivity.java b/app/src/main/java/github/daneren2005/dsub/activity/EditPlayActionActivity.java index bc56eeb7..9423eb38 100644 --- a/app/src/main/java/github/daneren2005/dsub/activity/EditPlayActionActivity.java +++ b/app/src/main/java/github/daneren2005/dsub/activity/EditPlayActionActivity.java @@ -18,7 +18,6 @@ package github.daneren2005.dsub.activity; import android.app.Activity; import androidx.appcompat.app.AlertDialog; -import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.drawerlayout.widget.DrawerLayout; @@ -29,7 +28,6 @@ import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; -import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Spinner; @@ -66,33 +64,20 @@ public class EditPlayActionActivity extends SubsonicActivity { doNothing = context.getResources().getString(R.string.tasker_edit_do_nothing); shuffleCheckbox = (CheckBox) findViewById(R.id.edit_shuffle_checkbox); - shuffleCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton view, boolean isChecked) { - startYearCheckbox.setEnabled(isChecked); - endYearCheckbox.setEnabled(isChecked); - genreButton.setEnabled(isChecked); - } + shuffleCheckbox.setOnCheckedChangeListener((view, isChecked) -> { + startYearCheckbox.setEnabled(isChecked); + endYearCheckbox.setEnabled(isChecked); + genreButton.setEnabled(isChecked); }); startYearCheckbox = (CheckBox) findViewById(R.id.edit_start_year_checkbox); startYearBox = (EditText) findViewById(R.id.edit_start_year); // Disable/enable number box if checked - startYearCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton view, boolean isChecked) { - startYearBox.setEnabled(isChecked); - } - }); + startYearCheckbox.setOnCheckedChangeListener((view, isChecked) -> startYearBox.setEnabled(isChecked)); endYearCheckbox = (CheckBox) findViewById(R.id.edit_end_year_checkbox); endYearBox = (EditText) findViewById(R.id.edit_end_year); - endYearCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton view, boolean isChecked) { - endYearBox.setEnabled(isChecked); - } - }); + endYearCheckbox.setOnCheckedChangeListener((view, isChecked) -> endYearBox.setEnabled(isChecked)); genreButton = (Button) findViewById(R.id.edit_genre_spinner); genreButton.setOnClickListener(new View.OnClickListener() { @@ -106,7 +91,7 @@ public class EditPlayActionActivity extends SubsonicActivity { @Override protected void done(final List<Genre> genres) { - List<String> names = new ArrayList<String>(); + List<String> names = new ArrayList<>(); String blank = context.getResources().getString(R.string.select_genre_blank); names.add(doNothing); names.add(blank); @@ -117,13 +102,11 @@ public class EditPlayActionActivity extends SubsonicActivity { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.shuffle_pick_genre) - .setItems(names.toArray(new CharSequence[names.size()]), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - if(which == 1) { - genreButton.setText(""); - } else { - genreButton.setText(finalNames.get(which)); - } + .setItems(names.toArray(new CharSequence[0]), (dialog, which) -> { + if(which == 1) { + genreButton.setText(""); + } else { + genreButton.setText(finalNames.get(which)); } }); AlertDialog dialog = builder.create(); diff --git a/app/src/main/java/github/daneren2005/dsub/activity/QueryReceiverActivity.java b/app/src/main/java/github/daneren2005/dsub/activity/QueryReceiverActivity.java index 68f46599..eb149b58 100644 --- a/app/src/main/java/github/daneren2005/dsub/activity/QueryReceiverActivity.java +++ b/app/src/main/java/github/daneren2005/dsub/activity/QueryReceiverActivity.java @@ -23,13 +23,9 @@ import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; -import android.provider.SearchRecentSuggestions; -import android.util.Log; -import github.daneren2005.dsub.fragments.SubsonicFragment; import github.daneren2005.dsub.util.Constants; import github.daneren2005.dsub.util.Util; -import github.daneren2005.dsub.provider.DSubSearchProvider; /** * Receives search queries and forwards to the SearchFragment. @@ -38,8 +34,6 @@ import github.daneren2005.dsub.provider.DSubSearchProvider; */ public class QueryReceiverActivity extends Activity { - private static final String TAG = QueryReceiverActivity.class.getSimpleName(); - @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); diff --git a/app/src/main/java/github/daneren2005/dsub/activity/SettingsActivity.java b/app/src/main/java/github/daneren2005/dsub/activity/SettingsActivity.java index fb5a0169..520ddf10 100644 --- a/app/src/main/java/github/daneren2005/dsub/activity/SettingsActivity.java +++ b/app/src/main/java/github/daneren2005/dsub/activity/SettingsActivity.java @@ -18,8 +18,6 @@ */ package github.daneren2005.dsub.activity; -import android.annotation.TargetApi; -import android.os.Build; import android.os.Bundle; import androidx.appcompat.widget.Toolbar; @@ -29,10 +27,7 @@ import github.daneren2005.dsub.fragments.SettingsFragment; import github.daneren2005.dsub.util.Constants; public class SettingsActivity extends SubsonicActivity { - private static final String TAG = SettingsActivity.class.getSimpleName(); - private PreferenceCompatFragment fragment; - @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -40,7 +35,7 @@ public class SettingsActivity extends SubsonicActivity { setContentView(R.layout.settings_activity); if (savedInstanceState == null) { - fragment = new SettingsFragment(); + PreferenceCompatFragment fragment = new SettingsFragment(); Bundle args = new Bundle(); args.putInt(Constants.INTENT_EXTRA_FRAGMENT_TYPE, R.xml.settings); diff --git a/app/src/main/java/github/daneren2005/dsub/activity/SubsonicActivity.java b/app/src/main/java/github/daneren2005/dsub/activity/SubsonicActivity.java index 167f3dd7..1063c72e 100644 --- a/app/src/main/java/github/daneren2005/dsub/activity/SubsonicActivity.java +++ b/app/src/main/java/github/daneren2005/dsub/activity/SubsonicActivity.java @@ -19,20 +19,21 @@ package github.daneren2005.dsub.activity; import android.Manifest; -import android.app.UiModeManager; +import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; -import android.content.res.Configuration; import android.media.AudioManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import com.google.android.material.navigation.NavigationView; + +import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.ActionBarDrawerToggle; @@ -49,10 +50,8 @@ import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; -import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; -import android.view.Window; import android.view.WindowManager; import android.view.animation.AnimationUtils; import android.widget.AdapterView; @@ -67,6 +66,7 @@ import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import github.daneren2005.dsub.R; import github.daneren2005.dsub.domain.ServerInfo; @@ -103,7 +103,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte private boolean drawerIdle = true; private boolean destroyed = false; private boolean finished = false; - protected List<SubsonicFragment> backStack = new ArrayList<SubsonicFragment>(); + protected List<SubsonicFragment> backStack = new ArrayList<>(); protected SubsonicFragment currentFragment; protected View primaryContainer; protected View secondaryContainer; @@ -111,7 +111,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte protected boolean touchscreen = true; protected Handler handler = new Handler(); Spinner actionBarSpinner; - ArrayAdapter<CharSequence> spinnerAdapter; + ArrayAdapter<String> spinnerAdapter; ViewGroup rootView; DrawerLayout drawer; ActionBarDrawerToggle drawerToggle; @@ -127,15 +127,11 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte SharedPreferences.OnSharedPreferenceChangeListener preferencesListener; static { - AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO); + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); } @Override protected void onCreate(Bundle bundle) { - UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE); - if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) { - // tv = true; - } PackageManager pm = getPackageManager(); if(!pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)) { touchscreen = false; @@ -153,30 +149,27 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte } if(preferencesListener == null) { - preferencesListener = new SharedPreferences.OnSharedPreferenceChangeListener() { - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - // When changing drawer settings change visibility - switch(key) { - case Constants.PREFERENCES_KEY_PODCASTS_ENABLED: - setDrawerItemVisible(R.id.drawer_podcasts, false); - break; - case Constants.PREFERENCES_KEY_BOOKMARKS_ENABLED: - setDrawerItemVisible(R.id.drawer_bookmarks, false); - break; - case Constants.PREFERENCES_KEY_INTERNET_RADIO_ENABLED: - setDrawerItemVisible(R.id.drawer_internet_radio_stations, false); - break; - case Constants.PREFERENCES_KEY_SHARED_ENABLED: - setDrawerItemVisible(R.id.drawer_shares, false); - break; - case Constants.PREFERENCES_KEY_CHAT_ENABLED: - setDrawerItemVisible(R.id.drawer_chat, false); - break; - case Constants.PREFERENCES_KEY_ADMIN_ENABLED: - setDrawerItemVisible(R.id.drawer_admin, false); - break; - } + preferencesListener = (sharedPreferences, key) -> { + // When changing drawer settings change visibility + switch(key) { + case Constants.PREFERENCES_KEY_PODCASTS_ENABLED: + setDrawerItemVisible(R.id.drawer_podcasts, false); + break; + case Constants.PREFERENCES_KEY_BOOKMARKS_ENABLED: + setDrawerItemVisible(R.id.drawer_bookmarks, false); + break; + case Constants.PREFERENCES_KEY_INTERNET_RADIO_ENABLED: + setDrawerItemVisible(R.id.drawer_internet_radio_stations, false); + break; + case Constants.PREFERENCES_KEY_SHARED_ENABLED: + setDrawerItemVisible(R.id.drawer_shares, false); + break; + case Constants.PREFERENCES_KEY_CHAT_ENABLED: + setDrawerItemVisible(R.id.drawer_chat, false); + break; + case Constants.PREFERENCES_KEY_ADMIN_ENABLED: + setDrawerItemVisible(R.id.drawer_admin, false); + break; } }; Util.getPreferences(this).registerOnSharedPreferenceChangeListener(preferencesListener); @@ -199,22 +192,19 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte } @Override - public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: { // If request is cancelled, the result arrays are empty. - if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - - } else { + if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { Util.toast(this, R.string.permission_external_storage_failed); finish(); } } case PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. - if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - - } else { + if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { Util.toast(this, R.string.permission_location_failed); } } @@ -228,7 +218,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte if(spinnerAdapter == null) { createCustomActionBarView(); } - getSupportActionBar().setDisplayHomeAsUpEnabled(true); + Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); // Sync the toggle state after onRestoreInstanceState has occurred. @@ -245,15 +235,17 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte protected void createCustomActionBarView() { actionBarSpinner = (Spinner) getLayoutInflater().inflate(R.layout.actionbar_spinner, null); - if((this instanceof SubsonicFragmentActivity || this instanceof SettingsActivity) && (Util.getPreferences(this).getBoolean(Constants.PREFERENCES_KEY_COLOR_ACTION_BAR, true) || ThemeUtil.getThemeRes(this) != R.style.Theme_DSub_Light_No_Color)) { - actionBarSpinner.setBackgroundDrawable(DrawableTint.getTintedDrawableFromColor(this, R.drawable.abc_spinner_mtrl_am_alpha, android.R.color.white)); + if((this instanceof SubsonicFragmentActivity || this instanceof SettingsActivity) + && (Util.getPreferences(this).getBoolean(Constants.PREFERENCES_KEY_COLOR_ACTION_BAR, true) + || ThemeUtil.getThemeRes(this) != R.style.Theme_DSub_Light_No_Color)) { + actionBarSpinner.setBackground(DrawableTint.getTintedDrawableFromColor(this, R.drawable.abc_spinner_mtrl_am_alpha, android.R.color.white)); } - spinnerAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item); + spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); actionBarSpinner.setOnItemSelectedListener(this); actionBarSpinner.setAdapter(spinnerAdapter); - getSupportActionBar().setCustomView(actionBarSpinner); + Objects.requireNonNull(getSupportActionBar()).setCustomView(actionBarSpinner); } @Override @@ -303,6 +295,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte Util.disablePendingTransition(this); } + @SuppressLint("ClickableViewAccessibility") @Override public void setContentView(int viewId) { if(isTv()) { @@ -320,88 +313,79 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte } drawerList = (NavigationView) findViewById(R.id.left_drawer); - drawerList.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { - @Override - public boolean onNavigationItemSelected(final MenuItem menuItem) { - if(showingTabs) { - // Settings are on a different selectable track - if (menuItem.getItemId() != R.id.drawer_settings && menuItem.getItemId() != R.id.drawer_admin && menuItem.getItemId() != R.id.drawer_offline) { + drawerList.setNavigationItemSelectedListener(menuItem -> { + if(showingTabs) { + // Settings are on a different selectable track + if (menuItem.getItemId() != R.id.drawer_settings && menuItem.getItemId() != R.id.drawer_admin && menuItem.getItemId() != R.id.drawer_offline) { + menuItem.setChecked(true); + lastSelectedPosition = menuItem.getItemId(); + } + + int id = menuItem.getItemId(); + if (id == R.id.drawer_home) { + drawerItemSelected("Home"); + return true; + } else if (id == R.id.drawer_library) { + drawerItemSelected("Artist"); + return true; + } else if (id == R.id.drawer_playlists) { + drawerItemSelected("Playlist"); + return true; + } else if (id == R.id.drawer_podcasts) { + drawerItemSelected("Podcast"); + return true; + } else if (id == R.id.drawer_bookmarks) { + drawerItemSelected("Bookmark"); + return true; + } else if (id == R.id.drawer_internet_radio_stations) { + drawerItemSelected("Internet Radio"); + return true; + } else if (id == R.id.drawer_shares) { + drawerItemSelected("Share"); + return true; + } else if (id == R.id.drawer_chat) { + drawerItemSelected("Chat"); + return true; + } else if (id == R.id.drawer_admin) { + if (UserUtil.isCurrentAdmin()) { + UserUtil.confirmCredentials(SubsonicActivity.this, () -> { + drawerItemSelected("Admin"); + menuItem.setChecked(true); + lastSelectedPosition = menuItem.getItemId(); + }); + } else { + drawerItemSelected("Admin"); menuItem.setChecked(true); lastSelectedPosition = menuItem.getItemId(); } - - switch (menuItem.getItemId()) { - case R.id.drawer_home: - drawerItemSelected("Home"); - return true; - case R.id.drawer_library: - drawerItemSelected("Artist"); - return true; - case R.id.drawer_playlists: - drawerItemSelected("Playlist"); - return true; - case R.id.drawer_podcasts: - drawerItemSelected("Podcast"); - return true; - case R.id.drawer_bookmarks: - drawerItemSelected("Bookmark"); - return true; - case R.id.drawer_internet_radio_stations: - drawerItemSelected("Internet Radio"); - return true; - case R.id.drawer_shares: - drawerItemSelected("Share"); - return true; - case R.id.drawer_chat: - drawerItemSelected("Chat"); - return true; - case R.id.drawer_admin: - if (UserUtil.isCurrentAdmin()) { - UserUtil.confirmCredentials(SubsonicActivity.this, new Runnable() { - @Override - public void run() { - drawerItemSelected("Admin"); - menuItem.setChecked(true); - lastSelectedPosition = menuItem.getItemId(); - } - }); - } else { - drawerItemSelected("Admin"); - menuItem.setChecked(true); - lastSelectedPosition = menuItem.getItemId(); - } - return true; - case R.id.drawer_downloading: - drawerItemSelected("Download"); - return true; - case R.id.drawer_offline: - toggleOffline(); - return true; - case R.id.drawer_settings: - startActivity(new Intent(SubsonicActivity.this, SettingsActivity.class)); - drawer.closeDrawers(); - return true; - } - } else { - int activeServer = menuItem.getItemId() - MENU_ITEM_SERVER_BASE; - SubsonicActivity.this.setActiveServer(activeServer); - populateTabs(); return true; + } else if (id == R.id.drawer_downloading) { + drawerItemSelected("Download"); + return true; + } else if (id == R.id.drawer_offline) { + toggleOffline(); + return true; + } else if (id == R.id.drawer_settings) { + startActivity(new Intent(SubsonicActivity.this, SettingsActivity.class)); + drawer.closeDrawers(); + return true; } - - return false; + } else { + int activeServer = menuItem.getItemId() - MENU_ITEM_SERVER_BASE; + SubsonicActivity.this.setActiveServer(activeServer); + populateTabs(); + return true; } + + return false; }); drawerHeader = drawerList.inflateHeaderView(R.layout.drawer_header); - drawerHeader.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if(showingTabs) { - populateServers(); - } else { - populateTabs(); - } + drawerHeader.setOnClickListener(v -> { + if(showingTabs) { + populateServers(); + } else { + populateTabs(); } }); @@ -448,16 +432,14 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte drawerIdle = false; } }; - drawer.setDrawerListener(drawerToggle); + drawer.addDrawerListener(drawerToggle); drawerToggle.setDrawerIndicatorEnabled(true); - drawer.setOnTouchListener(new View.OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - if (drawerIdle && currentFragment != null && currentFragment.getGestureDetector() != null) { - return currentFragment.getGestureDetector().onTouchEvent(event); - } else { - return false; - } + drawer.setOnTouchListener((v, event) -> { + if (drawerIdle && currentFragment != null && currentFragment.getGestureDetector() != null) { + return currentFragment.getGestureDetector().onTouchEvent(event); + } else { + return false; } }); } @@ -470,7 +452,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte } @Override - public void onSaveInstanceState(Bundle savedInstanceState) { + public void onSaveInstanceState(@NonNull Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); String[] ids = new String[backStack.size() + 1]; ids[0] = currentFragment.getTag(); @@ -490,17 +472,23 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte String[] ids = savedInstanceState.getStringArray(Constants.MAIN_BACK_STACK); FragmentManager fm = getSupportFragmentManager(); currentFragment = (SubsonicFragment)fm.findFragmentByTag(ids[0]); - currentFragment.setPrimaryFragment(true); - currentFragment.setSupportTag(ids[0]); + if (currentFragment != null) { + currentFragment.setPrimaryFragment(true); + currentFragment.setSupportTag(ids[0]); + } supportInvalidateOptionsMenu(); FragmentTransaction trans = getSupportFragmentManager().beginTransaction(); for(int i = 1; i < size; i++) { SubsonicFragment frag = (SubsonicFragment)fm.findFragmentByTag(ids[i]); - frag.setSupportTag(ids[i]); - if(secondaryContainer != null) { + if (frag != null) { + frag.setSupportTag(ids[i]); + } + if(frag != null && secondaryContainer != null) { frag.setPrimaryFragment(false, true); } - trans.hide(frag); + if(frag != null) { + trans.hide(frag); + } backStack.add(frag); } trans.commit(); @@ -599,7 +587,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte } } public void setSubtitle(CharSequence title) { - getSupportActionBar().setSubtitle(title); + Objects.requireNonNull(getSupportActionBar()).setSubtitle(title); } @Override @@ -771,10 +759,12 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte currentFragment.setPrimaryFragment(true); supportInvalidateOptionsMenu(); - if(secondaryContainer == null || oldFragment.isAlwaysFullscreen() || currentFragment.isAlwaysStartFullscreen()) { + if(secondaryContainer == null || Objects.requireNonNull(oldFragment).isAlwaysFullscreen() || currentFragment.isAlwaysStartFullscreen()) { FragmentTransaction trans = getSupportFragmentManager().beginTransaction(); trans.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right); - trans.hide(oldFragment); + if (oldFragment != null) { + trans.hide(oldFragment); + } trans.add(R.id.fragment_container, fragment, tag + ""); trans.commit(); } else { @@ -787,9 +777,9 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte if(backStack.size() > 1) { // Move old right to left if there is a backstack already SubsonicFragment newLeftFragment = backStack.get(backStack.size() - 1); - if(replaceCurrent) { - // trans.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right); - } +// if(replaceCurrent) { +// trans.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right); +// } trans.remove(newLeftFragment); // Only move right to left if replaceCurrent is false @@ -911,7 +901,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte if(currentFragment == null || currentFragment.getTitle() == null) { return; } - if(spinnerAdapter == null || getSupportActionBar().getCustomView() == null) { + if(spinnerAdapter == null || Objects.requireNonNull(getSupportActionBar()).getCustomView() == null) { createCustomActionBarView(); } @@ -921,30 +911,30 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte for(int i = 0; i < backStack.size(); i++) { CharSequence title = backStack.get(i).getTitle(); if(title != null) { - spinnerAdapter.add(title); + spinnerAdapter.add(title.toString()); } else { spinnerAdapter.add("null"); } } if(currentFragment.getTitle() != null) { - spinnerAdapter.add(currentFragment.getTitle()); + spinnerAdapter.add(currentFragment.getTitle().toString()); } else { spinnerAdapter.add("null"); } spinnerAdapter.notifyDataSetChanged(); actionBarSpinner.setSelection(spinnerAdapter.getCount() - 1); if(!isTv()) { - getSupportActionBar().setDisplayShowTitleEnabled(false); + Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayShowCustomEnabled(true); } if(drawerToggle.isDrawerIndicatorEnabled()) { - getSupportActionBar().setDisplayHomeAsUpEnabled(false); + Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(false); drawerToggle.setDrawerIndicatorEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } else if(!isTv()) { - getSupportActionBar().setDisplayShowTitleEnabled(true); + Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(true); getSupportActionBar().setTitle(currentFragment.getTitle()); getSupportActionBar().setDisplayShowCustomEnabled(false); drawerToggle.setDrawerIndicatorEnabled(true); @@ -971,7 +961,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte private void applyTheme() { theme = ThemeUtil.getTheme(this); - if(theme != null && theme.indexOf("fullscreen") != -1) { + if(theme != null && theme.contains("fullscreen")) { theme = theme.substring(0, theme.indexOf("_fullscreen")); ThemeUtil.setTheme(this, theme); } @@ -983,15 +973,11 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte fullScreen = Util.getPreferences(this).getBoolean(Constants.PREFERENCES_KEY_FULL_SCREEN, false); if(fullScreen || isTv()) { // Hide additional elements on higher Android versions - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - int flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | - View.SYSTEM_UI_FLAG_FULLSCREEN | - View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; - - getWindow().getDecorView().setSystemUiVisibility(flags); - } else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - getWindow().requestFeature(Window.FEATURE_NO_TITLE); - } + int flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_FULLSCREEN | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; + + getWindow().getDecorView().setSystemUiVisibility(flags); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } } @@ -1048,12 +1034,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte } private void checkIfServiceAvailable() { if(getDownloadService() == null) { - handler.postDelayed(new Runnable() { - @Override - public void run() { - checkIfServiceAvailable(); - } - }, 50); + handler.postDelayed(this::checkIfServiceAvailable, 50); } else if(afterServiceAvailable.size() > 0) { for(Runnable runnable: afterServiceAvailable) { handler.post(runnable); @@ -1086,7 +1067,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte if (service != null) { new SilentBackgroundTask<Void>(this) { @Override - protected Void doInBackground() throws Throwable { + protected Void doInBackground() { service.clearIncomplete(); return null; } @@ -1159,28 +1140,17 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte .setTitle(R.string.offline_sync_dialog_title) .setMessage(this.getResources().getString(R.string.offline_sync_dialog_message, scrobbleCount, starsCount)) .setView(checkBoxView) - .setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if(checkBox.isChecked()) { - Util.setSyncDefault(SubsonicActivity.this, "sync"); - } - syncOffline(scrobbleCount, starsCount); + .setPositiveButton(R.string.common_ok, (dialogInterface, i) -> { + if(checkBox.isChecked()) { + Util.setSyncDefault(SubsonicActivity.this, "sync"); } - }).setNeutralButton(R.string.common_cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - dialogInterface.dismiss(); - } - }).setNegativeButton(R.string.common_delete, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (checkBox.isChecked()) { - Util.setSyncDefault(SubsonicActivity.this, "delete"); - } - deleteOffline(); - } - }); + syncOffline(scrobbleCount, starsCount); + }).setNeutralButton(R.string.common_cancel, (dialogInterface, i) -> dialogInterface.dismiss()).setNegativeButton(R.string.common_delete, (dialogInterface, i) -> { + if (checkBox.isChecked()) { + Util.setSyncDefault(SubsonicActivity.this, "delete"); + } + deleteOffline(); + }); builder.create().show(); } @@ -1214,7 +1184,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte SharedPreferences.Editor offline = Util.getOfflineSync(this).edit(); offline.putInt(Constants.OFFLINE_SCROBBLE_COUNT, 0); offline.putInt(Constants.OFFLINE_STAR_COUNT, 0); - offline.commit(); + offline.apply(); } public int getDrawerItemId(String fragmentType) { @@ -1223,8 +1193,6 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte } switch(fragmentType) { - case "Home": - return R.id.drawer_home; case "Artist": return R.id.drawer_library; case "Playlist": @@ -1265,7 +1233,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte } @Override - public void uncaughtException(Thread thread, Throwable throwable) { + public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) { File file = null; PrintWriter printWriter = null; try { @@ -1273,7 +1241,7 @@ public class SubsonicActivity extends AppCompatActivity implements OnItemSelecte PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); file = new File(Environment.getExternalStorageDirectory(), "dsub-stacktrace.txt"); printWriter = new PrintWriter(file); - printWriter.println("Android API level: " + Build.VERSION.SDK); + printWriter.println("Android API level: " + Build.VERSION.SDK_INT); printWriter.println("Subsonic version name: " + packageInfo.versionName); printWriter.println("Subsonic version code: " + packageInfo.versionCode); printWriter.println(); diff --git a/app/src/main/java/github/daneren2005/dsub/activity/SubsonicFragmentActivity.java b/app/src/main/java/github/daneren2005/dsub/activity/SubsonicFragmentActivity.java index 17e564e2..b2d97247 100644 --- a/app/src/main/java/github/daneren2005/dsub/activity/SubsonicFragmentActivity.java +++ b/app/src/main/java/github/daneren2005/dsub/activity/SubsonicFragmentActivity.java @@ -23,14 +23,14 @@ import android.accounts.AccountManager; import android.app.Dialog; import android.content.ContentResolver; import android.content.Context; -import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.TypedArray; -import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; + +import androidx.annotation.NonNull; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.appcompat.app.AlertDialog; @@ -47,6 +47,7 @@ import com.sothree.slidinguppanel.SlidingUpPanelLayout; import java.io.File; import java.util.Date; import java.util.List; +import java.util.Objects; import github.daneren2005.dsub.R; import github.daneren2005.dsub.domain.MusicDirectory; @@ -85,10 +86,10 @@ import github.daneren2005.dsub.view.ChangeLog; * Created by Scott on 10/14/13. */ public class SubsonicFragmentActivity extends SubsonicActivity implements DownloadService.OnSongChangedListener { - private static String TAG = SubsonicFragmentActivity.class.getSimpleName(); + private static final String TAG = SubsonicFragmentActivity.class.getSimpleName(); private static boolean infoDialogDisplayed; private static boolean sessionInitialized = false; - private static long ALLOWED_SKEW = 30000L; + private static final long ALLOWED_SKEW = 30000L; private SlidingUpPanelLayout slideUpPanel; private SlidingUpPanelLayout.PanelSlideListener panelSlideListener; @@ -105,7 +106,6 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo private ImageButton startButton; private long lastBackPressTime = 0; private DownloadFile currentPlaying; - private PlayerState currentState; private ImageButton previousButton; private ImageButton nextButton; private ImageButton rewindButton; @@ -219,7 +219,7 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo currentFragment.stopActionMode(); // Disable custom view before switching - getSupportActionBar().setDisplayShowCustomEnabled(false); + Objects.requireNonNull(getSupportActionBar()).setDisplayShowCustomEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(true); bottomBar.setVisibility(View.GONE); @@ -250,12 +250,7 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo if(getIntent().hasExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD)) { // Post this later so it actually runs - handler.postDelayed(new Runnable() { - @Override - public void run() { - openNowPlaying(); - } - }, 200); + handler.postDelayed(this::openNowPlaying, 200); getIntent().removeExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD); } @@ -277,98 +272,73 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo } rewindButton = (ImageButton) findViewById(R.id.download_rewind); - rewindButton.setOnClickListener(new View.OnClickListener() { + rewindButton.setOnClickListener(v -> new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { @Override - public void onClick(View v) { - new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { - @Override - protected Void doInBackground() throws Throwable { - if (getDownloadService() == null) { - return null; - } + protected Void doInBackground() { + if (getDownloadService() == null) { + return null; + } - getDownloadService().rewind(); - return null; - } - }.execute(); + getDownloadService().rewind(); + return null; } - }); + }.execute()); previousButton = (ImageButton) findViewById(R.id.download_previous); - previousButton.setOnClickListener(new View.OnClickListener() { + previousButton.setOnClickListener(v -> new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { @Override - public void onClick(View v) { - new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { - @Override - protected Void doInBackground() throws Throwable { - if(getDownloadService() == null) { - return null; - } + protected Void doInBackground() { + if(getDownloadService() == null) { + return null; + } - getDownloadService().previous(); - return null; - } - }.execute(); + getDownloadService().previous(); + return null; } - }); + }.execute()); startButton = (ImageButton) findViewById(R.id.download_start); - startButton.setOnClickListener(new View.OnClickListener() { + startButton.setOnClickListener(v -> new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { @Override - public void onClick(View v) { - new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { - @Override - protected Void doInBackground() throws Throwable { - PlayerState state = getDownloadService().getPlayerState(); - if(state == PlayerState.STARTED) { - getDownloadService().pause(); - } else if(state == PlayerState.IDLE) { - getDownloadService().play(); - } else { - getDownloadService().start(); - } + protected Void doInBackground() { + PlayerState state = getDownloadService().getPlayerState(); + if(state == PlayerState.STARTED) { + getDownloadService().pause(); + } else if(state == PlayerState.IDLE) { + getDownloadService().play(); + } else { + getDownloadService().start(); + } - return null; - } - }.execute(); + return null; } - }); + }.execute()); nextButton = (ImageButton) findViewById(R.id.download_next); - nextButton.setOnClickListener(new View.OnClickListener() { + nextButton.setOnClickListener(v -> new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { @Override - public void onClick(View v) { - new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { - @Override - protected Void doInBackground() throws Throwable { - if(getDownloadService() == null) { - return null; - } + protected Void doInBackground() { + if(getDownloadService() == null) { + return null; + } - getDownloadService().next(); - return null; - } - }.execute(); + getDownloadService().next(); + return null; } - }); + }.execute()); fastforwardButton = (ImageButton) findViewById(R.id.download_fastforward); - fastforwardButton.setOnClickListener(new View.OnClickListener() { + fastforwardButton.setOnClickListener(v -> new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { @Override - public void onClick(View v) { - new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { - @Override - protected Void doInBackground() throws Throwable { - if (getDownloadService() == null) { - return null; - } + protected Void doInBackground() { + if (getDownloadService() == null) { + return null; + } - getDownloadService().fastForward(); - return null; - } - }.execute(); + getDownloadService().fastForward(); + return null; } - }); + }.execute()); } @Override @@ -456,12 +426,7 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo UserUtil.seedCurrentUser(this); createAccount(); - runWhenServiceAvailable(new Runnable() { - @Override - public void run() { - getDownloadService().addOnSongChangedListener(SubsonicFragmentActivity.this, true); - } - }); + runWhenServiceAvailable(() -> getDownloadService().addOnSongChangedListener(SubsonicFragmentActivity.this, true)); } @Override @@ -474,7 +439,7 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo } @Override - public void onSaveInstanceState(Bundle savedInstanceState) { + public void onSaveInstanceState(@NonNull Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putString(Constants.MAIN_NOW_PLAYING, nowPlayingFragment.getTag()); if(secondaryFragment != null) { @@ -598,7 +563,7 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo @Override public void setTitle(CharSequence title) { if(slideUpPanel.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED) { - getSupportActionBar().setTitle(title); + Objects.requireNonNull(getSupportActionBar()).setTitle(title); } else { super.setTitle(title); } @@ -687,19 +652,15 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo Updater updater = new Updater(ver); updater.checkUpdates(this); } - catch(Exception e) { - - } + catch(Exception ignored) {} } private void loadSession() { - if (Build.VERSION.SDK_INT >= 23) { - try { - KeyStoreUtil.loadKeyStore(); - } catch (Exception e) { - Log.w(TAG, "Error loading keystore"); - Log.w(TAG, Log.getStackTraceString(e)); - } + try { + KeyStoreUtil.loadKeyStore(); + } catch (Exception e) { + Log.w(TAG, "Error loading keystore"); + Log.w(TAG, Log.getStackTraceString(e)); } loadSettings(); @@ -741,41 +702,37 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo editor.putString(Constants.PREFERENCES_KEY_SERVER_NAME + 1, "Demo Server"); editor.putString(Constants.PREFERENCES_KEY_SERVER_URL + 1, "http://demo.subsonic.org"); editor.putString(Constants.PREFERENCES_KEY_USERNAME + 1, "guest"); - if (Build.VERSION.SDK_INT < 23) { - editor.putString(Constants.PREFERENCES_KEY_PASSWORD + 1, "guest"); - } else { - // Attempt to encrypt password - String encryptedDefaultPassword = KeyStoreUtil.encrypt("guest"); + // Attempt to encrypt password + String encryptedDefaultPassword = KeyStoreUtil.encrypt("guest"); - if (encryptedDefaultPassword != null) { - // If encryption succeeds, store encrypted password and flag password as encrypted - editor.putString(Constants.PREFERENCES_KEY_PASSWORD + 1, encryptedDefaultPassword); - editor.putBoolean(Constants.PREFERENCES_KEY_ENCRYPTED_PASSWORD + 1, true); - } else { - // Fall back to plaintext if Keystore is having issue - editor = editor.putString(Constants.PREFERENCES_KEY_PASSWORD + 1, "guest"); - editor.putBoolean(Constants.PREFERENCES_KEY_ENCRYPTED_PASSWORD + 1, false); - } + if (encryptedDefaultPassword != null) { + // If encryption succeeds, store encrypted password and flag password as encrypted + editor.putString(Constants.PREFERENCES_KEY_PASSWORD + 1, encryptedDefaultPassword); + editor.putBoolean(Constants.PREFERENCES_KEY_ENCRYPTED_PASSWORD + 1, true); + } else { + // Fall back to plaintext if Keystore is having issue + editor = editor.putString(Constants.PREFERENCES_KEY_PASSWORD + 1, "guest"); + editor.putBoolean(Constants.PREFERENCES_KEY_ENCRYPTED_PASSWORD + 1, false); } editor.putInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1); - editor.commit(); + editor.apply(); } if(!prefs.contains(Constants.PREFERENCES_KEY_SERVER_COUNT)) { SharedPreferences.Editor editor = prefs.edit(); editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, 1); - editor.commit(); + editor.apply(); } } private boolean resetCacheLocation(SharedPreferences prefs) { String newDirectory = FileUtil.getDefaultMusicDirectory(this).getPath(); String oldDirectory = prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null); - if(newDirectory == null || (oldDirectory != null && newDirectory.equals(oldDirectory))) { + if(newDirectory.equals(oldDirectory)) { return false; } else { SharedPreferences.Editor editor = prefs.edit(); editor.putString(Constants.PREFERENCES_KEY_CACHE_LOCATION, newDirectory); - editor.commit(); + editor.apply(); return true; } } @@ -807,7 +764,7 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo private PlayerQueue playerQueue; @Override - protected Void doInBackground() throws Throwable { + protected Void doInBackground() { try { MusicService musicService = MusicServiceFactory.getMusicService(context); PlayerQueue remoteState = musicService.getPlayQueue(context, null); @@ -849,50 +806,35 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo builder.setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.common_confirm) .setMessage(message) - .setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() { + .setPositiveButton(R.string.common_ok, (dialogInterface, i) -> new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { @Override - public void onClick(DialogInterface dialogInterface, int i) { - new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { - @Override - protected Void doInBackground() throws Throwable { - DownloadService downloadService = getDownloadService(); - downloadService.clear(); - downloadService.download(remoteState.songs, false, false, false, false, remoteState.currentPlayingIndex, remoteState.currentPlayingPosition); - return null; - } - }.execute(); + protected Void doInBackground() { + DownloadService downloadService = getDownloadService(); + downloadService.clear(); + downloadService.download(remoteState.songs, false, false, false, false, remoteState.currentPlayingIndex, remoteState.currentPlayingPosition); + return null; } - }) - .setNeutralButton(R.string.common_cancel, new DialogInterface.OnClickListener() { + }.execute()) + .setNeutralButton(R.string.common_cancel, (dialogInterface, i) -> new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { @Override - public void onClick(DialogInterface dialogInterface, int i) { - new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { - @Override - protected Void doInBackground() throws Throwable { - DownloadService downloadService = getDownloadService(); - downloadService.serializeQueue(false); - return null; - } - }.execute(); + protected Void doInBackground() { + DownloadService downloadService = getDownloadService(); + downloadService.serializeQueue(false); + return null; } - }) - .setNegativeButton(R.string.common_never, new DialogInterface.OnClickListener() { + }.execute()) + .setNegativeButton(R.string.common_never, (dialogInterface, i) -> new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { @Override - public void onClick(DialogInterface dialogInterface, int i) { - new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) { - @Override - protected Void doInBackground() throws Throwable { - DownloadService downloadService = getDownloadService(); - downloadService.serializeQueue(false); - - SharedPreferences.Editor editor = Util.getPreferences(SubsonicFragmentActivity.this).edit(); - editor.putBoolean(Constants.PREFERENCES_KEY_RESUME_PLAY_QUEUE_NEVER, true); - editor.commit(); - return null; - } - }.execute(); + protected Void doInBackground() { + DownloadService downloadService = getDownloadService(); + downloadService.serializeQueue(false); + + SharedPreferences.Editor editor = Util.getPreferences(SubsonicFragmentActivity.this).edit(); + editor.putBoolean(Constants.PREFERENCES_KEY_RESUME_PLAY_QUEUE_NEVER, true); + editor.apply(); + return null; } - }); + }.execute()); builder.create().show(); } @@ -902,7 +844,7 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo new SilentBackgroundTask<Void>(this) { @Override - protected Void doInBackground() throws Throwable { + protected Void doInBackground() { AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE); Account account = new Account(Constants.SYNC_ACCOUNT_NAME, Constants.SYNC_ACCOUNT_TYPE); accountManager.addAccountExplicitly(account, null, null); @@ -941,10 +883,6 @@ public class SubsonicFragmentActivity extends SubsonicActivity implements Downlo } } - public Toolbar getActiveToolbar() { - return slideUpPanel.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED ? nowPlayingToolbar : mainToolbar; - } - @Override public void onSongChanged(DownloadFile currentPlaying, int currentPlayingIndex, boolean shouldFastForward) { this.currentPlaying = currentPlaying; diff --git a/app/src/main/java/github/daneren2005/dsub/activity/VoiceQueryReceiverActivity.java b/app/src/main/java/github/daneren2005/dsub/activity/VoiceQueryReceiverActivity.java index 641b118f..78059faa 100644 --- a/app/src/main/java/github/daneren2005/dsub/activity/VoiceQueryReceiverActivity.java +++ b/app/src/main/java/github/daneren2005/dsub/activity/VoiceQueryReceiverActivity.java @@ -24,13 +24,9 @@ import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.provider.MediaStore; -import android.provider.SearchRecentSuggestions; -import android.util.Log; -import github.daneren2005.dsub.fragments.SubsonicFragment; import github.daneren2005.dsub.util.Constants; import github.daneren2005.dsub.util.Util; -import github.daneren2005.dsub.provider.DSubSearchProvider; /** * Receives voice search queries and forwards to the SearchFragment. @@ -40,7 +36,6 @@ import github.daneren2005.dsub.provider.DSubSearchProvider; * @author Sindre Mehus */ public class VoiceQueryReceiverActivity extends Activity { - private static final String TAG = VoiceQueryReceiverActivity.class.getSimpleName(); private static final String GMS_SEARCH_ACTION = "com.google.android.gms.actions.SEARCH_ACTION"; @Override @@ -51,7 +46,7 @@ public class VoiceQueryReceiverActivity extends Activity { if (query != null) { Intent intent = new Intent(VoiceQueryReceiverActivity.this, SubsonicFragmentActivity.class); - intent.putExtra(Constants.INTENT_EXTRA_NAME_QUERY, query); + intent.putExtra(Constants.INTENT_EXTRA_NAME_QUERY, query); if(!GMS_SEARCH_ACTION.equals(getIntent().getAction())) { intent.putExtra(Constants.INTENT_EXTRA_NAME_AUTOPLAY, true); } diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/ArtistAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/ArtistAdapter.java index 0a8b9a54..c10e3dab 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/ArtistAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/ArtistAdapter.java @@ -40,12 +40,8 @@ public class ArtistAdapter extends SectionAdapter<Serializable> implements FastS public static int VIEW_TYPE_SONG = 3; public static int VIEW_TYPE_ARTIST = 4; - private List<MusicFolder> musicFolders; - private OnMusicFolderChanged onMusicFolderChanged; - - public ArtistAdapter(Context context, List<Serializable> artists, OnItemClickedListener listener) { - this(context, artists, null, listener, null); - } + private final List<MusicFolder> musicFolders; + private final OnMusicFolderChanged onMusicFolderChanged; public ArtistAdapter(Context context, List<Serializable> artists, List<MusicFolder> musicFolders, OnItemClickedListener onItemClickedListener, OnMusicFolderChanged onMusicFolderChanged) { super(context, artists); @@ -93,7 +89,7 @@ public class ArtistAdapter extends SectionAdapter<Serializable> implements FastS } }); - return new UpdateView.UpdateViewHolder(header, false); + return new UpdateView.UpdateViewHolder(header); } @Override public void onBindHeaderHolder(UpdateView.UpdateViewHolder holder, String header, int sectionIndex) { diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/ChatAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/ChatAdapter.java index 0c116d39..5b5b23f6 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/ChatAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/ChatAdapter.java @@ -23,7 +23,7 @@ import java.util.regex.Pattern; public class ChatAdapter extends ArrayAdapter<ChatMessage> { private final SubsonicActivity activity; - private ArrayList<ChatMessage> messages; + private final ArrayList<ChatMessage> messages; private final ImageLoader imageLoader; private static final String phoneRegex = "1?\\W*([2-9][0-8][0-9])\\W*([2-9][0-9]{2})\\W*([0-9]{4})"; //you can just place your support phone here diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/DetailsAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/DetailsAdapter.java index 927b63ae..a2549204 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/DetailsAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/DetailsAdapter.java @@ -30,8 +30,8 @@ import java.util.List; import github.daneren2005.dsub.R; public class DetailsAdapter extends ArrayAdapter<String> { - private List<String> headers; - private List<String> details; + private final List<String> headers; + private final List<String> details; public DetailsAdapter(Context context, int layout, List<String> headers, List<String> details) { super(context, layout, headers); diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/EntryGridAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/EntryGridAdapter.java index e75a5104..b769987f 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/EntryGridAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/EntryGridAdapter.java @@ -35,14 +35,12 @@ import github.daneren2005.dsub.view.UpdateView; import github.daneren2005.dsub.view.UpdateView.UpdateViewHolder; public class EntryGridAdapter extends SectionAdapter<Entry> { - private static String TAG = EntryGridAdapter.class.getSimpleName(); - public static int VIEW_TYPE_ALBUM_CELL = 1; public static int VIEW_TYPE_ALBUM_LINE = 2; public static int VIEW_TYPE_SONG = 3; - private ImageLoader imageLoader; - private boolean largeAlbums; + private final ImageLoader imageLoader; + private final boolean largeAlbums; private boolean showArtist = false; private boolean showAlbum = false; private boolean removeFromPlaylist = false; @@ -94,7 +92,7 @@ public class EntryGridAdapter extends SectionAdapter<Entry> { } public UpdateViewHolder onCreateHeaderHolder(ViewGroup parent) { - return new UpdateViewHolder(header, false); + return new UpdateViewHolder(header); } public void onBindHeaderHolder(UpdateViewHolder holder, String header, int sectionIndex) { diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/EntryInfiniteGridAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/EntryInfiniteGridAdapter.java index 6c1c14da..4914d52d 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/EntryInfiniteGridAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/EntryInfiniteGridAdapter.java @@ -20,6 +20,8 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import androidx.annotation.NonNull; + import java.util.List; import github.daneren2005.dsub.R; @@ -47,12 +49,13 @@ public class EntryInfiniteGridAdapter extends EntryGridAdapter { super(context, entries, imageLoader, largeCell); } + @NonNull @Override - public UpdateView.UpdateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + public UpdateView.UpdateViewHolder<Entry> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if(viewType == VIEW_TYPE_LOADING) { View progress = LayoutInflater.from(context).inflate(R.layout.tab_progress, null); progress.setVisibility(View.VISIBLE); - return new UpdateView.UpdateViewHolder(progress, false); + return new UpdateView.UpdateViewHolder(progress); } return super.onCreateViewHolder(parent, viewType); @@ -131,7 +134,7 @@ public class EntryInfiniteGridAdapter extends EntryGridAdapter { result = service.getAlbumList(type, extra, size, offset, false, context, null); } else if("genres".equals(type) || "genres-songs".equals(type)) { result = service.getSongsByGenre(extra, size, offset, context, null); - }else if(type.indexOf(MainFragment.SONGS_LIST_PREFIX) != -1) { + }else if(type.contains(MainFragment.SONGS_LIST_PREFIX)) { result = service.getSongList(type, size, offset, context, null); } else { result = service.getAlbumList(type, size, offset, false, context, null); diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/ExpandableSectionAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/ExpandableSectionAdapter.java index 6ebb34e3..6fc41b1c 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/ExpandableSectionAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/ExpandableSectionAdapter.java @@ -16,13 +16,12 @@ package github.daneren2005.dsub.adapter; import android.content.Context; -import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import github.daneren2005.dsub.R; @@ -31,7 +30,6 @@ import github.daneren2005.dsub.view.BasicHeaderView; import github.daneren2005.dsub.view.UpdateView; public abstract class ExpandableSectionAdapter<T> extends SectionAdapter<T> { - private static final String TAG = ExpandableSectionAdapter.class.getSimpleName(); private static final int DEFAULT_VISIBLE = 4; private static final int EXPAND_TOGGLE = R.attr.select_server; private static final int COLLAPSE_TOGGLE = R.attr.select_tabs; @@ -46,10 +44,7 @@ public abstract class ExpandableSectionAdapter<T> extends SectionAdapter<T> { List<List<T>> sections = new ArrayList<>(); sections.add(section); - init(context, Arrays.asList("Section"), sections, Arrays.asList((Integer) null)); - } - public ExpandableSectionAdapter(Context context, List<String> headers, List<List<T>> sections) { - init(context, headers, sections, null); + init(context, Collections.singletonList("Section"), sections, Collections.singletonList((Integer) null)); } public ExpandableSectionAdapter(Context context, List<String> headers, List<List<T>> sections, List<Integer> sectionsDefaultVisible) { init(context, headers, sections, sectionsDefaultVisible); @@ -143,8 +138,6 @@ public abstract class ExpandableSectionAdapter<T> extends SectionAdapter<T> { toggleSelectionView.setVisibility(View.GONE); } - if(view != null) { - view.setObject(header); - } + view.setObject(header); } } diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/GenreAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/GenreAdapter.java index 70aa5fe3..4020d301 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/GenreAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/GenreAdapter.java @@ -28,7 +28,7 @@ public class GenreAdapter extends SectionAdapter<Genre> implements FastScroller. public static int VIEW_TYPE_GENRE = 1; public GenreAdapter(Context context, List<Genre> genres, OnItemClickedListener listener) { - super(context, genres); + super(context, genres); this.onItemClickedListener = listener; } diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/MainAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/MainAdapter.java index dd70aa99..afbedbdc 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/MainAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/MainAdapter.java @@ -108,8 +108,6 @@ public class MainAdapter extends SectionAdapter<Integer> { checkBox.setVisibility(View.GONE); } - if(view != null) { - view.setObject(display); - } + view.setObject(display); } } diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/PlaylistAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/PlaylistAdapter.java index 6402eecb..4b457326 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/PlaylistAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/PlaylistAdapter.java @@ -28,8 +28,8 @@ import github.daneren2005.dsub.view.UpdateView; public class PlaylistAdapter extends SectionAdapter<Playlist> implements FastScroller.BubbleTextGetter { public static int VIEW_TYPE_PLAYLIST = 1; - private ImageLoader imageLoader; - private boolean largeCell; + private final ImageLoader imageLoader; + private final boolean largeCell; public PlaylistAdapter(Context context, List<Playlist> playlists, ImageLoader imageLoader, boolean largeCell, OnItemClickedListener listener) { super(context, playlists); @@ -62,9 +62,9 @@ public class PlaylistAdapter extends SectionAdapter<Playlist> implements FastScr @Override public String getTextToShowInBubble(int position) { - Object item = getItemForPosition(position); - if(item instanceof Playlist) { - return getNameIndex(((Playlist) item).getName()); + Playlist item = getItemForPosition(position); + if(item != null) { + return getNameIndex(item.getName()); } else { return null; } diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/PodcastChannelAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/PodcastChannelAdapter.java index f843a722..bb243ebf 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/PodcastChannelAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/PodcastChannelAdapter.java @@ -43,8 +43,8 @@ public class PodcastChannelAdapter extends ExpandableSectionAdapter<Serializable public static final int VIEW_TYPE_PODCAST_CELL = 3; public static final int VIEW_TYPE_PODCAST_EPISODE = 4; - private ImageLoader imageLoader; - private boolean largeCell; + private final ImageLoader imageLoader; + private final boolean largeCell; public PodcastChannelAdapter(Context context, List<Serializable> podcasts, ImageLoader imageLoader, OnItemClickedListener listener, boolean largeCell) { super(context, podcasts); diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/SearchAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/SearchAdapter.java index 69e5d56d..4ab29f65 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/SearchAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/SearchAdapter.java @@ -19,9 +19,7 @@ import android.content.Context; import android.content.res.Resources; import android.view.Menu; import android.view.MenuInflater; -import android.view.View; import android.view.ViewGroup; -import android.widget.ImageView; import java.io.Serializable; import java.util.ArrayList; @@ -30,12 +28,10 @@ import java.util.List; import github.daneren2005.dsub.R; import github.daneren2005.dsub.domain.MusicDirectory.Entry; import github.daneren2005.dsub.domain.SearchResult; -import github.daneren2005.dsub.util.DrawableTint; import github.daneren2005.dsub.util.ImageLoader; import github.daneren2005.dsub.util.Util; import github.daneren2005.dsub.view.AlbumView; import github.daneren2005.dsub.view.ArtistView; -import github.daneren2005.dsub.view.BasicHeaderView; import github.daneren2005.dsub.view.SongView; import github.daneren2005.dsub.view.UpdateView; @@ -45,8 +41,8 @@ import static github.daneren2005.dsub.adapter.EntryGridAdapter.VIEW_TYPE_ALBUM_L import static github.daneren2005.dsub.adapter.EntryGridAdapter.VIEW_TYPE_SONG; public class SearchAdapter extends ExpandableSectionAdapter<Serializable> { - private ImageLoader imageLoader; - private boolean largeAlbums; + private final ImageLoader imageLoader; + private final boolean largeAlbums; private static final int MAX_ARTISTS = 10; private static final int MAX_ALBUMS = 4; diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/SectionAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/SectionAdapter.java index af3690c3..5ee97303 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/SectionAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/SectionAdapter.java @@ -19,6 +19,8 @@ import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Build; + +import androidx.annotation.NonNull; import androidx.appcompat.view.ActionMode; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; @@ -34,6 +36,7 @@ import android.widget.PopupMenu; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import github.daneren2005.dsub.R; @@ -46,7 +49,7 @@ import github.daneren2005.dsub.view.UpdateView; import github.daneren2005.dsub.view.UpdateView.UpdateViewHolder; public abstract class SectionAdapter<T> extends RecyclerView.Adapter<UpdateViewHolder<T>> { - private static String TAG = SectionAdapter.class.getSimpleName(); + private static final String TAG = SectionAdapter.class.getSimpleName(); public static int VIEW_TYPE_HEADER = 0; public static String[] ignoredArticles; @@ -54,7 +57,7 @@ public abstract class SectionAdapter<T> extends RecyclerView.Adapter<UpdateViewH protected List<String> headers; protected List<List<T>> sections; protected boolean singleSectionHeader; - protected OnItemClickedListener<T> onItemClickedListener; + protected OnItemClickedListener onItemClickedListener; protected List<T> selected = new ArrayList<>(); protected List<UpdateView> selectedViews = new ArrayList<>(); protected ActionMode currentActionMode; @@ -66,7 +69,7 @@ public abstract class SectionAdapter<T> extends RecyclerView.Adapter<UpdateViewH } public SectionAdapter(Context context, List<T> section, boolean singleSectionHeader) { this.context = context; - this.headers = Arrays.asList("Section"); + this.headers = Collections.singletonList("Section"); this.sections = new ArrayList<>(); this.sections.add(section); this.singleSectionHeader = singleSectionHeader; @@ -81,19 +84,20 @@ public abstract class SectionAdapter<T> extends RecyclerView.Adapter<UpdateViewH this.singleSectionHeader = singleSectionHeader; } - public void replaceExistingData(List<T> section) { - this.sections = new ArrayList<>(); - this.sections.add(section); - notifyDataSetChanged(); - } - public void replaceExistingData(List<String> headers, List<List<T>> sections) { - this.headers = headers; - this.sections = sections; - notifyDataSetChanged(); - } - +// public void replaceExistingData(List<T> section) { +// this.sections = new ArrayList<>(); +// this.sections.add(section); +// notifyDataSetChanged(); +// } +// public void replaceExistingData(List<String> headers, List<List<T>> sections) { +// this.headers = headers; +// this.sections = sections; +// notifyDataSetChanged(); +// } + + @NonNull @Override - public UpdateViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + public UpdateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if(viewType == VIEW_TYPE_HEADER) { return onCreateHeaderHolder(parent); } else { @@ -101,73 +105,59 @@ public abstract class SectionAdapter<T> extends RecyclerView.Adapter<UpdateViewH final UpdateView updateView = holder.getUpdateView(); if(updateView != null) { - updateView.getChildAt(0).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - T item = holder.getItem(); - updateView.onClick(); - if (currentActionMode != null) { - if(updateView.isCheckable()) { - if (selected.contains(item)) { - selected.remove(item); - selectedViews.remove(updateView); - setChecked(updateView, false); - } else { - selected.add(item); - selectedViews.add(updateView); - setChecked(updateView, true); - } + updateView.getChildAt(0).setOnClickListener(v -> { + T item = holder.getItem(); + updateView.onClick(); + if (currentActionMode != null) { + if(updateView.isCheckable()) { + if (selected.contains(item)) { + selected.remove(item); + selectedViews.remove(updateView); + setChecked(updateView, false); + } else { + selected.add(item); + selectedViews.add(updateView); + setChecked(updateView, true); + } - if (selected.isEmpty()) { - currentActionMode.finish(); - } else { - currentActionMode.setTitle(context.getResources().getString(R.string.select_album_n_selected, selected.size())); - } + if (selected.isEmpty()) { + currentActionMode.finish(); + } else { + currentActionMode.setTitle(context.getResources().getString(R.string.select_album_n_selected, selected.size())); } - } else if (onItemClickedListener != null) { - onItemClickedListener.onItemClicked(updateView, item); } + } else if (onItemClickedListener != null) { + onItemClickedListener.onItemClicked(updateView, item); } }); View moreButton = updateView.findViewById(R.id.item_more); if (moreButton != null) { - moreButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - try { - final T item = holder.getItem(); - if (onItemClickedListener != null) { - PopupMenu popup = new PopupMenu(context, v); - onItemClickedListener.onCreateContextMenu(popup.getMenu(), popup.getMenuInflater(), updateView, item); - - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem menuItem) { - return onItemClickedListener.onContextItemSelected(menuItem, updateView, item); - } - }); - popup.show(); - } - } catch(Exception e) { - Log.w(TAG, "Failed to show popup", e); + moreButton.setOnClickListener(v -> { + try { + final T item = holder.getItem(); + if (onItemClickedListener != null) { + PopupMenu popup = new PopupMenu(context, v); + onItemClickedListener.onCreateContextMenu(popup.getMenu(), popup.getMenuInflater(), updateView, item); + + popup.setOnMenuItemClickListener(menuItem -> onItemClickedListener.onContextItemSelected(menuItem, updateView, item)); + popup.show(); } + } catch(Exception e) { + Log.w(TAG, "Failed to show popup", e); } }); if(checkable) { - updateView.getChildAt(0).setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - if(updateView.isCheckable()) { - if (currentActionMode == null) { - startActionMode(holder); - } else { - updateView.getChildAt(0).performClick(); - } + updateView.getChildAt(0).setOnLongClickListener(v -> { + if(updateView.isCheckable()) { + if (currentActionMode == null) { + startActionMode(holder); + } else { + updateView.getChildAt(0).performClick(); } - return true; } + return true; }); } } @@ -342,20 +332,18 @@ public abstract class SectionAdapter<T> extends RecyclerView.Adapter<UpdateViewH selected.add(item); } public List<T> getSelected() { - List<T> selected = new ArrayList<>(); - selected.addAll(this.selected); - return selected; + return new ArrayList<>(this.selected); } public void clearSelected() { // TODO: This needs to work with multiple sections - for(T item: selected) { - int index = sections.get(0).indexOf(item); - - if(singleSectionHeader) { - index++; - } - } +// for(T item: selected) { +// int index = sections.get(0).indexOf(item); +// +// if(singleSectionHeader) { +// index++; +// } +// } selected.clear(); for(UpdateView updateView: selectedViews) { @@ -424,7 +412,7 @@ public abstract class SectionAdapter<T> extends RecyclerView.Adapter<UpdateViewH MenuUtil.hideMenuItems(context, menu, updateView); mode.setTitle(context.getResources().getString(R.string.select_album_n_selected, selected.size())); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Util.getPreferences(context).getBoolean(Constants.PREFERENCES_KEY_COLOR_ACTION_BAR, true)) { + if (Util.getPreferences(context).getBoolean(Constants.PREFERENCES_KEY_COLOR_ACTION_BAR, true)) { TypedValue typedValue = new TypedValue(); Resources.Theme theme = context.getTheme(); theme.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true); @@ -462,7 +450,7 @@ public abstract class SectionAdapter<T> extends RecyclerView.Adapter<UpdateViewH } selectedViews.clear(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Util.getPreferences(context).getBoolean(Constants.PREFERENCES_KEY_COLOR_ACTION_BAR, true)) { + if (Util.getPreferences(context).getBoolean(Constants.PREFERENCES_KEY_COLOR_ACTION_BAR, true)) { Window window = ((SubsonicFragmentActivity) context).getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } diff --git a/app/src/main/java/github/daneren2005/dsub/adapter/SettingsAdapter.java b/app/src/main/java/github/daneren2005/dsub/adapter/SettingsAdapter.java index 4e75a2f7..2f9e39fb 100644 --- a/app/src/main/java/github/daneren2005/dsub/adapter/SettingsAdapter.java +++ b/app/src/main/java/github/daneren2005/dsub/adapter/SettingsAdapter.java @@ -37,7 +37,6 @@ import github.daneren2005.dsub.view.UpdateView; import static github.daneren2005.dsub.domain.User.Setting; public class SettingsAdapter extends SectionAdapter<Setting> { - private static final String TAG = SettingsAdapter.class.getSimpleName(); public final int VIEW_TYPE_SETTING = 1; public final int VIEW_TYPE_SETTING_HEADER = 2; @@ -77,7 +76,7 @@ public class SettingsAdapter extends SectionAdapter<Setting> { public UpdateView.UpdateViewHolder onCreateHeaderHolder(ViewGroup parent) { View header = LayoutInflater.from(context).inflate(R.layout.user_header, parent, false); - return new UpdateView.UpdateViewHolder(header, false); + return new UpdateView.UpdateViewHolder(header); } public void onBindHeaderHolder(UpdateView.UpdateViewHolder holder, String description, int sectionIndex) { View header = holder.getView(); @@ -85,12 +84,7 @@ public class SettingsAdapter extends SectionAdapter<Setting> { RecyclingImageView coverArtView = (RecyclingImageView) header.findViewById(R.id.user_avatar); if(coverArtView != null) { imageLoader.loadAvatar(context, coverArtView, user.getUsername()); - coverArtView.setOnInvalidated(new RecyclingImageView.OnInvalidated() { - @Override - public void onInvalidated(RecyclingImageView imageView) { - imageLoader.loadAvatar(context, imageView, user.getUsername()); - } - }); + coverArtView.setOnInvalidated(imageView -> imageLoader.loadAvatar(context, imageView, user.getUsername())); TextView usernameView = (TextView) header.findViewById(R.id.user_username); usernameView.setText(user.getUsername()); diff --git a/app/src/main/java/github/daneren2005/dsub/audiofx/AudioEffectsController.java b/app/src/main/java/github/daneren2005/dsub/audiofx/AudioEffectsController.java index 1933bd64..18cabdc0 100644 --- a/app/src/main/java/github/daneren2005/dsub/audiofx/AudioEffectsController.java +++ b/app/src/main/java/github/daneren2005/dsub/audiofx/AudioEffectsController.java @@ -36,13 +36,11 @@ public class AudioEffectsController { private EqualizerController equalizerController; public AudioEffectsController(Context context, int audioSessionId) { - this.context = context; + this.context = context; this.audioSessionId = audioSessionId; - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { - available = true; - } - } + available = true; + } public boolean isAvailable() { return available; diff --git a/app/src/main/java/github/daneren2005/dsub/audiofx/EqualizerController.java b/app/src/main/java/github/daneren2005/dsub/audiofx/EqualizerController.java index f170af0b..7d58d3a6 100644 --- a/app/src/main/java/github/daneren2005/dsub/audiofx/EqualizerController.java +++ b/app/src/main/java/github/daneren2005/dsub/audiofx/EqualizerController.java @@ -23,7 +23,6 @@ import java.io.Serializable; import android.content.Context; import android.media.audiofx.BassBoost; import android.media.audiofx.Equalizer; -import android.os.Build; import android.util.Log; import github.daneren2005.dsub.util.FileUtil; @@ -43,7 +42,7 @@ public class EqualizerController { private boolean loudnessAvailable = false; private LoudnessEnhancerController loudnessEnhancerController; private boolean released = false; - private int audioSessionId = 0; + private final int audioSessionId; public EqualizerController(Context context, int audioSessionId) { this.context = context; @@ -54,10 +53,8 @@ public class EqualizerController { private void init() { equalizer = new Equalizer(0, audioSessionId); bass = new BassBoost(0, audioSessionId); - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - loudnessAvailable = true; - loudnessEnhancerController = new LoudnessEnhancerController(context, audioSessionId); - } + loudnessAvailable = true; + loudnessEnhancerController = new LoudnessEnhancerController(audioSessionId); } public void saveSettings() { @@ -146,15 +143,11 @@ public class EqualizerController { private static class EqualizerSettings implements Serializable { - private short[] bandLevels; - private short preset; - private boolean enabled; + private final short[] bandLevels; + private final boolean enabled; private short bass; private int loudness; - public EqualizerSettings() { - - } public EqualizerSettings(Equalizer equalizer, BassBoost boost, LoudnessEnhancerController loudnessEnhancerController) { enabled = equalizer.getEnabled(); bandLevels = new short[equalizer.getNumberOfBands()]; @@ -162,11 +155,6 @@ public class EqualizerController { bandLevels[i] = equalizer.getBandLevel(i); } try { - preset = equalizer.getCurrentPreset(); - } catch (Exception x) { - preset = -1; - } - try { bass = boost.getRoundedStrength(); } catch(Exception e) { bass = 0; diff --git a/app/src/main/java/github/daneren2005/dsub/audiofx/LoudnessEnhancerController.java b/app/src/main/java/github/daneren2005/dsub/audiofx/LoudnessEnhancerController.java index df6fdb1c..be47a551 100644 --- a/app/src/main/java/github/daneren2005/dsub/audiofx/LoudnessEnhancerController.java +++ b/app/src/main/java/github/daneren2005/dsub/audiofx/LoudnessEnhancerController.java @@ -25,15 +25,10 @@ import android.util.Log; public class LoudnessEnhancerController { private static final String TAG = LoudnessEnhancerController.class.getSimpleName(); - private final Context context; private LoudnessEnhancer enhancer; - private boolean released = false; - private int audioSessionId = 0; - public LoudnessEnhancerController(Context context, int audioSessionId) { - this.context = context; + public LoudnessEnhancerController(int audioSessionId) { try { - this.audioSessionId = audioSessionId; enhancer = new LoudnessEnhancer(audioSessionId); } catch (Throwable x) { Log.w(TAG, "Failed to create enhancer", x); @@ -69,7 +64,6 @@ public class LoudnessEnhancerController { public void release() { if (isAvailable()) { enhancer.release(); - released = true; } } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/Artist.java b/app/src/main/java/github/daneren2005/dsub/domain/Artist.java index ff4d86ce..1601047a 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/Artist.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/Artist.java @@ -20,9 +20,10 @@ package github.daneren2005.dsub.domain; import android.util.Log; +import androidx.annotation.NonNull; + import java.io.Serializable; import java.text.Collator; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; @@ -32,7 +33,6 @@ import java.util.Locale; */ public class Artist implements Serializable { private static final String TAG = Artist.class.getSimpleName(); - public static final String ROOT_ID = "-1"; public static final String MISSING_ID = "-2"; private String id; @@ -114,14 +114,15 @@ public class Artist implements Serializable { return id.hashCode(); } - @Override + @NonNull + @Override public String toString() { return name; } public static class ArtistComparator implements Comparator<Artist> { - private String[] ignoredArticles; - private Collator collator; + private final String[] ignoredArticles; + private final Collator collator; public ArtistComparator(String[] ignoredArticles) { this.ignoredArticles = ignoredArticles; @@ -150,7 +151,7 @@ public class Artist implements Serializable { public static void sort(List<Artist> artists, String[] ignoredArticles) { try { - Collections.sort(artists, new ArtistComparator(ignoredArticles)); + artists.sort(new ArtistComparator(ignoredArticles)); } catch (Exception e) { Log.w(TAG, "Failed to sort artists", e); } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/Genre.java b/app/src/main/java/github/daneren2005/dsub/domain/Genre.java index dcf12a1d..c67be70d 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/Genre.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/Genre.java @@ -1,5 +1,7 @@ package github.daneren2005.dsub.domain; +import androidx.annotation.NonNull; + import java.io.Serializable; import java.util.Collections; import java.util.Comparator; @@ -27,7 +29,8 @@ public class Genre implements Serializable { this.index = index; } - @Override + @NonNull + @Override public String toString() { return name; } @@ -58,7 +61,7 @@ public class Genre implements Serializable { } public static List<Genre> sort(List<Genre> genres) { - Collections.sort(genres, new GenreComparator()); + genres.sort(new GenreComparator()); return genres; } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/Indexes.java b/app/src/main/java/github/daneren2005/dsub/domain/Indexes.java index 05e686ca..b4fd08b2 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/Indexes.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/Indexes.java @@ -33,30 +33,29 @@ import github.daneren2005.dsub.util.Util; */ public class Indexes implements Serializable { - private long lastModified; +// private final long lastModified; private List<Artist> shortcuts; - private List<Artist> artists; - private List<MusicDirectory.Entry> entries; + private final List<Artist> artists; + private final List<MusicDirectory.Entry> entries; - public Indexes() { +// public Indexes() {} - } public Indexes(long lastModified, List<Artist> shortcuts, List<Artist> artists) { - this.lastModified = lastModified; +// this.lastModified = lastModified; this.shortcuts = shortcuts; - this.artists = artists; - this.entries = new ArrayList<MusicDirectory.Entry>(); + this.artists = artists; + this.entries = new ArrayList<>(); } public Indexes(long lastModified, List<Artist> shortcuts, List<Artist> artists, List<MusicDirectory.Entry> entries) { - this.lastModified = lastModified; +// this.lastModified = lastModified; this.shortcuts = shortcuts; this.artists = artists; this.entries = entries; } - public long getLastModified() { - return lastModified; - } +// public long getLastModified() { +// return lastModified; +// } public List<Artist> getShortcuts() { return shortcuts; diff --git a/app/src/main/java/github/daneren2005/dsub/domain/MusicDirectory.java b/app/src/main/java/github/daneren2005/dsub/domain/MusicDirectory.java index a2b6d4ed..16d12100 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/MusicDirectory.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/MusicDirectory.java @@ -18,13 +18,12 @@ */ package github.daneren2005.dsub.domain; -import android.annotation.TargetApi; import android.content.Context; -import android.content.SharedPreferences; import android.media.MediaMetadataRetriever; -import android.os.Build; import android.util.Log; +import androidx.annotation.NonNull; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -41,6 +40,7 @@ import java.io.Serializable; import java.util.Collections; import java.util.Comparator; import java.util.Locale; +import java.util.Objects; import github.daneren2005.dsub.service.DownloadService; import github.daneren2005.dsub.util.Constants; @@ -59,7 +59,7 @@ public class MusicDirectory implements Serializable { private List<Entry> children; public MusicDirectory() { - children = new ArrayList<Entry>(); + children = new ArrayList<>(); } public MusicDirectory(List<Entry> children) { this.children = children; @@ -111,16 +111,16 @@ public class MusicDirectory implements Serializable { return children; } - List<Entry> result = new ArrayList<Entry>(children.size()); + List<Entry> result = new ArrayList<>(children.size()); for (Entry child : children) { - if (child != null && child.isDirectory() && includeDirs || !child.isDirectory() && includeFiles) { + if (child != null && child.isDirectory() && includeDirs || !Objects.requireNonNull(child).isDirectory() && includeFiles) { result.add(child); } } return result; } public synchronized List<Entry> getSongs() { - List<Entry> result = new ArrayList<Entry>(); + List<Entry> result = new ArrayList<>(); for (Entry child : children) { if (child != null && !child.isDirectory() && !child.isVideo()) { result.add(child); @@ -149,11 +149,9 @@ public class MusicDirectory implements Serializable { public synchronized boolean updateMetadata(MusicDirectory refreshedDirectory) { boolean metadataUpdated = false; - Iterator<Entry> it = children.iterator(); - while(it.hasNext()) { - Entry entry = it.next(); + for (Entry entry : children) { int index = refreshedDirectory.children.indexOf(entry); - if(index != -1) { + if (index != -1) { final Entry refreshed = refreshedDirectory.children.get(index); entry.setTitle(refreshed.getTitle()); @@ -168,7 +166,7 @@ public class MusicDirectory implements Serializable { entry.setStarred(refreshed.isStarred()); entry.setRating(refreshed.getRating()); entry.setType(refreshed.getType()); - if(!Util.equals(entry.getCoverArt(), refreshed.getCoverArt())) { + if (!Util.equals(entry.getCoverArt(), refreshed.getCoverArt())) { metadataUpdated = true; entry.setCoverArt(refreshed.getCoverArt()); } @@ -188,7 +186,7 @@ public class MusicDirectory implements Serializable { found.setStarred(refreshed.isStarred()); found.setRating(refreshed.getRating()); found.setType(refreshed.getType()); - if(!Util.equals(found.getCoverArt(), refreshed.getCoverArt())) { + if (!Util.equals(found.getCoverArt(), refreshed.getCoverArt())) { found.setCoverArt(refreshed.getCoverArt()); metadataUpdate = DownloadService.METADATA_UPDATED_COVER_ART; } @@ -205,7 +203,7 @@ public class MusicDirectory implements Serializable { while(it.hasNext()) { Entry entry = it.next(); // No longer exists in here - if(refreshedDirectory.children.indexOf(entry) == -1) { + if(!refreshedDirectory.children.contains(entry)) { it.remove(); changed = true; } @@ -279,7 +277,6 @@ public class MusicDirectory implements Serializable { this.linkedArtist = artist; } - @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) public void loadMetadata(File file) { try { MediaMetadataRetriever metadata = new MediaMetadataRetriever(); @@ -325,7 +322,7 @@ public class MusicDirectory implements Serializable { if (index != -1) { filename = filename.substring(index + 1); if (getTrack() != null) { - filename = filename.replace(String.format("%02d ", getTrack()), ""); + filename = filename.replace(String.format(Locale.getDefault(), "%02d ", getTrack()), ""); } index = filename.lastIndexOf('.'); @@ -601,17 +598,17 @@ public class MusicDirectory implements Serializable { this.closeness = closeness; } - public boolean isOnlineId(Context context) { - try { - String cacheLocation = Util.getPreferences(context).getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null); - return cacheLocation == null || id == null || id.indexOf(cacheLocation) == -1; - } catch(Exception e) { - Log.w(TAG, "Failed to check online id validity"); - - // Err on the side of default functionality - return true; - } - } +// public boolean isOnlineId(Context context) { +// try { +// String cacheLocation = Util.getPreferences(context).getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null); +// return cacheLocation == null || id == null || !id.contains(cacheLocation); +// } catch(Exception e) { +// Log.w(TAG, "Failed to check online id validity"); +// +// // Err on the side of default functionality +// return true; +// } +// } @Override public boolean equals(Object o) { @@ -631,49 +628,35 @@ public class MusicDirectory implements Serializable { return id.hashCode(); } - @Override + @NonNull + @Override public String toString() { return title; } public byte[] toByteArray() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutput out = null; - try { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + ObjectOutput out; out = new ObjectOutputStream(bos); out.writeObject(this); out.flush(); return bos.toByteArray(); - } finally { - try { - bos.close(); - } catch (IOException ex) { - // ignore close exception - } } + // ignore close exception } public static Entry fromByteArray(byte[] byteArray) throws IOException, ClassNotFoundException { ByteArrayInputStream bis = new ByteArrayInputStream(byteArray); - ObjectInput in = null; - try { - in = new ObjectInputStream(bis); + try (ObjectInput in = new ObjectInputStream(bis)) { return (Entry) in.readObject(); - } finally { - try { - if (in != null) { - in.close(); - } - } catch (IOException ex) { - // ignore close exception - } } + // ignore close exception } } public static class EntryComparator implements Comparator<Entry> { - private boolean byYear; - private Collator collator; + private final boolean byYear; + private final Collator collator; public EntryComparator(boolean byYear) { this.byYear = byYear; @@ -715,7 +698,7 @@ public class MusicDirectory implements Serializable { Integer lhsTrack = lhs.getTrack(); Integer rhsTrack = rhs.getTrack(); - if(lhsTrack == rhsTrack) { + if(Objects.equals(lhsTrack, rhsTrack)) { return collator.compare(lhs.getTitle(), rhs.getTitle()); } else if(lhsTrack != null && rhsTrack != null) { return lhsTrack.compareTo(rhsTrack); @@ -730,7 +713,7 @@ public class MusicDirectory implements Serializable { } public static void sort(List<Entry> entries, boolean byYear) { try { - Collections.sort(entries, new EntryComparator(byYear)); + entries.sort(new EntryComparator(byYear)); } catch (Exception e) { Log.w(TAG, "Failed to sort MusicDirectory"); } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/MusicFolder.java b/app/src/main/java/github/daneren2005/dsub/domain/MusicFolder.java index 37f76249..6f97e89c 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/MusicFolder.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/MusicFolder.java @@ -72,7 +72,7 @@ public class MusicFolder implements Serializable { public static void sort(List<MusicFolder> musicFolders) { try { - Collections.sort(musicFolders, new MusicFolderComparator()); + musicFolders.sort(new MusicFolderComparator()); } catch (Exception e) { Log.w(TAG, "Failed to sort music folders", e); } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/PlayerState.java b/app/src/main/java/github/daneren2005/dsub/domain/PlayerState.java index 21f1b1a4..a733814f 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/PlayerState.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/PlayerState.java @@ -20,6 +20,8 @@ package github.daneren2005.dsub.domain; import android.media.RemoteControlClient; +import androidx.media.MediaSessionManager; + /** * @author Sindre Mehus * @version $Id$ diff --git a/app/src/main/java/github/daneren2005/dsub/domain/Playlist.java b/app/src/main/java/github/daneren2005/dsub/domain/Playlist.java index d3453e50..002ad57e 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/Playlist.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/Playlist.java @@ -18,6 +18,8 @@ */ package github.daneren2005.dsub.domain; +import androidx.annotation.NonNull; + import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -51,7 +53,7 @@ public class Playlist implements Serializable { } public Playlist(String id, String name, String owner, String comment, String songCount, String pub, Date created, Date changed, Integer duration) { this.id = id; - this.name = name; + this.name = name; this.owner = (owner == null) ? "" : owner; this.comment = (comment == null) ? "" : comment; this.songCount = (songCount == null) ? "" : songCount; @@ -152,6 +154,7 @@ public class Playlist implements Serializable { this.duration = duration; } + @NonNull @Override public String toString() { return name; @@ -180,7 +183,7 @@ public class Playlist implements Serializable { } public static List<Playlist> sort(List<Playlist> playlists) { - Collections.sort(playlists, new PlaylistComparator()); + playlists.sort(new PlaylistComparator()); return playlists; } } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/PodcastChannel.java b/app/src/main/java/github/daneren2005/dsub/domain/PodcastChannel.java index 41640636..75fd4180 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/PodcastChannel.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/PodcastChannel.java @@ -145,7 +145,7 @@ public class PodcastChannel implements Serializable { String ignoredArticlesString = prefs.getString(Constants.CACHE_KEY_IGNORE, "The El La Los Las Le Les"); ignoredArticles = ignoredArticlesString.split(" "); - Collections.sort(podcasts, new PodcastComparator()); + podcasts.sort(new PodcastComparator()); return podcasts; } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/SearchCritera.java b/app/src/main/java/github/daneren2005/dsub/domain/SearchCritera.java index ed2400ef..29ab7c7c 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/SearchCritera.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/SearchCritera.java @@ -68,24 +68,24 @@ public class SearchCritera { // * Replace spaces and wildcard '*' characters with ".*" // * All other characters are properly quoted if (this.pattern == null) { - String regex = ".*"; - String currentPart = ""; + StringBuilder regex = new StringBuilder(".*"); + StringBuilder currentPart = new StringBuilder(); for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); if (c == '*' || c == ' ') { - regex += Pattern.quote(currentPart); - regex += ".*"; - currentPart = ""; + regex.append(Pattern.quote(currentPart.toString())); + regex.append(".*"); + currentPart = new StringBuilder(); } else { - currentPart += c; + currentPart.append(c); } } if (currentPart.length() > 0) { - regex += Pattern.quote(currentPart); + regex.append(Pattern.quote(currentPart.toString())); } - regex += ".*"; - this.pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); + regex.append(".*"); + this.pattern = Pattern.compile(regex.toString(), Pattern.CASE_INSENSITIVE); } return this.pattern; diff --git a/app/src/main/java/github/daneren2005/dsub/domain/ServerInfo.java b/app/src/main/java/github/daneren2005/dsub/domain/ServerInfo.java index 5852210e..5ac4635b 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/ServerInfo.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/ServerInfo.java @@ -24,7 +24,6 @@ import java.io.Serializable; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import github.daneren2005.dsub.util.Constants; import github.daneren2005.dsub.util.FileUtil; import github.daneren2005.dsub.util.Util; @@ -37,7 +36,7 @@ public class ServerInfo implements Serializable { public static final int TYPE_SUBSONIC = 1; public static final int TYPE_MADSONIC = 2; public static final int TYPE_AMPACHE = 3; - private static final Map<Integer, ServerInfo> SERVERS = new ConcurrentHashMap<Integer, ServerInfo>(); + private static final Map<Integer, ServerInfo> SERVERS = new ConcurrentHashMap<>(); private boolean isLicenseValid; private Version restVersion; @@ -70,12 +69,12 @@ public class ServerInfo implements Serializable { this.type = type; } - public boolean isStockSubsonic() { - return type == TYPE_SUBSONIC; - } - public boolean isMadsonic() { - return type == TYPE_MADSONIC; - } +// public boolean isStockSubsonic() { +// return type == TYPE_SUBSONIC; +// } +// public boolean isMadsonic() { +// return type == TYPE_MADSONIC; +// } @Override public boolean equals(Object o) { @@ -97,10 +96,11 @@ public class ServerInfo implements Serializable { } } - // Stub to make sure this is never used, too easy to screw up - private void saveServerInfo(Context context) { +// // Stub to make sure this is never used, too easy to screw up +// private void saveServerInfo(Context context) { +// +// } - } public void saveServerInfo(Context context, int instance) { ServerInfo current = SERVERS.get(instance); if(!this.equals(current)) { @@ -109,9 +109,10 @@ public class ServerInfo implements Serializable { } } - public static ServerInfo getServerInfo(Context context) { - return getServerInfo(context, Util.getActiveServer(context)); - } +// public static ServerInfo getServerInfo(Context context) { +// return getServerInfo(context, Util.getActiveServer(context)); +// } + public static ServerInfo getServerInfo(Context context, int instance) { ServerInfo current = SERVERS.get(instance); if(current != null) { @@ -156,9 +157,10 @@ public class ServerInfo implements Serializable { return version.compareTo(required) >= 0; } - public static int getServerType(Context context) { - return getServerType(context, Util.getActiveServer(context)); - } +// public static int getServerType(Context context) { +// return getServerType(context, Util.getActiveServer(context)); +// } + public static int getServerType(Context context, int instance) { if(Util.isOffline(context)) { return 0; @@ -192,12 +194,13 @@ public class ServerInfo implements Serializable { return getServerType(context, instance) == TYPE_MADSONIC && checkServerVersion(context, "2.0", instance); } - public static boolean isAmpache(Context context) { - return isAmpache(context, Util.getActiveServer(context)); - } - public static boolean isAmpache(Context context, int instance) { - return getServerType(context, instance) == TYPE_AMPACHE; - } +// public static boolean isAmpache(Context context) { +// return isAmpache(context, Util.getActiveServer(context)); +// } + +// public static boolean isAmpache(Context context, int instance) { +// return getServerType(context, instance) == TYPE_AMPACHE; +// } private static String getCacheName(Context context, int instance) { return "server-" + Util.getRestUrl(context, null, instance, false).hashCode() + ".ser"; @@ -231,16 +234,13 @@ public class ServerInfo implements Serializable { return ServerInfo.isMadsonic(context) || ServerInfo.checkServerVersion(context, "1.13"); } - public static boolean canUseToken(Context context) { - return canUseToken(context, Util.getActiveServer(context)); - } +// public static boolean canUseToken(Context context) { +// return canUseToken(context, Util.getActiveServer(context)); +// } + public static boolean canUseToken(Context context, int instance) { if(isStockSubsonic(context, instance) && checkServerVersion(context, "1.14", instance)) { - if(Util.getBlockTokenUse(context, instance)) { - return false; - } else { - return true; - } + return !Util.getBlockTokenUse(context, instance); } else { return false; } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/Share.java b/app/src/main/java/github/daneren2005/dsub/domain/Share.java index 380811a7..9dcd76bb 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/Share.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/Share.java @@ -36,10 +36,10 @@ public class Share implements Serializable { private Date lastVisited; private Date expires; private Long visitCount; - private List<Entry> entries; + private final List<Entry> entries; public Share() { - entries = new ArrayList<Entry>(); + entries = new ArrayList<>(); } public String getName() { @@ -105,17 +105,18 @@ public class Share implements Serializable { return lastVisited; } - public void setLastVisited(String lastVisited) { - if (lastVisited != null) { - try { - this.lastVisited = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH).parse(lastVisited); - } catch (ParseException e) { - this.lastVisited = null; - } - } else { - this.lastVisited = null; - } - } +// public void setLastVisited(String lastVisited) { +// if (lastVisited != null) { +// try { +// this.lastVisited = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH).parse(lastVisited); +// } catch (ParseException e) { +// this.lastVisited = null; +// } +// } else { +// this.lastVisited = null; +// } +// } + public void setLastVisited(Date lastVisited) { this.lastVisited = lastVisited; } diff --git a/app/src/main/java/github/daneren2005/dsub/domain/User.java b/app/src/main/java/github/daneren2005/dsub/domain/User.java index 5307828a..11ef2d53 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/User.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/User.java @@ -15,8 +15,6 @@ package github.daneren2005.dsub.domain; -import android.util.Pair; - import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -55,7 +53,7 @@ public class User implements Serializable { private String password; private String email; - private List<Setting> settings = new ArrayList<Setting>(); + private final List<Setting> settings = new ArrayList<>(); private List<Setting> musicFolders; public User() { @@ -139,11 +137,12 @@ public class User implements Serializable { } public static class MusicFolderSetting extends Setting { - private String label; + private final String label; - public MusicFolderSetting() { +// public MusicFolderSetting() { +// +// } - } public MusicFolderSetting(String name, String label, Boolean value) { super(name, value); this.label = label; diff --git a/app/src/main/java/github/daneren2005/dsub/domain/Version.java b/app/src/main/java/github/daneren2005/dsub/domain/Version.java index 9df0dbb4..39e83c3c 100644 --- a/app/src/main/java/github/daneren2005/dsub/domain/Version.java +++ b/app/src/main/java/github/daneren2005/dsub/domain/Version.java @@ -18,6 +18,8 @@ */ package github.daneren2005.dsub.domain; +import androidx.annotation.NonNull; + import java.io.Serializable; /** @@ -42,14 +44,14 @@ public class Version implements Comparable<Version>, Serializable { */ public Version(String version) { String[] s = version.split("\\."); - major = Integer.valueOf(s[0]); - minor = Integer.valueOf(s[1]); + major = Integer.parseInt(s[0]); + minor = Integer.parseInt(s[1]); if (s.length > 2) { if (s[2].contains("beta")) { - beta = Integer.valueOf(s[2].replace("beta", "")); + beta = Integer.parseInt(s[2].replace("beta", "")); } else { - bugfix = Integer.valueOf(s[2]); + bugfix = Integer.parseInt(s[2]); } } } @@ -63,40 +65,39 @@ public class Version implements Comparable<Version>, Serializable { } public String getVersion() { - switch(major) { - case 1: - switch(minor) { - case 0: - return "3.8"; - case 1: - return "3.9"; - case 2: - return "4.0"; - case 3: - return "4.1"; - case 4: - return "4.2"; - case 5: - return "4.3.1"; - case 6: - return "4.5"; - case 7: - return "4.6"; - case 8: - return "4.7"; - case 9: - return "4.8"; - case 10: - return "4.9"; - case 11: - return "5.1"; - case 12: - return "5.2"; - case 13: - return "5.3"; - case 14: - return "6.0"; - } + if (major == 1) { + switch (minor) { + case 0: + return "3.8"; + case 1: + return "3.9"; + case 2: + return "4.0"; + case 3: + return "4.1"; + case 4: + return "4.2"; + case 5: + return "4.3.1"; + case 6: + return "4.5"; + case 7: + return "4.6"; + case 8: + return "4.7"; + case 9: + return "4.8"; + case 10: + return "4.9"; + case 11: + return "5.1"; + case 12: + return "5.2"; + case 13: + return "5.3"; + case 14: + return "6.0"; + } } return ""; } @@ -135,8 +136,9 @@ public class Version implements Comparable<Version>, Serializable { * Returns a string representation of the form "1.27", "1.27.2" or "1.27.beta3". * @return A string representation of the form "1.27", "1.27.2" or "1.27.beta3". */ + @NonNull public String toString() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(major).append('.').append(minor); if (beta != 0) { buf.append(".beta").append(beta); diff --git a/app/src/main/java/github/daneren2005/dsub/fragments/AdminFragment.java b/app/src/main/java/github/daneren2005/dsub/fragments/AdminFragment.java index 552712f7..dcd3d16a 100644 --- a/app/src/main/java/github/daneren2005/dsub/fragments/AdminFragment.java +++ b/app/src/main/java/github/daneren2005/dsub/fragments/AdminFragment.java @@ -37,7 +37,6 @@ import github.daneren2005.dsub.adapter.UserAdapter; import github.daneren2005.dsub.view.UpdateView; public class AdminFragment extends SelectRecyclerFragment<User> { - private static String TAG = AdminFragment.class.getSimpleName(); @Override public boolean onOptionsItemSelected(MenuItem item) { @@ -45,10 +44,8 @@ public class AdminFragment extends SelectRecyclerFragment<User> { return true; } - switch (item.getItemId()) { - case R.id.menu_add_user: - UserUtil.addNewUser(context, this, (objects.size() > 0) ? objects.get(0) : null); - break; + if (item.getItemId() == R.id.menu_add_user) { + UserUtil.addNewUser(context, this, (objects.size() > 0) ? objects.get(0) : null); } return false; @@ -65,18 +62,14 @@ public class AdminFragment extends SelectRecyclerFragment<User> { @Override public boolean onContextItemSelected(MenuItem menuItem, UpdateView<User> updateView, User user) { - switch(menuItem.getItemId()) { - case R.id.admin_change_email: - UserUtil.changeEmail(context, user); - break; - case R.id.admin_change_password: - UserUtil.changePassword(context, user); - break; - case R.id.admin_delete_user: - UserUtil.deleteUser(context, user, adapter); - break; + int id = menuItem.getItemId(); + if (id == R.id.admin_change_email) { + UserUtil.changeEmail(context, user); + } else if (id == R.id.admin_change_password) { + UserUtil.changePassword(context, user); + } else if (id == R.id.admin_delete_user) { + UserUtil.deleteUser(context, user, adapter); } - return true; } diff --git a/app/src/main/java/github/daneren2005/dsub/fragments/ChatFragment.java b/app/src/main/java/github/daneren2005/dsub/fragments/ChatFragment.java index efdf0c7f..cec28722 100644 --- a/app/src/main/java/github/daneren2005/dsub/fragments/ChatFragment.java +++ b/app/src/main/java/github/daneren2005/dsub/fragments/ChatFragment.java @@ -9,6 +9,8 @@ import java.util.Collections; import java.util.List; import android.os.Bundle; import android.os.Handler; + +import androidx.annotation.NonNull; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.text.Editable; import android.text.TextWatcher; @@ -24,7 +26,6 @@ import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; -import android.widget.TextView; import github.daneren2005.dsub.R; import github.daneren2005.dsub.domain.ChatMessage; import github.daneren2005.dsub.service.MusicService; @@ -42,7 +43,6 @@ import java.util.concurrent.TimeUnit; * @author Joshua Bahnsen */ public class ChatFragment extends SubsonicFragment { - private static final String TAG = ChatFragment.class.getSimpleName(); private ListView chatListView; private EditText messageEditText; private ImageButton sendButton; @@ -56,7 +56,7 @@ public class ChatFragment extends SubsonicFragment { if(bundle != null) { List<ChatMessage> abstractList = (List<ChatMessage>) bundle.getSerializable(Constants.FRAGMENT_LIST); - messageList = new ArrayList<ChatMessage>(abstractList); + messageList = new ArrayList<>(abstractList); } } @@ -73,12 +73,7 @@ public class ChatFragment extends SubsonicFragment { messageEditText = (EditText) rootView.findViewById(R.id.chat_edittext); sendButton = (ImageButton) rootView.findViewById(R.id.chat_send); - sendButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - sendMessage(); - } - }); + sendButton.setOnClickListener(view -> sendMessage()); chatListView = (ListView) rootView.findViewById(R.id.chat_entries); chatListView.setStackFromBottom(true); @@ -99,21 +94,17 @@ public class ChatFragment extends SubsonicFragment { } }); - messageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { - - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (actionId == EditorInfo.IME_ACTION_DONE || (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)) { - sendMessage(); - return true; - } - - return false; + messageEditText.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_DONE || (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)) { + sendMessage(); + return true; } + + return false; }); if(messageList == null) { - messageList = new ArrayList<ChatMessage>(); + messageList = new ArrayList<>(); refresh(true); } else { for (ChatMessage message : messageList) { @@ -139,21 +130,13 @@ public class ChatFragment extends SubsonicFragment { super.onStart(); final Handler handler = new Handler(); - Runnable runnable = new Runnable() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - if(primaryFragment) { - load(false); - } else { - invalidated = true; - } - } - }); + Runnable runnable = () -> handler.post(() -> { + if(primaryFragment) { + load(false); + } else { + invalidated = true; } - }; + }); SharedPreferences prefs = Util.getPreferences(context); long refreshRate = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_CHAT_REFRESH, "30")); @@ -173,7 +156,7 @@ public class ChatFragment extends SubsonicFragment { } @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) { + public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater menuInflater) { menuInflater.inflate(R.menu.abstract_top_menu, menu); } diff --git a/app/src/main/java/github/daneren2005/dsub/fragments/DownloadFragment.java b/app/src/main/java/github/daneren2005/dsub/fragments/DownloadFragment.java index 4c37beec..49f31141 100644 --- a/app/src/main/java/github/daneren2005/dsub/fragments/DownloadFragment.java +++ b/app/src/main/java/github/daneren2005/dsub/fragments/DownloadFragment.java @@ -15,7 +15,6 @@ package github.daneren2005.dsub.fragments; -import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import androidx.recyclerview.widget.ItemTouchHelper; @@ -69,17 +68,7 @@ public class DownloadFragment extends SelectRecyclerFragment<DownloadFile> imple super.onStart(); final Handler handler = new Handler(); - Runnable runnable = new Runnable() { - @Override - public void run() { - handler.post(new Runnable() { - @Override - public void run() { - update(); - } - }); - } - }; + Runnable runnable = () -> handler.post(this::update); executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleWithFixedDelay(runnable, 0L, 1000L, TimeUnit.MILLISECONDS); @@ -105,11 +94,10 @@ public class DownloadFragment extends SelectRecyclerFragment<DownloadFile> imple public List<DownloadFile> getObjects(MusicService musicService, boolean refresh, ProgressListener listener) throws Exception { DownloadService downloadService = getDownloadService(); if(downloadService == null) { - return new ArrayList<DownloadFile>(); + return new ArrayList<>(); } - List<DownloadFile> songList = new ArrayList<DownloadFile>(); - songList.addAll(downloadService.getBackgroundDownloads()); + List<DownloadFile> songList = new ArrayList<>(downloadService.getBackgroundDownloads()); currentRevision = downloadService.getDownloadListUpdateRevision(); return songList; } @@ -147,26 +135,20 @@ public class DownloadFragment extends SelectRecyclerFragment<DownloadFile> imple return true; } - switch (menuItem.getItemId()) { - case R.id.menu_remove_all: - Util.confirmDialog(context, R.string.download_menu_remove_all, "", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - new SilentBackgroundTask<Void>(context) { - @Override - protected Void doInBackground() throws Throwable { - getDownloadService().clearBackground(); - return null; - } - - @Override - protected void done(Void result) { - update(); - } - }.execute(); - } - }); - return true; + if (menuItem.getItemId() == R.id.menu_remove_all) { + Util.confirmDialog(context, R.string.download_menu_remove_all, "", (dialog, which) -> new SilentBackgroundTask<Void>(context) { + @Override + protected Void doInBackground() { + getDownloadService().clearBackground(); + return null; + } + + @Override + protected void done(Void result) { + update(); + } + }.execute()); + return true; } return false; diff --git a/app/src/main/java/github/daneren2005/dsub/fragments/LyricsFragment.java b/app/src/main/java/github/daneren2005/dsub/fragments/LyricsFragment.java index 402bd257..50049656 100644 --- a/app/src/main/java/github/daneren2005/dsub/fragments/LyricsFragment.java +++ b/app/src/main/java/github/daneren2005/dsub/fragments/LyricsFragment.java @@ -81,6 +81,7 @@ public final class LyricsFragment extends SubsonicFragment { BackgroundTask<Lyrics> task = new TabBackgroundTask<Lyrics>(this) { @Override protected Lyrics doInBackground() throws Throwable { + assert getArguments() != null; String artist = getArguments().getString(Constants.INTENT_EXTRA_NAME_ARTIST); String title = getArguments().getString(Constants.INTENT_EXTRA_NAME_TITLE); MusicService musicService = MusicServiceFactory.getMusicService(context); diff --git a/app/src/main/java/github/daneren2005/dsub/view/UpdateView.java b/app/src/main/java/github/daneren2005/dsub/view/UpdateView.java index a4727643..d977bdf0 100644 --- a/app/src/main/java/github/daneren2005/dsub/view/UpdateView.java +++ b/app/src/main/java/github/daneren2005/dsub/view/UpdateView.java @@ -43,7 +43,7 @@ import github.daneren2005.dsub.util.SilentBackgroundTask; public abstract class UpdateView<T> extends LinearLayout { private static final String TAG = UpdateView.class.getSimpleName(); - private static final WeakHashMap<UpdateView, ?> INSTANCES = new WeakHashMap<UpdateView, Object>(); + private static final WeakHashMap<UpdateView<?>, ?> INSTANCES = new WeakHashMap<>(); protected static Handler backgroundHandler; protected static Handler uiHandler; @@ -79,7 +79,7 @@ public abstract class UpdateView<T> extends LinearLayout { this.autoUpdate = autoUpdate; setLayoutParams(new AbsListView.LayoutParams( - ViewGroup.LayoutParams.FILL_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); if(autoUpdate) { @@ -110,9 +110,15 @@ public abstract class UpdateView<T> extends LinearLayout { updateBackground(); update(); } + public void setObject(T obj1, Object obj2) { - setObject(obj1, null); + if (obj2 == null) { + setObject(obj1); + } else { + setObject(obj1, null); + } } + protected abstract void setObjectImpl(T obj); private static synchronized void startUpdater() { @@ -123,20 +129,13 @@ public abstract class UpdateView<T> extends LinearLayout { uiHandler = new Handler(); // Needed so handler is never null until thread creates it backgroundHandler = uiHandler; - updateRunnable = new Runnable() { - @Override - public void run() { - updateAll(); - } - }; + updateRunnable = UpdateView::updateAll; - new Thread(new Runnable() { - public void run() { - Looper.prepare(); - backgroundHandler = new Handler(Looper.myLooper()); - uiHandler.post(updateRunnable); - Looper.loop(); - } + new Thread(() -> { + Looper.prepare(); + backgroundHandler = new Handler(Looper.myLooper()); + uiHandler.post(updateRunnable); + Looper.loop(); }, "UpdateView").start(); } @@ -156,8 +155,8 @@ public abstract class UpdateView<T> extends LinearLayout { return; } - List<UpdateView> views = new ArrayList<UpdateView>(); - for (UpdateView view : INSTANCES.keySet()) { + List<UpdateView<?>> views = new ArrayList<>(); + for (UpdateView<?> view : INSTANCES.keySet()) { if (view.isShown()) { views.add(view); } @@ -171,32 +170,26 @@ public abstract class UpdateView<T> extends LinearLayout { Log.w(TAG, "Error when updating song views.", x); } } - private static void updateAllLive(final List<UpdateView> views) { - final Runnable runnable = new Runnable() { - @Override - public void run() { - try { - for(UpdateView view: views) { - view.update(); - } - } catch (Throwable x) { - Log.w(TAG, "Error when updating song views.", x); + private static void updateAllLive(final List<UpdateView<?>> views) { + final Runnable runnable = () -> { + try { + for(UpdateView<?> view: views) { + view.update(); } - uiHandler.postDelayed(updateRunnable, 1000L); + } catch (Throwable x) { + Log.w(TAG, "Error when updating song views.", x); } + uiHandler.postDelayed(updateRunnable, 1000L); }; - backgroundHandler.post(new Runnable() { - @Override - public void run() { - try { - for(UpdateView view: views) { - view.updateBackground(); - } - uiHandler.post(runnable); - } catch (Throwable x) { - Log.w(TAG, "Error when updating song views.", x); + backgroundHandler.post(() -> { + try { + for(UpdateView<?> view: views) { + view.updateBackground(); } + uiHandler.post(runnable); + } catch (Throwable x) { + Log.w(TAG, "Error when updating song views.", x); } }); } @@ -218,7 +211,7 @@ public abstract class UpdateView<T> extends LinearLayout { } public static MusicDirectory.Entry findEntry(MusicDirectory.Entry entry) { - for(UpdateView view: INSTANCES.keySet()) { + for(UpdateView<?> view: INSTANCES.keySet()) { MusicDirectory.Entry check = null; if(view instanceof SongView) { check = ((SongView) view).getEntry(); @@ -297,7 +290,7 @@ public abstract class UpdateView<T> extends LinearLayout { startBackgroundDrawable = child.getBackground(); child.setBackgroundColor(DrawableTint.getColorRes(context, R.attr.colorPrimary)); } else if (!checked && startBackgroundDrawable != null) { - child.setBackgroundDrawable(startBackgroundDrawable); + child.setBackground(startBackgroundDrawable); startBackgroundDrawable = null; } } @@ -311,11 +304,11 @@ public abstract class UpdateView<T> extends LinearLayout { } public static class UpdateViewHolder<T> extends RecyclerView.ViewHolder { - private UpdateView updateView; - private View view; + private UpdateView<T> updateView; + private final View view; private T item; - public UpdateViewHolder(UpdateView itemView) { + public UpdateViewHolder(UpdateView<T> itemView) { super(itemView); this.updateView = itemView; @@ -323,7 +316,7 @@ public abstract class UpdateView<T> extends LinearLayout { } // Different is so that call is not ambiguous - public UpdateViewHolder(View view, boolean different) { + public UpdateViewHolder(View view) { super(view); this.view = view; } |