Browse Source

Merge pull request #2916 from nextcloud/codacy

Further codacy fixes
Andy Scherzinger 6 years ago
parent
commit
d8ba6f3c3a
75 changed files with 462 additions and 427 deletions
  1. 2 2
      src/main/java/com/owncloud/android/MainApp.java
  2. 6 7
      src/main/java/com/owncloud/android/authentication/AccountUtils.java
  3. 19 20
      src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java
  4. 2 2
      src/main/java/com/owncloud/android/authentication/PassCodeManager.java
  5. 5 1
      src/main/java/com/owncloud/android/datamodel/MediaProvider.java
  6. 2 2
      src/main/java/com/owncloud/android/datamodel/OCFile.java
  7. 1 1
      src/main/java/com/owncloud/android/datamodel/UploadsStorageManager.java
  8. 1 1
      src/main/java/com/owncloud/android/db/OCUpload.java
  9. 2 4
      src/main/java/com/owncloud/android/files/FileMenuFilter.java
  10. 9 13
      src/main/java/com/owncloud/android/files/services/FileUploader.java
  11. 98 88
      src/main/java/com/owncloud/android/jobs/FilesSyncJob.java
  12. 4 4
      src/main/java/com/owncloud/android/media/MediaService.java
  13. 2 4
      src/main/java/com/owncloud/android/media/MediaServiceBinder.java
  14. 3 9
      src/main/java/com/owncloud/android/operations/CopyFileOperation.java
  15. 9 9
      src/main/java/com/owncloud/android/operations/DownloadFileOperation.java
  16. 2 5
      src/main/java/com/owncloud/android/operations/GetServerInfoOperation.java
  17. 2 6
      src/main/java/com/owncloud/android/operations/MoveFileOperation.java
  18. 1 2
      src/main/java/com/owncloud/android/operations/RenameFileOperation.java
  19. 1 2
      src/main/java/com/owncloud/android/operations/SynchronizeFileOperation.java
  20. 4 5
      src/main/java/com/owncloud/android/operations/SynchronizeFolderOperation.java
  21. 0 7
      src/main/java/com/owncloud/android/operations/UpdateShareViaLinkOperation.java
  22. 2 2
      src/main/java/com/owncloud/android/operations/UploadFileOperation.java
  23. 80 84
      src/main/java/com/owncloud/android/providers/FileContentProvider.java
  24. 7 12
      src/main/java/com/owncloud/android/services/OperationsService.java
  25. 11 12
      src/main/java/com/owncloud/android/syncadapter/FileSyncAdapter.java
  26. 1 1
      src/main/java/com/owncloud/android/ui/ExtendedListView.java
  27. 15 9
      src/main/java/com/owncloud/android/ui/ThemeableSwitchPreference.java
  28. 1 1
      src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java
  29. 4 8
      src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java
  30. 2 3
      src/main/java/com/owncloud/android/ui/activity/PassCodeActivity.java
  31. 13 12
      src/main/java/com/owncloud/android/ui/activity/ReceiveExternalFilesActivity.java
  32. 2 2
      src/main/java/com/owncloud/android/ui/activity/ShareActivity.java
  33. 1 1
      src/main/java/com/owncloud/android/ui/activity/StorageMigration.java
  34. 1 1
      src/main/java/com/owncloud/android/ui/activity/SyncedFoldersActivity.java
  35. 3 3
      src/main/java/com/owncloud/android/ui/activity/UploadFilesActivity.java
  36. 1 1
      src/main/java/com/owncloud/android/ui/adapter/ActivityListAdapter.java
  37. 1 1
      src/main/java/com/owncloud/android/ui/adapter/LocalFileListAdapter.java
  38. 1 1
      src/main/java/com/owncloud/android/ui/adapter/UploadListAdapter.java
  39. 0 1
      src/main/java/com/owncloud/android/ui/adapter/X509CertificateViewAdapter.java
  40. 1 1
      src/main/java/com/owncloud/android/ui/dialog/SamlWebViewDialog.java
  41. 0 2
      src/main/java/com/owncloud/android/ui/dialog/SendShareDialog.java
  42. 1 2
      src/main/java/com/owncloud/android/ui/dialog/SetupEncryptionDialogFragment.java
  43. 3 4
      src/main/java/com/owncloud/android/ui/dialog/ShareLinkToDialog.java
  44. 1 1
      src/main/java/com/owncloud/android/ui/dialog/SortingOrderDialogFragment.java
  45. 1 1
      src/main/java/com/owncloud/android/ui/dialog/SslValidatorDialog.java
  46. 2 2
      src/main/java/com/owncloud/android/ui/dialog/SyncedFolderPreferencesDialogFragment.java
  47. 3 3
      src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java
  48. 5 6
      src/main/java/com/owncloud/android/ui/fragment/FileDetailFragment.java
  49. 4 4
      src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java
  50. 5 1
      src/main/java/com/owncloud/android/ui/fragment/util/SharingMenuHelper.java
  51. 1 1
      src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java
  52. 1 1
      src/main/java/com/owncloud/android/ui/helpers/UriUploader.java
  53. 5 1
      src/main/java/com/owncloud/android/ui/notifications/NotificationUtils.java
  54. 2 2
      src/main/java/com/owncloud/android/ui/preview/FileDownloadFragment.java
  55. 1 1
      src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java
  56. 6 5
      src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.java
  57. 1 1
      src/main/java/com/owncloud/android/ui/preview/PreviewMediaFragment.java
  58. 6 4
      src/main/java/com/owncloud/android/utils/BitmapUtils.java
  59. 5 1
      src/main/java/com/owncloud/android/utils/ConnectivityUtils.java
  60. 5 1
      src/main/java/com/owncloud/android/utils/CsrHelper.java
  61. 5 1
      src/main/java/com/owncloud/android/utils/DeviceCredentialUtils.java
  62. 7 5
      src/main/java/com/owncloud/android/utils/DisplayUtils.java
  63. 5 1
      src/main/java/com/owncloud/android/utils/EncryptionUtils.java
  64. 6 1
      src/main/java/com/owncloud/android/utils/ErrorMessageAdapter.java
  65. 5 1
      src/main/java/com/owncloud/android/utils/FileStorageUtils.java
  66. 7 3
      src/main/java/com/owncloud/android/utils/FilesSyncHelper.java
  67. 3 0
      src/main/java/com/owncloud/android/utils/MimeType.java
  68. 13 9
      src/main/java/com/owncloud/android/utils/MimeTypeUtil.java
  69. 5 1
      src/main/java/com/owncloud/android/utils/PermissionUtil.java
  70. 5 1
      src/main/java/com/owncloud/android/utils/PowerUtils.java
  71. 7 3
      src/main/java/com/owncloud/android/utils/ReceiversHelper.java
  72. 5 1
      src/main/java/com/owncloud/android/utils/ThemeUtils.java
  73. 7 4
      src/main/java/com/owncloud/android/utils/UriUtils.java
  74. 1 1
      src/main/java/org/nextcloud/providers/cursors/FileCursor.java
  75. 1 1
      src/main/java/org/nextcloud/providers/cursors/RootCursor.java

+ 2 - 2
src/main/java/com/owncloud/android/MainApp.java

@@ -109,7 +109,7 @@ public class MainApp extends MultiDexApplication {
 
     private static String storagePath;
 
-    private static boolean mOnlyOnDevice = false;
+    private static boolean mOnlyOnDevice;
 
     private SharedPreferences appPrefs;
     @SuppressWarnings("unused")
@@ -154,7 +154,7 @@ public class MainApp extends MultiDexApplication {
             Log_OC.d("Debug", "start logging");
         }
 
-        if (Build.VERSION.SDK_INT >= 24) {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
             try {
                 Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
                 m.invoke(null);

+ 6 - 7
src/main/java/com/owncloud/android/authentication/AccountUtils.java

@@ -15,7 +15,6 @@
  *
  *   You should have received a copy of the GNU General Public License
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
  */
 
 package com.owncloud.android.authentication;
@@ -34,12 +33,14 @@ import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
 import com.owncloud.android.ui.activity.ManageAccountsActivity;
 
-
-public class AccountUtils {
+/**
+ * Helper class for dealing with accounts.
+ */
+public final class AccountUtils {
     private static final String PREF_SELECT_OC_ACCOUNT = "select_oc_account";
 
     public static final int ACCOUNT_VERSION = 1;
-    public static final int ACCOUNT_VERSION_WITH_PROPER_ID = 2;
+    //public static final int ACCOUNT_VERSION_WITH_PROPER_ID = 2;
     public static final String ACCOUNT_USES_STANDARD_PASSWORD = "ACCOUNT_USES_STANDARD_PASSWORD";
 
     private AccountUtils() {
@@ -152,10 +153,8 @@ public class AccountUtils {
     public static boolean setCurrentOwnCloudAccount(final Context context, String accountName) {
         boolean result = false;
         if (accountName != null) {
-            boolean found;
             for (final Account account : getAccounts(context)) {
-                found = (account.name.equals(accountName));
-                if (found) {
+                if (accountName.equals(account.name)) {
                     SharedPreferences.Editor appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
                     appPrefs.putString(PREF_SELECT_OC_ACCOUNT, accountName);
                     appPrefs.apply();

+ 19 - 20
src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java

@@ -188,6 +188,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     public static final String REGULAR_SERVER_INPUT_TYPE = "regular";
     public static final String SUBDOMAIN_SERVER_INPUT_TYPE = "prefix";
     public static final String DIRECTORY_SERVER_INPUT_TYPE = "suffix";
+    public static final int NO_ICON = 0;
+    public static final String EMPTY_STRING = "";
 
     /// parameters from EXTRAs in starter Intent
     private byte mAction;
@@ -196,8 +198,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
     /// activity-level references / state
     private final Handler mHandler = new Handler();
-    private ServiceConnection mOperationsServiceConnection = null;
-    private OperationsServiceBinder mOperationsServiceBinder = null;
+    private ServiceConnection mOperationsServiceConnection;
+    private OperationsServiceBinder mOperationsServiceBinder;
     private AccountManager mAccountMgr;
     private Uri mNewCapturedUriFromOAuth2Redirection;
 
@@ -207,7 +209,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     private TextView mServerStatusView;
 
     private TextWatcher mHostUrlInputWatcher;
-    private String mServerStatusText = "";
+    private String mServerStatusText = EMPTY_STRING;
     private int mServerStatusIcon;
 
     private boolean mServerIsChecked;
@@ -227,10 +229,10 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
     private WebView mLoginWebView;
 
-    private String mAuthStatusText = "";
+    private String mAuthStatusText = EMPTY_STRING;
     private int mAuthStatusIcon;
 
-    private String mAuthToken = "";
+    private String mAuthToken = EMPTY_STRING;
     private AuthenticatorAsyncTask mAsyncTask;
 
     private boolean mIsFirstAuthAttempt;
@@ -547,7 +549,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         if (dataString.length() < prefix.length()) {
             throw new IllegalArgumentException("Invalid login URL detected");
         }
-        LoginUrlInfo loginUrlInfo = new LoginUrlInfo();
 
         // format is basically xxx://login/server:xxx&user:xxx&password while all variables are optional
         String data = dataString.substring(prefix.length());
@@ -560,6 +561,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             throw new IllegalArgumentException("Illegal number of login URL elements detected: " + values.length);
         }
 
+        LoginUrlInfo loginUrlInfo = new LoginUrlInfo();
+
         for (String value : values) {
             if (value.startsWith("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
                 loginUrlInfo.username = URLDecoder.decode(
@@ -754,7 +757,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
                     if (mAuthStatusIcon != 0) {
                         Log_OC.d(TAG, "onTextChanged: hiding authentication status");
                         mAuthStatusIcon = 0;
-                        mAuthStatusText = "";
+                        mAuthStatusText = EMPTY_STRING;
                         showAuthStatus();
                     }
                 }
@@ -815,7 +818,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             mUsernameInput.setEnabled(false);
             mUsernameInput.setFocusable(false);
         }
-        mPasswordInput.setText(""); // clean password to avoid social hacking
+        mPasswordInput.setText(EMPTY_STRING); // clean password to avoid social hacking
         if (isPasswordExposed) {
             showPassword();
         }
@@ -1179,7 +1182,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             }
 
         } else {
-            mServerStatusText = "";
+            mServerStatusText = EMPTY_STRING;
             mServerStatusIcon = 0;
             if (!webViewLoginMethod) {
                 showServerStatus();
@@ -1403,7 +1406,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
                 if (!webViewLoginMethod && !mUsernameInput.getText().toString().trim().equals(username)) {
                     // fail - not a new account, but an existing one; disallow
                     result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
-                    mAuthToken = "";
+                    mAuthToken = EMPTY_STRING;
                     updateAuthStatusIconAndText(result);
                     showAuthStatus();
                     Log_OC.d(TAG, result.getLogMessage());
@@ -1622,7 +1625,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
                 mServerStatusText = getResources().getString(R.string.untrusted_domain);
                 break;
             default:
-                mServerStatusText = "";
+                mServerStatusText = EMPTY_STRING;
                 mServerStatusIcon = 0;
                 break;
         }
@@ -1718,7 +1721,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         }
     }
 
-
     /**
      * Processes the result of the access check performed to try the user credentials.
      *
@@ -1790,7 +1792,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             updateServerStatusIconAndText(result);
             showServerStatus();
             mAuthStatusIcon = 0;
-            mAuthStatusText = "";
+            mAuthStatusText = EMPTY_STRING;
             if (!webViewLoginMethod) {
                 showAuthStatus();
 
@@ -1823,7 +1825,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         }
     }
 
-
     /**
      * Updates the authentication token.
      *
@@ -1873,7 +1874,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
     }
 
-
     /**
      * Creates a new account through the Account Authenticator that started this activity.
      *
@@ -1922,7 +1922,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
             if (isOAuth || isSaml) {
                 // with external authorizations, the password is never input in the app
-                mAccountMgr.addAccountExplicitly(mAccount, "", null);
+                mAccountMgr.addAccountExplicitly(mAccount, EMPTY_STRING, null);
             } else {
                 if (!webViewLoginMethod) {
                     mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
@@ -1983,12 +1983,13 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         }
     }
 
+    /**
     /**
      * Updates the content and visibility state of the icon and text associated
      * to the last check on the ownCloud server.
      */
     private void showServerStatus() {
-        if (mServerStatusIcon == 0 && "".equals(mServerStatusText)) {
+        if (mServerStatusIcon == NO_ICON && EMPTY_STRING.equals(mServerStatusText)) {
             mServerStatusView.setVisibility(View.INVISIBLE);
         } else {
             mServerStatusView.setText(mServerStatusText);
@@ -1997,13 +1998,12 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         }
     }
 
-
     /**
      * Updates the content and visibility state of the icon and text associated
      * to the interactions with the OAuth authorization server.
      */
     private void showAuthStatus() {
-        if (mAuthStatusIcon == 0 && "".equals(mAuthStatusText)) {
+        if (mAuthStatusIcon == NO_ICON && EMPTY_STRING.equals(mAuthStatusText)) {
             mAuthStatusView.setVisibility(View.INVISIBLE);
         } else {
             mAuthStatusView.setText(mAuthStatusText);
@@ -2012,7 +2012,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         }
     }
 
-
     private void showRefreshButton(boolean show) {
         if (webViewLoginMethod && mRefreshButton != null) {
             if (show) {

+ 2 - 2
src/main/java/com/owncloud/android/authentication/PassCodeManager.java

@@ -53,10 +53,10 @@ public class PassCodeManager {
     private static final int PASS_CODE_TIMEOUT = 1000;
         // keeping a "low" positive value is the easiest way to prevent the pass code is requested on rotations
 
-    private static PassCodeManager passCodeManagerInstance = null;
+    private static PassCodeManager passCodeManagerInstance;
 
     private Long timestamp = 0L;
-    private int visibleActivitiesCounter = 0;
+    private int visibleActivitiesCounter;
 
     public static PassCodeManager getPassCodeManager() {
         if (passCodeManagerInstance == null) {

+ 5 - 1
src/main/java/com/owncloud/android/datamodel/MediaProvider.java

@@ -44,7 +44,7 @@ import javax.annotation.Nullable;
 /**
  * Media queries to gain access to media lists for the device.
  */
-public class MediaProvider {
+public final class MediaProvider {
     private static final String TAG = MediaProvider.class.getSimpleName();
 
     // fixed query parameters
@@ -58,6 +58,10 @@ public class MediaProvider {
     private static final String[] VIDEOS_FOLDER_PROJECTION = {"Distinct " + MediaStore.Video.Media.BUCKET_ID,
             MediaStore.Video.Media.BUCKET_DISPLAY_NAME};
 
+    private MediaProvider() {
+        // utility class -> private constructor
+    }
+
     /**
      * Getting All Images Paths.
      *

+ 2 - 2
src/main/java/com/owncloud/android/datamodel/OCFile.java

@@ -466,8 +466,8 @@ public class OCFile implements Parcelable, Comparable<OCFile>, ServerFileInterfa
         Log_OC.d(TAG, "OCFile name changing from " + mRemotePath);
         if (name != null && name.length() > 0 && !name.contains(PATH_SEPARATOR) &&
                 !mRemotePath.equals(ROOT_PATH)) {
-            String parent = (new File(this.getRemotePath())).getParent();
-            parent = (parent.endsWith(PATH_SEPARATOR)) ? parent : parent + PATH_SEPARATOR;
+            String parent = new File(this.getRemotePath()).getParent();
+            parent = parent.endsWith(PATH_SEPARATOR) ? parent : parent + PATH_SEPARATOR;
             mRemotePath = parent + name;
             if (isFolder()) {
                 mRemotePath += PATH_SEPARATOR;

+ 1 - 1
src/main/java/com/owncloud/android/datamodel/UploadsStorageManager.java

@@ -275,7 +275,7 @@ public class UploadsStorageManager extends Observable {
         return getUploads(null, null);
     }
 
-    private OCUpload[] getUploads(@Nullable String selection, @Nullable String[] selectionArgs) {
+    private OCUpload[] getUploads(@Nullable String selection, @Nullable String... selectionArgs) {
         OCUpload[] list;
 
         Cursor c = getDB().query(

+ 1 - 1
src/main/java/com/owncloud/android/db/OCUpload.java

@@ -353,7 +353,7 @@ public class OCUpload implements Parcelable {
                     (getLastResult() == null ? "null" : getLastResult().getValue());
         } catch (NullPointerException e) {
             Log_OC.d(TAG, "Exception " + e.toString());
-            return (e.toString());
+            return e.toString();
         }
     }
 

+ 2 - 4
src/main/java/com/owncloud/android/files/FileMenuFilter.java

@@ -363,11 +363,9 @@ public class FileMenuFilter {
             OperationsServiceBinder opsBinder = mComponentsGetter.getOperationsServiceBinder();
             FileUploaderBinder uploaderBinder = mComponentsGetter.getFileUploaderBinder();
             FileDownloaderBinder downloaderBinder = mComponentsGetter.getFileDownloaderBinder();
-            synchronizing = (
-                    anyFileSynchronizing(opsBinder) ||      // comparing local and remote
+            synchronizing = anyFileSynchronizing(opsBinder) ||      // comparing local and remote
                             anyFileDownloading(downloaderBinder) ||
-                            anyFileUploading(uploaderBinder)
-            );
+                            anyFileUploading(uploaderBinder);
         }
         return synchronizing;
     }

+ 9 - 13
src/main/java/com/owncloud/android/files/services/FileUploader.java

@@ -399,11 +399,10 @@ public class FileUploader extends Service
             boolean isPowerSaving = PowerUtils.isPowerSaveMode(context);
 
             for ( OCUpload failedUpload: failedUploads) {
-                accountMatch = (account == null || account.name.equals(failedUpload.getAccountName()));
-                resultMatch = ((uploadResult == null || uploadResult.equals(failedUpload.getLastResult())));
+                accountMatch = account == null || account.name.equals(failedUpload.getAccountName());
+                resultMatch = uploadResult == null || uploadResult.equals(failedUpload.getLastResult());
                 if (accountMatch && resultMatch) {
-                    if (currentAccount == null ||
-                            !currentAccount.name.equals(failedUpload.getAccountName())) {
+                    if (currentAccount == null || !currentAccount.name.equals(failedUpload.getAccountName())) {
                         currentAccount = failedUpload.getAccount(context);
                     }
 
@@ -572,12 +571,6 @@ public class FileUploader extends Service
                 mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
             }
 
-            boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
-            int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
-
-            boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
-            int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
-
             if (intent.hasExtra(KEY_FILE) && files == null) {
                 Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
                 return Service.START_NOT_STICKY;
@@ -612,6 +605,10 @@ public class FileUploader extends Service
             }
             // at this point variable "OCFile[] files" is loaded correctly.
 
+            boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
+            int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
+            boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
+            int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
             String uploadKey;
             UploadFileOperation newUpload;
             try {
@@ -1217,15 +1214,14 @@ public class FileUploader extends Service
             !uploadResult.getCode().equals(ResultCode.DELAYED_IN_POWER_SAVE_MODE) &&
             !uploadResult.getCode().equals(ResultCode.LOCK_FAILED)    ) {
 
-            int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker :
+            int tickerId = uploadResult.isSuccess() ? R.string.uploader_upload_succeeded_ticker :
                     R.string.uploader_upload_failed_ticker;
 
             String content;
 
             // check credentials error
             boolean needsToUpdateCredentials = ResultCode.UNAUTHORIZED.equals(uploadResult.getCode());
-            tickerId = (needsToUpdateCredentials) ?
-                    R.string.uploader_upload_failed_credentials_error : tickerId;
+            tickerId = needsToUpdateCredentials ? R.string.uploader_upload_failed_credentials_error : tickerId;
 
             mNotificationBuilder
                     .setTicker(getString(tickerId))

+ 98 - 88
src/main/java/com/owncloud/android/jobs/FilesSyncJob.java

@@ -47,6 +47,7 @@ import com.owncloud.android.operations.UploadFileOperation;
 import com.owncloud.android.ui.activity.Preferences;
 import com.owncloud.android.utils.FileStorageUtils;
 import com.owncloud.android.utils.FilesSyncHelper;
+import com.owncloud.android.utils.MimeType;
 import com.owncloud.android.utils.MimeTypeUtil;
 import com.owncloud.android.utils.PowerUtils;
 
@@ -65,7 +66,6 @@ import java.util.TimeZone;
  */
 public class FilesSyncJob extends Job {
     public static final String TAG = "FilesSyncJob";
-
     public static final String SKIP_CUSTOM = "skipCustom";
     public static final String OVERRIDE_POWER_SAVING = "overridePowerSaving";
 
@@ -73,8 +73,6 @@ public class FilesSyncJob extends Job {
     @Override
     protected Result onRunJob(@NonNull Params params) {
         final Context context = MainApp.getAppContext();
-        final ContentResolver contentResolver = context.getContentResolver();
-        FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
         PowerManager.WakeLock wakeLock = null;
 
         if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
@@ -84,7 +82,6 @@ public class FilesSyncJob extends Job {
         }
 
         PersistableBundleCompat bundle = params.getExtras();
-        final boolean skipCustom = bundle.getBoolean(SKIP_CUSTOM, false);
         final boolean overridePowerSaving = bundle.getBoolean(OVERRIDE_POWER_SAVING, false);
 
         // If we are in power save mode, better to postpone upload
@@ -96,110 +93,123 @@ public class FilesSyncJob extends Job {
         Resources resources = MainApp.getAppContext().getResources();
         boolean lightVersion = resources.getBoolean(R.bool.syncedFolder_light);
 
+        final boolean skipCustom = bundle.getBoolean(SKIP_CUSTOM, false);
         FilesSyncHelper.restartJobsIfNeeded();
         FilesSyncHelper.insertAllDBEntries(skipCustom);
 
         // Create all the providers we'll need
+        final ContentResolver contentResolver = context.getContentResolver();
         final FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
         SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver);
 
+        Locale currentLocale = context.getResources().getConfiguration().locale;
+        SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale);
+        sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
+        FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
+
         for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
             if ((syncedFolder.isEnabled()) && (!skipCustom || MediaFolderType.CUSTOM != syncedFolder.getType())) {
-                for (String path : filesystemDataProvider.getFilesForUpload(syncedFolder.getLocalPath(),
-                        Long.toString(syncedFolder.getId()))) {
-                    File file = new File(path);
-
-                    Long lastModificationTime = file.lastModified();
-                    final Locale currentLocale = context.getResources().getConfiguration().locale;
-
-                    if (MediaFolderType.IMAGE == syncedFolder.getType()) {
-                        String mimeTypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath());
-                        if ("image/jpeg".equalsIgnoreCase(mimeTypeString) || "image/tiff".
-                                equalsIgnoreCase(mimeTypeString)) {
-                            try {
-                                ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
-                                String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
-                                if (!TextUtils.isEmpty(exifDate)) {
-                                    ParsePosition pos = new ParsePosition(0);
-                                    SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss",
-                                            currentLocale);
-                                    sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
-                                    Date dateTime = sFormatter.parse(exifDate, pos);
-                                    lastModificationTime = dateTime.getTime();
-                                }
-
-                            } catch (Exception e) {
-                                Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage());
-                            }
-                        }
-                    }
-
-                    String mimeType = MimeTypeUtil.getBestMimeTypeByFilename(file.getAbsolutePath());
-
-                    Account account = AccountUtils.getOwnCloudAccountByName(context, syncedFolder.getAccount());
+                syncFolder(context, resources, lightVersion, filesystemDataProvider, currentLocale, sFormatter,
+                        requester, syncedFolder);
+            }
+        }
 
-                    String remotePath;
-                    boolean subfolderByDate;
-                    Integer uploadAction;
-                    boolean needsCharging;
-                    boolean needsWifi;
+        if (wakeLock != null) {
+            wakeLock.release();
+        }
 
-                    if (lightVersion) {
-                        ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(
-                                context.getContentResolver());
+        return Result.SUCCESS;
+    }
 
-                        needsCharging = resources.getBoolean(R.bool.syncedFolder_light_on_charging);
-                        needsWifi = account == null || arbitraryDataProvider.getBooleanValue(account.name,
-                                Preferences.SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI);
-                        String uploadActionString = resources.getString(R.string.syncedFolder_light_upload_behaviour);
-                        uploadAction = getUploadAction(uploadActionString);
+    private void syncFolder(Context context, Resources resources, boolean lightVersion,
+                            FilesystemDataProvider filesystemDataProvider, Locale currentLocale,
+                            SimpleDateFormat sFormatter, FileUploader.UploadRequester requester,
+                            SyncedFolder syncedFolder) {
+        String remotePath;
+        boolean subfolderByDate;
+        Integer uploadAction;
+        boolean needsCharging;
+        boolean needsWifi;
+        Account account = AccountUtils.getOwnCloudAccountByName(context, syncedFolder.getAccount());
+
+        for (String path : filesystemDataProvider.getFilesForUpload(syncedFolder.getLocalPath(),
+                Long.toString(syncedFolder.getId()))) {
+            File file = new File(path);
+            Long lastModificationTime = calculateLastModificationTime(file, syncedFolder, sFormatter);
+            String mimeType = MimeTypeUtil.getBestMimeTypeByFilename(file.getAbsolutePath());
+
+            if (lightVersion) {
+                ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(
+                        context.getContentResolver());
+
+                needsCharging = resources.getBoolean(R.bool.syncedFolder_light_on_charging);
+                needsWifi = account == null || arbitraryDataProvider.getBooleanValue(account.name,
+                        Preferences.SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI);
+                String uploadActionString = resources.getString(R.string.syncedFolder_light_upload_behaviour);
+                uploadAction = getUploadAction(uploadActionString);
+
+                subfolderByDate = resources.getBoolean(R.bool.syncedFolder_light_use_subfolders);
+
+                remotePath = resources.getString(R.string.syncedFolder_remote_folder);
+            } else {
+                needsCharging = syncedFolder.getChargingOnly();
+                needsWifi = syncedFolder.getWifiOnly();
+                uploadAction = syncedFolder.getUploadAction();
+                subfolderByDate = syncedFolder.getSubfolderByDate();
+                remotePath = syncedFolder.getRemotePath();
+            }
 
-                        subfolderByDate = resources.getBoolean(R.bool.syncedFolder_light_use_subfolders);
+            if (!subfolderByDate) {
+                String adaptedPath = file.getAbsolutePath()
+                        .replace(syncedFolder.getLocalPath(), "")
+                        .replace("/" + file.getName(), "");
+                remotePath += adaptedPath;
+            }
 
-                        remotePath = resources.getString(R.string.syncedFolder_remote_folder);
-                    } else {
-                        needsCharging = syncedFolder.getChargingOnly();
-                        needsWifi = syncedFolder.getWifiOnly();
-                        uploadAction = syncedFolder.getUploadAction();
-                        subfolderByDate = syncedFolder.getSubfolderByDate();
-                        remotePath = syncedFolder.getRemotePath();
-                    }
+            requester.uploadFileWithOverwrite(
+                    context,
+                    account,
+                    file.getAbsolutePath(),
+                    FileStorageUtils.getInstantUploadFilePath(
+                            currentLocale,
+                            remotePath, file.getName(),
+                            lastModificationTime, subfolderByDate),
+                    uploadAction,
+                    mimeType,
+                    true,           // create parent folder if not existent
+                    UploadFileOperation.CREATED_AS_INSTANT_PICTURE,
+                    needsWifi,
+                    needsCharging,
+                    true
+            );
+
+            filesystemDataProvider.updateFilesystemFileAsSentForUpload(path,
+                    Long.toString(syncedFolder.getId()));
+        }
+    }
 
-                    if (!subfolderByDate) {
-                        String adaptedPath = file.getAbsolutePath()
-                                .replace(syncedFolder.getLocalPath(), "")
-                                .replace("/" + file.getName(), "");
-                        remotePath += adaptedPath;
+    private Long calculateLastModificationTime(File file, SyncedFolder syncedFolder, SimpleDateFormat formatter) {
+        Long lastModificationTime = file.lastModified();
+
+        if (MediaFolderType.IMAGE == syncedFolder.getType()) {
+            String mimeTypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath());
+            if (MimeType.JPEG.equalsIgnoreCase(mimeTypeString)
+                    || MimeType.TIFF.equalsIgnoreCase(mimeTypeString)) {
+                try {
+                    ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
+                    String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
+                    if (!TextUtils.isEmpty(exifDate)) {
+                        ParsePosition pos = new ParsePosition(0);
+                        Date dateTime = formatter.parse(exifDate, pos);
+                        lastModificationTime = dateTime.getTime();
                     }
-
-                    requester.uploadFileWithOverwrite(
-                            context,
-                            account,
-                            file.getAbsolutePath(),
-                            FileStorageUtils.getInstantUploadFilePath(
-                                    currentLocale,
-                                    remotePath, file.getName(),
-                                    lastModificationTime, subfolderByDate),
-                            uploadAction,
-                            mimeType,
-                            true,           // create parent folder if not existent
-                            UploadFileOperation.CREATED_AS_INSTANT_PICTURE,
-                            needsWifi,
-                            needsCharging,
-                            true
-                    );
-
-                    filesystemDataProvider.updateFilesystemFileAsSentForUpload(path,
-                            Long.toString(syncedFolder.getId()));
+                } catch (Exception e) {
+                    Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage());
                 }
             }
         }
 
-        if (wakeLock != null) {
-            wakeLock.release();
-        }
-
-        return Result.SUCCESS;
+        return lastModificationTime;
     }
 
     private Integer getUploadAction(String action) {

+ 4 - 4
src/main/java/com/owncloud/android/media/MediaService.java

@@ -100,10 +100,10 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     private static final float DUCK_VOLUME = 0.1f;
 
     /** Media player instance */
-    private MediaPlayer mPlayer = null;
+    private MediaPlayer mPlayer;
 
     /** Reference to the system AudioManager */
-    private AudioManager mAudioManager = null;
+    private AudioManager mAudioManager;
 
 
     /** Values to indicate the state of the service */
@@ -426,9 +426,9 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     private void tryToGetAudioFocus() {
         if (mAudioFocus != AudioFocus.FOCUS
                 && mAudioManager != null
-                && (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus(this,
+                && AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus(this,
                 AudioManager.STREAM_MUSIC,
-                AudioManager.AUDIOFOCUS_GAIN))
+                AudioManager.AUDIOFOCUS_GAIN)
                 ) {
             mAudioFocus = AudioFocus.FOCUS;
         }

+ 2 - 4
src/main/java/com/owncloud/android/media/MediaServiceBinder.java

@@ -118,7 +118,7 @@ public class MediaServiceBinder extends Binder implements MediaController.MediaP
     @Override
     public boolean isPlaying() {
         MediaService.State currentState = mService.getState();
-        return (currentState == State.PLAYING || (currentState == State.PREPARING && mService.mPlayOnPrepared));
+        return currentState == State.PLAYING || (currentState == State.PREPARING && mService.mPlayOnPrepared);
     }
 
 
@@ -169,15 +169,13 @@ public class MediaServiceBinder extends Binder implements MediaController.MediaP
 
     public boolean isInPlaybackState() {
         MediaService.State currentState = mService.getState();
-        return (currentState == MediaService.State.PLAYING || currentState == MediaService.State.PAUSED);
+        return currentState == MediaService.State.PLAYING || currentState == MediaService.State.PAUSED;
     }
 
-
     @Override
     public int getAudioSessionId() {
         return 1; // not really used
     }
-
 }
 
 

+ 3 - 9
src/main/java/com/owncloud/android/operations/CopyFileOperation.java

@@ -1,4 +1,4 @@
-    /* ownCloud Android client application
+/*   ownCloud Android client application
  *   Copyright (C) 2012-2014 ownCloud Inc.
  *
  *   This program is free software: you can redistribute it and/or modify
@@ -12,7 +12,6 @@
  *
  *   You should have received a copy of the GNU General Public License
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
  */
 
 package com.owncloud.android.operations;
@@ -36,10 +35,8 @@ public class CopyFileOperation extends SyncOperation {
 
     private String mSrcPath;
     private String mTargetParentPath;
-
     private OCFile mFile;
 
-
     /**
      * Constructor
      *
@@ -63,8 +60,6 @@ public class CopyFileOperation extends SyncOperation {
      */
     @Override
     protected RemoteOperationResult run(OwnCloudClient client) {
-        RemoteOperationResult result;
-
         /// 1. check copy validity
         if (mTargetParentPath.startsWith(mSrcPath)) {
             return new RemoteOperationResult(ResultCode.INVALID_COPY_INTO_DESCENDANT);
@@ -84,7 +79,8 @@ public class CopyFileOperation extends SyncOperation {
                 targetPath,
                 false
         );
-        result = operation.execute(client);
+
+        RemoteOperationResult result = operation.execute(client);
 
         /// 3. local copy
         if (result.isSuccess()) {
@@ -94,6 +90,4 @@ public class CopyFileOperation extends SyncOperation {
 
         return result;
     }
-
-
 }

+ 9 - 9
src/main/java/com/owncloud/android/operations/DownloadFileOperation.java

@@ -154,21 +154,21 @@ public class DownloadFileOperation extends RemoteOperation {
 
     @Override
     protected RemoteOperationResult run(OwnCloudClient client) {
-        RemoteOperationResult result;
-        File newFile;
-        boolean moved;
-        
-        /// download will be performed to a temporal file, then moved to the final location
-        File tmpFile = new File(getTmpPath());
-        
-        String tmpFolder =  getTmpFolder();
-        
         /// perform the download
         synchronized(mCancellationRequested) {
             if (mCancellationRequested.get()) {
                 return new RemoteOperationResult(new OperationCancelledException());
             }
         }
+
+        RemoteOperationResult result;
+        File newFile;
+        boolean moved;
+
+        /// download will be performed to a temporal file, then moved to the final location
+        File tmpFile = new File(getTmpPath());
+
+        String tmpFolder =  getTmpFolder();
         
         mDownloadOperation = new DownloadRemoteFileOperation(mFile.getRemotePath(), tmpFolder);
         Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();

+ 2 - 5
src/main/java/com/owncloud/android/operations/GetServerInfoOperation.java

@@ -49,7 +49,6 @@ public class GetServerInfoOperation extends RemoteOperation {
     
     private String mUrl;
     private Context mContext;
-    
     private ServerInfo mResultData;
 
     /** 
@@ -62,11 +61,9 @@ public class GetServerInfoOperation extends RemoteOperation {
     public GetServerInfoOperation(String url, Context context) {
         mUrl = trimWebdavSuffix(url);
         mContext = context;
-        
         mResultData = new ServerInfo();
     }
     
-    
     /**
      * Performs the operation
      * 
@@ -143,10 +140,10 @@ public class GetServerInfoOperation extends RemoteOperation {
     
     
     public static class ServerInfo {
-        public OwnCloudVersion mVersion = null;
+        public OwnCloudVersion mVersion;
         public String mBaseUrl = "";
         public AuthenticationMethod mAuthMethod = AuthenticationMethod.UNKNOWN;
-        public boolean mIsSslConn = false;
+        public boolean mIsSslConn;
     }
 	
 }

+ 2 - 6
src/main/java/com/owncloud/android/operations/MoveFileOperation.java

@@ -1,4 +1,4 @@
-/**
+/*
  *   ownCloud Android client application
  *
  *   @author David A. Velasco
@@ -15,7 +15,6 @@
  *
  *   You should have received a copy of the GNU General Public License
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
  */
 
 package com.owncloud.android.operations;
@@ -37,7 +36,6 @@ public class MoveFileOperation extends SyncOperation {
     
     private String mSrcPath;
     private String mTargetParentPath;
-    
     private OCFile mFile;
     
     /**
@@ -63,8 +61,6 @@ public class MoveFileOperation extends SyncOperation {
      */
     @Override
     protected RemoteOperationResult run(OwnCloudClient client) {
-        RemoteOperationResult result;
-        
         /// 1. check move validity
         if (mTargetParentPath.startsWith(mSrcPath)) {
             return new RemoteOperationResult(ResultCode.INVALID_MOVE_INTO_DESCENDANT);
@@ -84,7 +80,7 @@ public class MoveFileOperation extends SyncOperation {
                 targetPath, 
                 false
         );
-        result = operation.execute(client);
+        RemoteOperationResult result = operation.execute(client);
         
         /// 3. local move
         if (result.isSuccess()) {

+ 1 - 2
src/main/java/com/owncloud/android/operations/RenameFileOperation.java

@@ -82,8 +82,7 @@ public class RenameFileOperation extends SyncOperation {
                 return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME);
             }
             String parent = (new File(mFile.getRemotePath())).getParent();
-            parent = (parent.endsWith(OCFile.PATH_SEPARATOR)) ? parent : parent +
-                    OCFile.PATH_SEPARATOR;
+            parent = parent.endsWith(OCFile.PATH_SEPARATOR) ? parent : parent + OCFile.PATH_SEPARATOR;
             mNewRemotePath =  parent + mNewName;
             if (mFile.isFolder()) {
                 mNewRemotePath += OCFile.PATH_SEPARATOR;

+ 1 - 2
src/main/java/com/owncloud/android/operations/SynchronizeFileOperation.java

@@ -50,8 +50,7 @@ public class SynchronizeFileOperation extends SyncOperation {
     private Account mAccount;
     private boolean mSyncFileContents;
     private Context mContext;
-
-    private boolean mTransferWasRequested = false;
+    private boolean mTransferWasRequested;
 
     /**
      * When 'false', uploads to the server are not done; only downloads or conflict detection.

+ 4 - 5
src/main/java/com/owncloud/android/operations/SynchronizeFolderOperation.java

@@ -172,7 +172,6 @@ public class SynchronizeFolderOperation extends SyncOperation {
         Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
 
         mRemoteFolderChanged = true;
-        RemoteOperationResult result;
         
         if (mCancellationRequested.get()) {
             throw new OperationCancelledException();
@@ -180,7 +179,7 @@ public class SynchronizeFolderOperation extends SyncOperation {
         
         // remote request
         ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
-        result = operation.execute(client);
+        RemoteOperationResult result = operation.execute(client);
         if (result.isSuccess()) {
             OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
 
@@ -261,8 +260,6 @@ public class SynchronizeFolderOperation extends SyncOperation {
      * @param folderAndFiles Remote folder and children files in Folder
      */
     private void synchronizeData(List<Object> folderAndFiles) throws OperationCancelledException {
-        FileDataStorageManager storageManager = getStorageManager();
-        
         // parse data from remote folder
         OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
         remoteFolder.setParentId(mLocalFolder.getParentId());
@@ -271,7 +268,6 @@ public class SynchronizeFolderOperation extends SyncOperation {
         Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
                 + " changed - starting update of local data ");
 
-        List<OCFile> updatedFiles = new Vector<>(folderAndFiles.size() - 1);
         mFilesForDirectDownload.clear();
         mFilesToSyncContents.clear();
 
@@ -279,6 +275,9 @@ public class SynchronizeFolderOperation extends SyncOperation {
             throw new OperationCancelledException();
         }
 
+        FileDataStorageManager storageManager = getStorageManager();
+        List<OCFile> updatedFiles = new Vector<>(folderAndFiles.size() - 1);
+
         // get current data about local contents of the folder to synchronize
         List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder, false);
         Map<String, OCFile> localFilesMap = new HashMap<>(localFiles.size());

+ 0 - 7
src/main/java/com/owncloud/android/operations/UpdateShareViaLinkOperation.java

@@ -48,14 +48,10 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
      * @param path          Full path of the file/folder being shared. Mandatory argument
      */
     public UpdateShareViaLinkOperation(String path) {
-
         mPath = path;
-        mPassword = null;
         mExpirationDateInMillis = 0;
-        mPublicUpload = null;
     }
 
-
     /**
      * Set password to update in public link.
      *
@@ -67,7 +63,6 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
         mPassword = password;
     }
 
-
     /**
      * Set expiration date to update in Share resource.
      *
@@ -90,7 +85,6 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
         mPublicUpload = publicUpload;
     }
 
-
     @Override
     protected RemoteOperationResult run(OwnCloudClient client) {
 
@@ -157,6 +151,5 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
             getStorageManager().saveFile(file);
         }
     }
-
 }
 

+ 2 - 2
src/main/java/com/owncloud/android/operations/UploadFileOperation.java

@@ -127,7 +127,7 @@ public class UploadFileOperation extends SyncOperation {
     /**
      * Local path to file which is to be uploaded (before any possible renaming or moving).
      */
-    private String mOriginalStoragePath = null;
+    private String mOriginalStoragePath;
     private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<>();
     private OnRenameListener mRenameUploadListener;
 
@@ -138,7 +138,7 @@ public class UploadFileOperation extends SyncOperation {
 
     private UploadRemoteFileOperation mUploadOperation;
 
-    protected RequestEntity mEntity = null;
+    protected RequestEntity mEntity;
 
     private Account mAccount;
     private OCUpload mUpload;

+ 80 - 84
src/main/java/com/owncloud/android/providers/FileContentProvider.java

@@ -92,12 +92,11 @@ public class FileContentProvider extends ContentProvider {
 
     @Override
     public int delete(@NonNull Uri uri, String where, String[] whereArgs) {
-        int count;
-
         if (isCallerNotAllowed()) {
             return -1;
         }
 
+        int count;
         SQLiteDatabase db = mDbHelper.getWritableDatabase();
         db.beginTransaction();
         try {
@@ -110,95 +109,20 @@ public class FileContentProvider extends ContentProvider {
         return count;
     }
 
-    private int delete(SQLiteDatabase db, Uri uri, String where, String[] whereArgs) {
+    private int delete(SQLiteDatabase db, Uri uri, String where, String... whereArgs) {
         if (isCallerNotAllowed()) {
             return -1;
         }
 
-        int count = 0;
+        int count;
         switch (mUriMatcher.match(uri)) {
             case SINGLE_FILE:
-                Cursor c = query(db, uri, null, where, whereArgs, null);
-                String remoteId = "";
-                try {
-                    if (c != null && c.moveToFirst()) {
-                        remoteId = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID));
-                        //ThumbnailsCacheManager.removeFileFromCache(remoteId);
-                    }
-                    Log_OC.d(TAG, "Removing FILE " + remoteId);
-
-                    count = db.delete(ProviderTableMeta.FILE_TABLE_NAME,
-                            ProviderTableMeta._ID
-                                    + "="
-                                    + uri.getPathSegments().get(1)
-                                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""),
-                            whereArgs);
-                } catch (Exception e) {
-                    Log_OC.d(TAG, "DB-Error removing file!", e);
-                } finally {
-                    if (c != null) {
-                        c.close();
-                    }
-                }
+                count = deleteSingleFile(db, uri, where, whereArgs);
                 break;
             case DIRECTORY:
-                // deletion of folder is recursive
-            /*
-            Uri folderUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, Long.parseLong(uri.getPathSegments().get(1)));
-            Cursor folder = query(db, folderUri, null, null, null, null);
-            String folderName = "(unknown)";
-            if (folder != null && folder.moveToFirst()) {
-                folderName = folder.getString(folder.getColumnIndex(ProviderTableMeta.FILE_PATH));
-            }
-            */
-                Cursor children = query(uri, null, null, null, null);
-                if (children != null) {
-                    if (children.moveToFirst()) {
-                        long childId;
-                        boolean isDir;
-                        while (!children.isAfterLast()) {
-                            childId = children.getLong(children.getColumnIndex(ProviderTableMeta._ID));
-                            isDir = MimeType.DIRECTORY.equals(children.getString(
-                                    children.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)
-                            ));
-                            //remotePath = children.getString(children.getColumnIndex(ProviderTableMeta.FILE_PATH));
-                            if (isDir) {
-                                count += delete(
-                                        db,
-                                        ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId),
-                                        null,
-                                        null
-                                );
-                            } else {
-                                count += delete(
-                                        db,
-                                        ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId),
-                                        null,
-                                        null
-                                );
-                            }
-                            children.moveToNext();
-                        }
-                    }
-                    children.close();
-                } /*else {
-                Log_OC.d(TAG, "No child to remove in DIRECTORY " + folderName);
-            }
-            Log_OC.d(TAG, "Removing DIRECTORY " + folderName + " (or maybe not) ");
-            */
-                count += db.delete(ProviderTableMeta.FILE_TABLE_NAME,
-                        ProviderTableMeta._ID
-                                + "="
-                                + uri.getPathSegments().get(1)
-                                + (!TextUtils.isEmpty(where) ? " AND (" + where
-                                + ")" : ""), whereArgs);
-            /* Just for log
-             if (folder != null) {
-                folder.close();
-            }*/
+                count = deleteDirectory(db, uri, where, whereArgs);
                 break;
             case ROOT_DIRECTORY:
-                //Log_OC.d(TAG, "Removing ROOT!");
                 count = db.delete(ProviderTableMeta.FILE_TABLE_NAME, where, whereArgs);
                 break;
             case SHARES:
@@ -226,9 +150,82 @@ public class FileContentProvider extends ContentProvider {
                 count = db.delete(ProviderTableMeta.FILESYSTEM_TABLE_NAME, where, whereArgs);
                 break;
             default:
-                //Log_OC.e(TAG, "Unknown uri " + uri);
                 throw new IllegalArgumentException("Unknown uri: " + uri.toString());
         }
+
+        return count;
+    }
+
+    private int deleteDirectory(SQLiteDatabase db, Uri uri, String where, String... whereArgs) {
+        int count = 0;
+
+        Cursor children = query(uri, null, null, null, null);
+        if (children != null) {
+            if (children.moveToFirst()) {
+                long childId;
+                boolean isDir;
+                while (!children.isAfterLast()) {
+                    childId = children.getLong(children.getColumnIndex(ProviderTableMeta._ID));
+                    isDir = MimeType.DIRECTORY.equals(children.getString(
+                            children.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)
+                    ));
+                    //remotePath = children.getString(children.getColumnIndex(ProviderTableMeta.FILE_PATH));
+                    if (isDir) {
+                        count += delete(
+                                db,
+                                ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId),
+                                null,
+                                null
+                        );
+                    } else {
+                        count += delete(
+                                db,
+                                ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId),
+                                null,
+                                null
+                        );
+                    }
+                    children.moveToNext();
+                }
+            }
+            children.close();
+        }
+
+        count += db.delete(ProviderTableMeta.FILE_TABLE_NAME,
+                ProviderTableMeta._ID
+                        + "="
+                        + uri.getPathSegments().get(1)
+                        + (!TextUtils.isEmpty(where) ? " AND (" + where
+                        + ")" : ""), whereArgs);
+
+        return count;
+    }
+
+    private int deleteSingleFile(SQLiteDatabase db, Uri uri, String where, String... whereArgs) {
+        int count = 0;
+        Cursor c = query(db, uri, null, where, whereArgs, null);
+        String remoteId = "";
+        try {
+            if (c != null && c.moveToFirst()) {
+                remoteId = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID));
+                //ThumbnailsCacheManager.removeFileFromCache(remoteId);
+            }
+            Log_OC.d(TAG, "Removing FILE " + remoteId);
+
+            count = db.delete(ProviderTableMeta.FILE_TABLE_NAME,
+                    ProviderTableMeta._ID
+                            + "="
+                            + uri.getPathSegments().get(1)
+                            + (!TextUtils.isEmpty(where) ? " AND (" + where + ")" : ""),
+                    whereArgs);
+        } catch (Exception e) {
+            Log_OC.d(TAG, "DB-Error removing file!", e);
+        } finally {
+            if (c != null) {
+                c.close();
+            }
+        }
+
         return count;
     }
 
@@ -654,13 +651,12 @@ public class FileContentProvider extends ContentProvider {
         return count;
     }
 
-
     private int update(
             SQLiteDatabase db,
             Uri uri,
             ContentValues values,
             String selection,
-            String[] selectionArgs
+            String... selectionArgs
     ) {
         switch (mUriMatcher.match(uri)) {
             case DIRECTORY:

+ 7 - 12
src/main/java/com/owncloud/android/services/OperationsService.java

@@ -269,10 +269,9 @@ public class OperationsService extends Service {
          * Map of listeners that will be reported about the end of operations from a
          * {@link OperationsServiceBinder} instance
          */
-        private final ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
-                new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
+        private final ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners = new ConcurrentHashMap<>();
 
-        private ServiceHandler mServiceHandler = null;
+        private ServiceHandler mServiceHandler;
 
         public OperationsServiceBinder(ServiceHandler serviceHandler) {
             mServiceHandler = serviceHandler;
@@ -355,7 +354,6 @@ public class OperationsService extends Service {
             }
         }
 
-
         public boolean dispatchResultIfFinished(int operationId,
                                                 OnRemoteOperationListener listener) {
             Pair<RemoteOperation, RemoteOperationResult> undispatched = 
@@ -363,13 +361,11 @@ public class OperationsService extends Service {
             if (undispatched != null) {
                 listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
                 return true;
-                //Log_OC.e(TAG, "Sending callback later");
             } else {
-                return (!mServiceHandler.mPendingOperations.isEmpty());
+                return !mServiceHandler.mPendingOperations.isEmpty();
             }
         }
         
-        
         /**
          * Returns True when the file described by 'file' in the ownCloud account 'account' is
          * downloading or waiting to download.
@@ -402,10 +398,10 @@ public class OperationsService extends Service {
 
 
         private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
-                new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
-        private RemoteOperation mCurrentOperation = null;
-        private Target mLastTarget = null;
-        private OwnCloudClient mOwnCloudClient = null;
+                new ConcurrentLinkedQueue<>();
+        private RemoteOperation mCurrentOperation;
+        private Target mLastTarget;
+        private OwnCloudClient mOwnCloudClient;
         private FileDataStorageManager mStorageManager;
         
         
@@ -423,7 +419,6 @@ public class OperationsService extends Service {
             Log_OC.d(TAG, "Stopping after command with id " + msg.arg1);
             mService.stopSelf(msg.arg1);
         }
-
         
         /**
          * Performs the next operation in the queue

+ 11 - 12
src/main/java/com/owncloud/android/syncadapter/FileSyncAdapter.java

@@ -141,9 +141,6 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
             SyncResult syncResult) {
 
         mCancellation = false;
-        /* When 'true' the process was requested by the user through the user interface;
-       when 'false', it was requested automatically by the system */
-        boolean mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
         mFailedResultsCounter = 0;
         mLastFailedResult = null;
         mConflictsFound = 0;
@@ -170,7 +167,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
         sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null);  // message to signal the start
                                                                 // of the synchronization to the UI
-        
+
+        /* When 'true' the process was requested by the user through the user interface;
+           when 'false', it was requested automatically by the system */
+        boolean mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
         try {
             updateOCVersion();
             mCurrentSyncTime = System.currentTimeMillis();
@@ -182,7 +182,6 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                         "because cancellation request");
             }
             
-            
         } finally {
             // it's important making this although very unexpected errors occur;
             // that's the reason for the finally
@@ -316,12 +315,12 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      *                              synchronization
      */
     private boolean isFinisher(RemoteOperationResult failedResult) {
-        if  (failedResult != null) {
+        if (failedResult != null) {
             RemoteOperationResult.ResultCode code = failedResult.getCode();
-            return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
-                    code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
-                    code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
-                    code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
+            return code.equals(RemoteOperationResult.ResultCode.SSL_ERROR)
+                    || code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)
+                    || code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION)
+                    || code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
         }
         return false;
     }
@@ -522,8 +521,8 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * @param builder
      */
     private void showNotification(int id, NotificationCompat.Builder builder) {
-        NotificationManager notificationManager = ((NotificationManager) getContext().
-                getSystemService(Context.NOTIFICATION_SERVICE));
+        NotificationManager notificationManager = (NotificationManager) getContext().
+                getSystemService(Context.NOTIFICATION_SERVICE);
 
         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
             builder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_FILE_SYNC);

+ 1 - 1
src/main/java/com/owncloud/android/ui/ExtendedListView.java

@@ -36,7 +36,7 @@ public class ExtendedListView extends ListView {
 
     private static final String TAG = ExtendedListView.class.getSimpleName();
 
-    private int mPositionToSetAndCenter = 0;
+    private int mPositionToSetAndCenter;
 
     public ExtendedListView(Context context) {
         super(context);

+ 15 - 9
src/main/java/com/owncloud/android/ui/ThemeableSwitchPreference.java

@@ -38,7 +38,6 @@ import com.owncloud.android.utils.ThemeUtils;
 /**
  * Themeable switch preference
  */
-
 public class ThemeableSwitchPreference extends SwitchPreference {
 
     public ThemeableSwitchPreference(Context context) {
@@ -64,24 +63,31 @@ public class ThemeableSwitchPreference extends SwitchPreference {
 
     @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
     private void findSwitch(ViewGroup viewGroup) {
+        ColorStateList thumbColorStateList = null;
+        ColorStateList trackColorStateList = null;
+
         for (int i = 0; i < viewGroup.getChildCount(); i++) {
             View child = viewGroup.getChildAt(i);
 
             if (child instanceof Switch) {
                 Switch switchView = (Switch) child;
 
-                int color = ThemeUtils.primaryAccentColor(getContext());
-                int trackColor = Color.argb(77, Color.red(color), Color.green(color), Color.blue(color));
+                if(thumbColorStateList == null && trackColorStateList == null) {
+                    int color = ThemeUtils.primaryAccentColor(getContext());
+                    int trackColor = Color.argb(77, Color.red(color), Color.green(color), Color.blue(color));
+                    thumbColorStateList = new ColorStateList(
+                            new int[][]{new int[]{android.R.attr.state_checked}, new int[]{}},
+                            new int[]{color, Color.WHITE});
+                    trackColorStateList = new ColorStateList(
+                            new int[][]{new int[]{android.R.attr.state_checked}, new int[]{}},
+                            new int[]{trackColor, Color.parseColor("#4D000000")});
+                }
 
                 // setting the thumb color
-                DrawableCompat.setTintList(switchView.getThumbDrawable(), new ColorStateList(
-                        new int[][]{new int[]{android.R.attr.state_checked}, new int[]{}},
-                        new int[]{color, Color.WHITE}));
+                DrawableCompat.setTintList(switchView.getThumbDrawable(), thumbColorStateList);
 
                 // setting the track color
-                DrawableCompat.setTintList(switchView.getTrackDrawable(), new ColorStateList(
-                        new int[][]{new int[]{android.R.attr.state_checked}, new int[]{}},
-                        new int[]{trackColor, Color.parseColor("#4D000000")}));
+                DrawableCompat.setTintList(switchView.getTrackDrawable(), trackColorStateList);
 
                 break;
             } else if (child instanceof ViewGroup) {

+ 1 - 1
src/main/java/com/owncloud/android/ui/activity/DrawerActivity.java

@@ -946,13 +946,13 @@ public abstract class DrawerActivity extends ToolbarActivity implements DisplayU
         Thread t = new Thread(new Runnable() {
             public void run() {
                 Context context = MainApp.getAppContext();
-                AccountManager mAccountMgr = AccountManager.get(context);
                 Account account = AccountUtils.getCurrentOwnCloudAccount(context);
 
                 if (account == null) {
                     return;
                 }
 
+                AccountManager mAccountMgr = AccountManager.get(context);
                 String userId = mAccountMgr.getUserData(account,
                         com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
 

+ 4 - 8
src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java

@@ -704,8 +704,8 @@ public class FileDisplayActivity extends HookActivity
     protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
                                          boolean success) {
         FileFragment secondFragment = getSecondFragment();
-        boolean waitedPreview = (mWaitingToPreview != null &&
-                mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
+        boolean waitedPreview = mWaitingToPreview != null
+                && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath);
         if (secondFragment instanceof FileDetailFragment) {
             FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
             OCFile fileInFragment = detailsFragment.getFile();
@@ -745,7 +745,7 @@ public class FileDisplayActivity extends HookActivity
                     mWaitingToPreview = null;
                 }
                 if (!detailsFragmentChanged) {
-                    detailsFragment.updateFileDetails(false, (success));
+                    detailsFragment.updateFileDetails(false, success);
                 }
             }
         }
@@ -1497,12 +1497,8 @@ public class FileDisplayActivity extends HookActivity
         // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
         private boolean isAscendant(String linkedToRemotePath) {
             OCFile currentDir = getCurrentDir();
-            return (
-                    currentDir != null &&
-                            currentDir.getRemotePath().startsWith(linkedToRemotePath)
-            );
+            return currentDir != null && currentDir.getRemotePath().startsWith(linkedToRemotePath);
         }
-
     }
 
 

+ 2 - 3
src/main/java/com/owncloud/android/ui/activity/PassCodeActivity.java

@@ -315,8 +315,7 @@ public class    PassCodeActivity extends AppCompatActivity {
 
         boolean result = true;
         for (int i = 0; i < mPassCodeDigits.length && result; i++) {
-            result = (mPassCodeDigits[i] != null) &&
-                    mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
+            result = mPassCodeDigits[i] != null && mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
         }
         return result;
     }
@@ -332,7 +331,7 @@ public class    PassCodeActivity extends AppCompatActivity {
 
         boolean result = true;
         for (int i = 0; i < mPassCodeEditTexts.length && result; i++) {
-            result = ((mPassCodeEditTexts[i].getText().toString()).equals(mPassCodeDigits[i]));
+            result = mPassCodeEditTexts[i].getText().toString().equals(mPassCodeDigits[i]);
         }
         return result;
     }

+ 13 - 12
src/main/java/com/owncloud/android/ui/activity/ReceiveExternalFilesActivity.java

@@ -98,6 +98,7 @@ import com.owncloud.android.utils.DataHolderUtil;
 import com.owncloud.android.utils.DisplayUtils;
 import com.owncloud.android.utils.ErrorMessageAdapter;
 import com.owncloud.android.utils.FileSortOrder;
+import com.owncloud.android.utils.MimeType;
 import com.owncloud.android.utils.ThemeUtils;
 
 import java.io.File;
@@ -131,6 +132,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
     public static final String URL_FILE_SUFFIX = ".url";
     public static final String WEBLOC_FILE_SUFFIX = ".webloc";
     public static final String DESKTOP_FILE_SUFFIX = ".desktop";
+    public static final int SINGLE_PARENT = 1;
 
     private AccountManager mAccountManager;
     private Stack<String> mParents = new Stack<>();
@@ -526,7 +528,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
             inputText.setText(filename);
             int selectionStart = 0;
             int extensionStart = filename.lastIndexOf(".");
-            int selectionEnd = (extensionStart >= 0) ? extensionStart : filename.length();
+            int selectionEnd = extensionStart >= 0 ? extensionStart : filename.length();
             if (selectionEnd >= 0) {
                 inputText.setSelection(
                         Math.min(selectionStart, selectionEnd),
@@ -544,7 +546,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
         }
 
         private boolean isIntentStartWithUrl(String extraText) {
-            return (extraText.startsWith("http://") || extraText.startsWith("https://"));
+            return extraText.startsWith("http://") || extraText.startsWith("https://");
         }
 
         @Nullable
@@ -728,7 +730,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
         ListView mListView = findViewById(android.R.id.list);
 
         String current_dir = mParents.peek();
-        boolean notRoot = (mParents.size() > 1);
+        boolean notRoot = mParents.size() > 1;
 
         if (actionBar != null) {
             if ("".equals(current_dir)) {
@@ -880,7 +882,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
     }
 
     private void saveTextsFromIntent(Intent intent) {
-        if (!"text/plain".equals(intent.getType())) {
+        if (!MimeType.TEXT_PLAIN.equals(intent.getType())) {
             return;
         }
         mUploadFromTmpFile = true;
@@ -1063,7 +1065,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
                 dialog.show(getSupportFragmentManager(), CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
                 break;
             case android.R.id.home:
-                if ((mParents.size() > 1)) {
+                if (mParents.size() > SINGLE_PARENT) {
                     onBackPressed();
                 }
                 break;
@@ -1115,8 +1117,8 @@ public class ReceiveExternalFilesActivity extends FileActivity
                 String syncFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
                 RemoteOperationResult syncResult = (RemoteOperationResult)
                         DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
-                boolean sameAccount = (getAccount() != null &&
-                        accountName.equals(getAccount().name) && getStorageManager() != null);
+                boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name)
+                        && getStorageManager() != null;
 
                 if (sameAccount) {
 
@@ -1150,13 +1152,12 @@ public class ReceiveExternalFilesActivity extends FileActivity
                             mFile = currentFile;
                         }
 
-                        mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
-                                !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
+                        mSyncInProgress = !FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
+                                !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event);
 
-                        if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
-                                equals(event) &&
+                        if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event)
                                 /// TODO refactor and make common
-                                syncResult != null && !syncResult.isSuccess()) {
+                                && syncResult != null && !syncResult.isSuccess()) {
 
                             if (syncResult.getCode() == ResultCode.UNAUTHORIZED ||
                                     (syncResult.isException() && syncResult.getException()

+ 2 - 2
src/main/java/com/owncloud/android/ui/activity/ShareActivity.java

@@ -148,8 +148,8 @@ public class ShareActivity extends FileActivity implements ShareFragmentListener
             return OCShare.READ_PERMISSION_FLAG;    // minimum permissions
 
         } else if (isFederated) {
-                return (getFile().isFolder() ? OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9 :
-                        OCShare.FEDERATED_PERMISSIONS_FOR_FILE_AFTER_OC9);
+                return getFile().isFolder() ? OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9 :
+                        OCShare.FEDERATED_PERMISSIONS_FOR_FILE_AFTER_OC9;
         } else {
             return (getFile().isFolder() ? OCShare.MAXIMUM_PERMISSIONS_FOR_FOLDER :
                     OCShare.MAXIMUM_PERMISSIONS_FOR_FILE);

+ 1 - 1
src/main/java/com/owncloud/android/ui/activity/StorageMigration.java

@@ -269,7 +269,7 @@ public class StorageMigration {
             }
         }
 
-        protected void restoreAccountsSyncStatus(boolean oldSync[]) {
+        protected void restoreAccountsSyncStatus(boolean... oldSync) {
             // If we don't have the old sync statuses, then
             // probably migration failed even before saving states,
             // which is weird and should be investigated.

+ 1 - 1
src/main/java/com/owncloud/android/ui/activity/SyncedFoldersActivity.java

@@ -423,7 +423,7 @@ public class SyncedFoldersActivity extends FileActivity implements SyncedFolderA
         return files;
     }
 
-    private List<String> getDisplayFilePathList(File[] files) {
+    private List<String> getDisplayFilePathList(File... files) {
         List<String> filePaths = null;
 
         if (files != null && files.length > 0) {

+ 3 - 3
src/main/java/com/owncloud/android/ui/activity/UploadFilesActivity.java

@@ -84,9 +84,9 @@ public class UploadFilesActivity extends FileActivity implements
     private static final String SORT_ORDER_DIALOG_TAG = "SORT_ORDER_DIALOG";
 
     private ArrayAdapter<String> mDirectories;
-    private File mCurrentDir = null;
-    private boolean mSelectAll = false;
-    private boolean mLocalFolderPickerMode = false;
+    private File mCurrentDir;
+    private boolean mSelectAll;
+    private boolean mLocalFolderPickerMode;
     private LocalFileListFragment mFileListFragment;
     protected Button mUploadBtn;
     private Spinner mBehaviourSpinner;

+ 1 - 1
src/main/java/com/owncloud/android/ui/adapter/ActivityListAdapter.java

@@ -239,7 +239,7 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
     private void setBitmap(OCFile file, ImageView fileIcon, boolean isDetailView) {
         // No Folder
         if (!file.isFolder()) {
-            if ((MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file))) {
+            if (MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file)) {
                 int placeholder;
 
                 if (MimeTypeUtil.isImage(file)) {

+ 1 - 1
src/main/java/com/owncloud/android/ui/adapter/LocalFileListAdapter.java

@@ -68,7 +68,7 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
     private List<File> mFiles = new ArrayList<>();
     private List<File> mFilesAll = new ArrayList<>();
     private boolean mLocalFolderPicker;
-    private boolean gridView = false;
+    private boolean gridView;
     private LocalFileListFragmentInterface localFileListFragmentInterface;
     private Set<File> checkedFiles;
 

+ 1 - 1
src/main/java/com/owncloud/android/ui/adapter/UploadListAdapter.java

@@ -605,7 +605,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
             return items[position];
         }
 
-        public void setItems(OCUpload[] items) {
+        public void setItems(OCUpload... items) {
             this.items = items;
         }
 

+ 0 - 1
src/main/java/com/owncloud/android/ui/adapter/X509CertificateViewAdapter.java

@@ -16,7 +16,6 @@
  *
  *   You should have received a copy of the GNU General Public License
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
  */
 package com.owncloud.android.ui.adapter;
 

+ 1 - 1
src/main/java/com/owncloud/android/ui/dialog/SamlWebViewDialog.java

@@ -194,7 +194,7 @@ public class SamlWebViewDialog extends DialogFragment {
         
         // Work around bug: http://code.google.com/p/android/issues/detail?id=17423
         Dialog dialog = getDialog();
-        if ((dialog != null)) {
+        if (dialog != null) {
             dialog.setOnDismissListener(null);
         }
         

+ 0 - 2
src/main/java/com/owncloud/android/ui/dialog/SendShareDialog.java

@@ -89,8 +89,6 @@ public class SendShareDialog extends BottomSheetDialogFragment {
         // keep the state of the fragment on configuration changes
         setRetainInstance(true);
 
-        view = null;
-
         file = getArguments().getParcelable(KEY_OCFILE);
         hideNcSharingOptions = getArguments().getBoolean(KEY_HIDE_NCSHARING_OPTIONS, false);
         sharingPublicPasswordEnforced = getArguments().getBoolean(KEY_SHARING_PUBLIC_PASSWORD_ENFORCED, false);

+ 1 - 2
src/main/java/com/owncloud/android/ui/dialog/SetupEncryptionDialogFragment.java

@@ -345,7 +345,6 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
 
                 // Create public/private key pair
                 KeyPair keyPair = EncryptionUtils.generateKeyPair();
-                PrivateKey privateKey = keyPair.getPrivate();
 
                 // get user id
                 String userID;
@@ -369,13 +368,13 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
 
                 if (result.isSuccess()) {
                     Log_OC.d(TAG, "public key success");
-
                     publicKey = (String) result.getData().get(0);
                 } else {
                     keyResult = KEY_FAILED;
                     return "";
                 }
 
+                PrivateKey privateKey = keyPair.getPrivate();
                 String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKey.getEncoded());
                 String privatePemKeyString = EncryptionUtils.privateKeyToPEM(privateKey);
                 String encryptedPrivateKey = EncryptionUtils.encryptPrivateKey(privatePemKeyString,

+ 3 - 4
src/main/java/com/owncloud/android/ui/dialog/ShareLinkToDialog.java

@@ -65,7 +65,7 @@ public class ShareLinkToDialog  extends DialogFragment {
     private ActivityAdapter mAdapter;
     private Intent mIntent;
     
-    public static ShareLinkToDialog newInstance(Intent intent, String[] packagesToExclude) {
+    public static ShareLinkToDialog newInstance(Intent intent, String... packagesToExclude) {
         ShareLinkToDialog f = new ShareLinkToDialog();
         Bundle args = new Bundle();
         args.putParcelable(ARG_INTENT, intent);
@@ -165,8 +165,8 @@ public class ShareLinkToDialog  extends DialogFragment {
         }
         
         private View newView(ViewGroup parent) {
-            return(((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
-                    inflate(R.layout.activity_row, parent, false));
+            return((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
+                    inflate(R.layout.activity_row, parent, false);
         }
         
         private void bindView(int position, View row) {
@@ -176,5 +176,4 @@ public class ShareLinkToDialog  extends DialogFragment {
             icon.setImageDrawable(getItem(position).loadIcon(mPackageManager));
         }
     }
-    
 }

+ 1 - 1
src/main/java/com/owncloud/android/ui/dialog/SortingOrderDialogFragment.java

@@ -48,7 +48,7 @@ public class SortingOrderDialogFragment extends DialogFragment {
     public static final String SORTING_ORDER_FRAGMENT = "SORTING_ORDER_FRAGMENT";
     private static final String KEY_SORT_ORDER = "SORT_ORDER";
 
-    private View mView = null;
+    private View mView;
     private View[] mTaggedViews;
     private AppCompatButton mCancel;
     private String mCurrentSortOrderName;

+ 1 - 1
src/main/java/com/owncloud/android/ui/dialog/SslValidatorDialog.java

@@ -54,7 +54,7 @@ public class SslValidatorDialog extends Dialog {
     private final static String TAG = SslValidatorDialog.class.getSimpleName();
 
     private OnSslValidatorListener mListener;
-    private CertificateCombinedException mException = null;
+    private CertificateCombinedException mException;
     private View mView;
     
     

+ 2 - 2
src/main/java/com/owncloud/android/ui/dialog/SyncedFolderPreferencesDialogFragment.java

@@ -83,14 +83,14 @@ public class SyncedFolderPreferencesDialogFragment extends DialogFragment {
     private AlertDialog behaviourDialog;
 
     public static SyncedFolderPreferencesDialogFragment newInstance(SyncedFolderDisplayItem syncedFolder, int section) {
-        SyncedFolderPreferencesDialogFragment dialogFragment = new SyncedFolderPreferencesDialogFragment();
-
         if (syncedFolder == null) {
             throw new IllegalArgumentException("SyncedFolder is mandatory but NULL!");
         }
 
         Bundle args = new Bundle();
         args.putParcelable(SYNCED_FOLDER_PARCELABLE, new SyncedFolderParcelable(syncedFolder, section));
+
+        SyncedFolderPreferencesDialogFragment dialogFragment = new SyncedFolderPreferencesDialogFragment();
         dialogFragment.setArguments(args);
         dialogFragment.setStyle(STYLE_NORMAL, R.style.Theme_ownCloud_Dialog);
 

+ 3 - 3
src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java

@@ -101,7 +101,7 @@ public class ExtendedListFragment extends Fragment
     private int maxColumnSizePortrait = 5;
     private int maxColumnSizeLandscape = 10;
 
-    private ScaleGestureDetector mScaleGestureDetector = null;
+    private ScaleGestureDetector mScaleGestureDetector;
     protected SwipeRefreshLayout mRefreshListLayout;
     protected LinearLayout mEmptyListContainer;
     protected TextView mEmptyListMessage;
@@ -115,9 +115,9 @@ public class ExtendedListFragment extends Fragment
     private ArrayList<Integer> mIndexes;
     private ArrayList<Integer> mFirstPositions;
     private ArrayList<Integer> mTops;
-    private int mHeightCell = 0;
+    private int mHeightCell;
 
-    private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null;
+    private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener;
 
     private EmptyRecyclerView mRecyclerView;
 

+ 5 - 6
src/main/java/com/owncloud/android/ui/fragment/FileDetailFragment.java

@@ -508,10 +508,9 @@ public class FileDetailFragment extends FileFragment implements OnClickListener
             // configure UI for depending upon local state of the file
             FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
             FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
-            if (transferring ||
-                    (downloaderBinder != null && downloaderBinder.isDownloading(account, file)) ||
-                    (uploaderBinder != null && uploaderBinder.isUploading(account, file))
-                    ) {
+            if (transferring
+                    || (downloaderBinder != null && downloaderBinder.isDownloading(account, file))
+                    || (uploaderBinder != null && uploaderBinder.isUploading(account, file))) {
                 setButtonsForTransferring();
 
             } else if (file.isDown()) {
@@ -544,7 +543,7 @@ public class FileDetailFragment extends FileFragment implements OnClickListener
      * @return 'True' when the fragment is ready to show details of a file
      */
     private boolean readyToShow() {
-        return (getFile() != null && account != null && layout == R.layout.file_details_fragment);
+        return getFile() != null && account != null && layout == R.layout.file_details_fragment;
     }
 
     /**
@@ -677,7 +676,7 @@ public class FileDetailFragment extends FileFragment implements OnClickListener
      * Helper class responsible for updating the progress bar shown for file downloading.
      */
     private class ProgressListener implements OnDatatransferProgressListener {
-        private int lastPercent = 0;
+        private int lastPercent;
         private WeakReference<ProgressBar> progressBarReference;
 
         ProgressListener(ProgressBar progressBar) {

+ 4 - 4
src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java

@@ -306,14 +306,14 @@ public class OCFileListFragment extends ExtendedListFragment implements
         }
 
         Bundle args = getArguments();
-        mOnlyFoldersClickable = (args != null) && args.getBoolean(ARG_ONLY_FOLDERS_CLICKABLE, false);
-        boolean hideItemOptions = (args != null) && args.getBoolean(ARG_HIDE_ITEM_OPTIONS, false);
+        mOnlyFoldersClickable = args != null && args.getBoolean(ARG_ONLY_FOLDERS_CLICKABLE, false);
+        boolean hideItemOptions = args != null && args.getBoolean(ARG_HIDE_ITEM_OPTIONS, false);
 
         mAdapter = new OCFileListAdapter(getActivity(), mContainerActivity, this, hideItemOptions,
                 isGridViewPreferred(mFile));
         setRecyclerViewAdapter(mAdapter);
 
-        mHideFab = (args != null) && args.getBoolean(ARG_HIDE_FAB, false);
+        mHideFab = args != null && args.getBoolean(ARG_HIDE_FAB, false);
 
         if (mHideFab) {
             setFabEnabled(false);
@@ -434,7 +434,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
         /**
          * True when action mode is finished because the drawer was opened
          */
-        private boolean mActionModeClosedByDrawer = false;
+        private boolean mActionModeClosedByDrawer;
 
         /**
          * Selected items in list when action mode is closed by drawer

+ 5 - 1
src/main/java/com/owncloud/android/ui/fragment/util/SharingMenuHelper.java

@@ -32,7 +32,11 @@ import java.util.Date;
 /**
  * Helper calls for visibility logic of the sharing menu.
  */
-public class SharingMenuHelper {
+public final class SharingMenuHelper {
+
+    private SharingMenuHelper() {
+        // utility class -> private constructor
+    }
 
     /**
      * Sets checked/visiblity state on the given {@link MenuItem} based on the given criteria.

+ 1 - 1
src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java

@@ -343,7 +343,7 @@ public class FileOperationsHelper {
         return openFileWithIntent;
     }
 
-    private Uri getFileUri(OCFile file, String[] officeExtensions) {
+    private Uri getFileUri(OCFile file, String... officeExtensions) {
         if (file.getFileName().contains(".") &&
                 Arrays.asList(officeExtensions).contains(file.getFileName().substring(file.getFileName().
                         lastIndexOf(".") + 1, file.getFileName().length())) &&

+ 1 - 1
src/main/java/com/owncloud/android/ui/helpers/UriUploader.java

@@ -177,7 +177,7 @@ public class UriUploader {
      * @param sourceUris        Array of content:// URIs to the files to upload
      * @param remotePaths       Array of absolute paths to set to the uploaded files
      */
-    private void copyThenUpload(Uri[] sourceUris, String[] remotePaths) {
+    private void copyThenUpload(Uri[] sourceUris, String... remotePaths) {
         if (mShowWaitingDialog) {
             mActivity.showLoadingDialog(mActivity.getResources().
                     getString(R.string.wait_for_tmp_copy_from_private_storage));

+ 5 - 1
src/main/java/com/owncloud/android/ui/notifications/NotificationUtils.java

@@ -32,7 +32,7 @@ import java.util.Random;
 
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 
-public class NotificationUtils {
+public final class NotificationUtils {
 
     public static final String NOTIFICATION_CHANNEL_GENERAL = "NOTIFICATION_CHANNEL_GENERAL";
     public static final String NOTIFICATION_CHANNEL_DOWNLOAD = "NOTIFICATION_CHANNEL_DOWNLOAD";
@@ -42,6 +42,10 @@ public class NotificationUtils {
     public static final String NOTIFICATION_CHANNEL_FILE_OBSERVER = "NOTIFICATION_CHANNEL_FILE_OBSERVER";
     public static final String NOTIFICATION_CHANNEL_PUSH = "NOTIFICATION_CHANNEL_PUSH";
 
+    private NotificationUtils() {
+        // utility class -> private constructor
+    }
+
     /**
      * Factory method for {@link android.support.v4.app.NotificationCompat.Builder} instances.
      *

+ 2 - 2
src/main/java/com/owncloud/android/ui/preview/FileDownloadFragment.java

@@ -283,8 +283,8 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
      * Helper class responsible for updating the progress bar shown for file uploading or downloading
      */
     private class ProgressListener implements OnDatatransferProgressListener {
-        int mLastPercent = 0;
-        WeakReference<ProgressBar> mProgressBar = null;
+        int mLastPercent;
+        WeakReference<ProgressBar> mProgressBar;
 
         ProgressListener(ProgressBar progressBar) {
             mProgressBar = new WeakReference<>(progressBar);

+ 1 - 1
src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java

@@ -145,7 +145,7 @@ public class PreviewImageActivity extends FileActivity implements
         mViewPager = findViewById(R.id.fragmentPager);
 
         int position = mHasSavedPosition ? mSavedPosition : mPreviewImagePagerAdapter.getFilePosition(getFile());
-        position = (position >= 0) ? position : 0;
+        position = position >= 0 ? position : 0;
 
         mViewPager.setAdapter(mPreviewImagePagerAdapter);
         mViewPager.addOnPageChangeListener(this);

+ 6 - 5
src/main/java/com/owncloud/android/ui/preview/PreviewImageFragment.java

@@ -65,6 +65,7 @@ import com.owncloud.android.ui.dialog.RemoveFilesDialogFragment;
 import com.owncloud.android.ui.fragment.FileFragment;
 import com.owncloud.android.utils.BitmapUtils;
 import com.owncloud.android.utils.DisplayUtils;
+import com.owncloud.android.utils.MimeType;
 import com.owncloud.android.utils.MimeTypeUtil;
 
 import java.io.FileInputStream;
@@ -113,7 +114,7 @@ public class PreviewImageFragment extends FileFragment {
 
     private boolean mIgnoreFirstSavedState;
 
-    private LoadBitmapTask mLoadBitmapTask = null;
+    private LoadBitmapTask mLoadBitmapTask;
 
     /**
      * Public factory method to create a new fragment that previews an image.
@@ -439,12 +440,12 @@ public class PreviewImageFragment extends FileFragment {
         protected LoadImage doInBackground(OCFile... params) {
             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
 
-            Bitmap bitmapResult = null;
-            Drawable drawableResult = null;
-
             if (params.length != 1) {
                 return null;
             }
+
+            Bitmap bitmapResult = null;
+            Drawable drawableResult = null;
             OCFile ocFile = params[0];
             String storagePath = ocFile.getStoragePath();
             try {
@@ -492,7 +493,7 @@ public class PreviewImageFragment extends FileFragment {
                                 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
                                 break;
                             } else {
-                                if ("image/jpeg".equalsIgnoreCase(ocFile.getMimeType())) {
+                                if (MimeType.JPEG.equalsIgnoreCase(ocFile.getMimeType())) {
                                     // Rotate image, obeying exif tag.
                                     bitmapResult = BitmapUtils.rotateImage(bitmapResult, storagePath);
                                 }

+ 1 - 1
src/main/java/com/owncloud/android/ui/preview/PreviewMediaFragment.java

@@ -804,7 +804,7 @@ public class PreviewMediaFragment extends FileFragment implements
      * @return 'True' if the file can be handled by the fragment.
      */
     public static boolean canBePreviewed(OCFile file) {
-        return (file != null && (MimeTypeUtil.isAudio(file) || MimeTypeUtil.isVideo(file)));
+        return file != null && (MimeTypeUtil.isAudio(file) || MimeTypeUtil.isVideo(file));
     }
 
 

+ 6 - 4
src/main/java/com/owncloud/android/utils/BitmapUtils.java

@@ -41,9 +41,12 @@ import java.util.Locale;
 /**
  * Utility class with methods for decoding Bitmaps.
  */
-public class BitmapUtils {
+public final class BitmapUtils {
     public static final String TAG = BitmapUtils.class.getSimpleName();
 
+    private BitmapUtils() {
+        // utility class -> private constructor
+    }
 
     /**
      * Decodes a bitmap from a file containing it minimizing the memory use, known that the bitmap
@@ -257,7 +260,7 @@ public class BitmapUtils {
         }
 
         if (3 * h < 2) {
-            return p + ((q - p) * 6 * ((2.0f / 3.0f) - h));
+            return p + ((q - p) * 6 * (2.0f / 3.0f - h));
         }
 
         return p;
@@ -376,8 +379,6 @@ public class BitmapUtils {
     }
 
     public static Bitmap drawableToBitmap(Drawable drawable) {
-        Bitmap bitmap;
-
         if (drawable instanceof BitmapDrawable) {
             BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
             if (bitmapDrawable.getBitmap() != null) {
@@ -385,6 +386,7 @@ public class BitmapUtils {
             }
         }
 
+        Bitmap bitmap;
         if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
             bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
         } else {

+ 5 - 1
src/main/java/com/owncloud/android/utils/ConnectivityUtils.java

@@ -44,10 +44,14 @@ import org.json.JSONObject;
 
 import java.io.IOException;
 
-public class ConnectivityUtils {
+public final class ConnectivityUtils {
 
     private final static String TAG = ConnectivityUtils.class.getName();
 
+    private ConnectivityUtils() {
+        // utility class -> private constructor
+    }
+
     public static boolean isInternetWalled(Context context) {
         if (isOnlineWithWifi(context)) {
             try {

+ 5 - 1
src/main/java/com/owncloud/android/utils/CsrHelper.java

@@ -28,7 +28,11 @@ import java.security.KeyPair;
  * Own parts are licensed unter GPLv3+.
  */
 
-public class CsrHelper {
+public final class CsrHelper {
+
+    private CsrHelper() {
+        // utility class -> private constructor
+    }
 
     /**
      * Generate CSR with PEM encoding

+ 5 - 1
src/main/java/com/owncloud/android/utils/DeviceCredentialUtils.java

@@ -53,7 +53,7 @@ import javax.crypto.SecretKey;
  * Utility class with methods for handling device credentials.
  */
 @RequiresApi(Build.VERSION_CODES.M)
-public class DeviceCredentialUtils {
+public final class DeviceCredentialUtils {
 
     private static final String TAG = DeviceCredentialUtils.class.getSimpleName();
 
@@ -61,6 +61,10 @@ public class DeviceCredentialUtils {
 
     private static final String ANDROID_KEY_STORE = "AndroidKeyStore";
 
+    private DeviceCredentialUtils() {
+        // utility class -> private constructor
+    }
+
     public static boolean areCredentialsAvailable(Context context) {
         KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
         

+ 7 - 5
src/main/java/com/owncloud/android/utils/DisplayUtils.java

@@ -27,7 +27,6 @@ package com.owncloud.android.utils;
 import android.accounts.Account;
 import android.accounts.AccountManager;
 import android.annotation.SuppressLint;
-import android.annotation.TargetApi;
 import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
@@ -103,7 +102,7 @@ import java.util.Set;
 /**
  * A helper class for UI/display related operations.
  */
-public class DisplayUtils {
+public final class DisplayUtils {
     private static final String TAG = DisplayUtils.class.getSimpleName();
 
     private static final String[] sizeSuffixes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
@@ -132,6 +131,10 @@ public class DisplayUtils {
         mimeType2HumanReadable.put("application/ogg", "OGG music file");
     }
 
+    private DisplayUtils() {
+        // utility class -> private constructor
+    }
+
     /**
      * Converts the file size in bytes to human readable output.
      * <ul>
@@ -241,7 +244,6 @@ public class DisplayUtils {
      * @param toASCII if true converts from Unicode to ASCII, if false converts from ASCII to Unicode
      * @return the URL containing the converted domain name
      */
-    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
     public static String convertIdn(String url, boolean toASCII) {
 
         String urlNoDots = url;
@@ -261,7 +263,7 @@ public class DisplayUtils {
 
         int hostEnd = url.substring(hostStart).indexOf("/");
         // Handle URL which doesn't have a path (path is implicitly '/')
-        hostEnd = (hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd);
+        hostEnd = hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd;
 
         String host = urlNoDots.substring(hostStart, hostEnd);
         host = toASCII ? IDN.toASCII(host) : IDN.toUnicode(host);
@@ -733,7 +735,7 @@ public class DisplayUtils {
     // Copied from https://raw.githubusercontent.com/nextcloud/talk-android/8ec8606bc61878e87e3ac8ad32c8b72d4680013c/app/src/main/java/com/nextcloud/talk/utils/DisplayUtils.java
     // under GPL3
     public static void useCompatVectorIfNeeded() {
-        if (Build.VERSION.SDK_INT < 23) {
+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
             try {
                 @SuppressLint("RestrictedApi") AppCompatDrawableManager drawableManager = AppCompatDrawableManager.get();
                 Class<?> inflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$InflateDelegate");

+ 5 - 1
src/main/java/com/owncloud/android/utils/EncryptionUtils.java

@@ -87,7 +87,7 @@ import javax.crypto.spec.SecretKeySpec;
  * Utils for encryption
  */
 
-public class EncryptionUtils {
+public final class EncryptionUtils {
     private static String TAG = EncryptionUtils.class.getSimpleName();
 
     public static final String PUBLIC_KEY = "PUBLIC_KEY";
@@ -105,6 +105,10 @@ public class EncryptionUtils {
     private static final String RSA_CIPHER = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
     private static final String RSA = "RSA";
 
+    private EncryptionUtils() {
+        // utility class -> private constructor
+    }
+
     /*
     JSON
      */

+ 6 - 1
src/main/java/com/owncloud/android/utils/ErrorMessageAdapter.java

@@ -53,7 +53,12 @@ import java.net.SocketTimeoutException;
  * Class to choose proper error messages to show to the user depending on the results of operations,
  * always following the same policy
  */
-public class ErrorMessageAdapter {
+public final class ErrorMessageAdapter {
+
+    private ErrorMessageAdapter() {
+        // utility class -> private constructor
+    }
+
     /**
      * Return an internationalized user message corresponding to an operation result
      * and the operation performed.

+ 5 - 1
src/main/java/com/owncloud/android/utils/FileStorageUtils.java

@@ -50,11 +50,15 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 /**
  * Static methods to help in access to local file system.
  */
-public class FileStorageUtils {
+public final class FileStorageUtils {
     private static final String TAG = FileStorageUtils.class.getSimpleName();
 
     public static final String PATTERN_YYYY_MM = "yyyy/MM/";
 
+    private FileStorageUtils() {
+        // utility class -> private constructor
+    }
+
     /**
      * Get local owncloud storage path for accountName.
      */

+ 7 - 3
src/main/java/com/owncloud/android/utils/FilesSyncHelper.java

@@ -63,10 +63,10 @@ import java.io.IOException;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
-/*
-    Various utilities that make auto upload tick
+/**
+ * Various utilities that make auto upload tick
  */
-public class FilesSyncHelper {
+public final class FilesSyncHelper {
     public static final String TAG = "FileSyncHelper";
 
     public static final String GLOBAL = "global";
@@ -74,6 +74,10 @@ public class FilesSyncHelper {
 
     public static final int ContentSyncJobId = 315;
 
+    private FilesSyncHelper() {
+        // utility class -> private constructor
+    }
+
     public static void insertAllDBEntriesForSyncedFolder(SyncedFolder syncedFolder) {
         final Context context = MainApp.getAppContext();
         final ContentResolver contentResolver = context.getContentResolver();

+ 3 - 0
src/main/java/com/owncloud/android/utils/MimeType.java

@@ -22,4 +22,7 @@ package com.owncloud.android.utils;
  */
 public class MimeType {
     public static final String DIRECTORY = "DIR";
+    public static final String JPEG = "image/jpeg";
+    public static final String TIFF = "image/tiff";
+    public static final String TEXT_PLAIN = "text/plain";
 }

+ 13 - 9
src/main/java/com/owncloud/android/utils/MimeTypeUtil.java

@@ -1,4 +1,4 @@
-/**
+/*
  * ownCloud Android client application
  * <p>
  * Copyright (C) 2016 ownCloud Inc.
@@ -64,7 +64,7 @@ import javax.annotation.Nullable;
  * </ol>
  */
 @SuppressWarnings("PMD.AvoidDuplicateLiterals")
-public class MimeTypeUtil {
+public final class MimeTypeUtil {
     /** Mapping: icon for mime type */
     private static final Map<String, Integer> MIMETYPE_TO_ICON_MAPPING = new HashMap<>();
     /** Mapping: icon for main mime type (first part of a mime type declaration). */
@@ -78,6 +78,10 @@ public class MimeTypeUtil {
         populateMainMimeTypeMapping();
     }
 
+    private MimeTypeUtil() {
+        // utility class -> private constructor
+    }
+
     /**
      * Returns the Drawable of an image to use as icon associated to a known MIME type.
      *
@@ -196,29 +200,29 @@ public class MimeTypeUtil {
      * @return 'True' if the mime type defines image
      */
     public static boolean isImage(String mimeType) {
-        return (mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("image/") &&
-                !mimeType.toLowerCase(Locale.ROOT).contains("djvu"));
+        return mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("image/") &&
+                !mimeType.toLowerCase(Locale.ROOT).contains("djvu");
     }
 
     /**
      * @return 'True' the mime type defines video
      */
     public static boolean isVideo(String mimeType) {
-        return (mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("video/"));
+        return mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("video/");
     }
 
     /**
      * @return 'True' the mime type defines audio
      */
     public static boolean isAudio(String mimeType) {
-        return (mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("audio/"));
+        return mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("audio/");
     }
 
     /**
      * @return 'True' if mime type defines text
      */
     public static boolean isText(String mimeType) {
-        return (mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("text/"));
+        return mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("text/");
     }
 
     /**
@@ -273,8 +277,8 @@ public class MimeTypeUtil {
      * @return 'True' if the file contains an image
      */
     public static boolean isImage(ServerFileInterface file) {
-        return (MimeTypeUtil.isImage(file.getMimeType())
-                || MimeTypeUtil.isImage(getMimeTypeFromPath(file.getRemotePath())));
+        return MimeTypeUtil.isImage(file.getMimeType())
+                || MimeTypeUtil.isImage(getMimeTypeFromPath(file.getRemotePath()));
     }
 
     /**

+ 5 - 1
src/main/java/com/owncloud/android/utils/PermissionUtil.java

@@ -9,12 +9,16 @@ import android.support.v4.content.ContextCompat;
 /**
  * Created by scherzia on 29.12.2015.
  */
-public class PermissionUtil {
+public final class PermissionUtil {
     public static final int PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
     public static final int PERMISSIONS_READ_CONTACTS_AUTOMATIC = 2;
     public static final int PERMISSIONS_READ_CONTACTS_MANUALLY = 3;
     public static final int PERMISSIONS_WRITE_CONTACTS = 4;
 
+    private PermissionUtil() {
+        // utility class -> private constructor
+    }
+
     /**
      * Wrapper method for ContextCompat.checkSelfPermission().
      * Determine whether <em>the app</em> has been granted a particular permission.

+ 5 - 1
src/main/java/com/owncloud/android/utils/PowerUtils.java

@@ -5,7 +5,11 @@ import android.content.Context;
 import android.os.Build;
 import android.os.PowerManager;
 
-public class PowerUtils {
+public final class PowerUtils {
+
+    private PowerUtils() {
+        // utility class -> private constructor
+    }
 
     /**
      * Checks if device is in power save mode. For older devices that do not support this API, returns false.

+ 7 - 3
src/main/java/com/owncloud/android/utils/ReceiversHelper.java

@@ -29,10 +29,14 @@ import com.evernote.android.job.JobRequest;
 import com.evernote.android.job.util.Device;
 import com.owncloud.android.MainApp;
 
-/*
-    Helper for setting up network and power receivers
+/**
+ * Helper for setting up network and power receivers
  */
-public class ReceiversHelper {
+public final class ReceiversHelper {
+
+    private ReceiversHelper() {
+        // utility class -> private constructor
+    }
 
     public static void registerNetworkChangeReceiver() {
         Context context = MainApp.getAppContext();

+ 5 - 1
src/main/java/com/owncloud/android/utils/ThemeUtils.java

@@ -62,7 +62,11 @@ import com.owncloud.android.ui.activity.ToolbarActivity;
 /**
  * Utility class with methods for client side theming.
  */
-public class ThemeUtils {
+public final class ThemeUtils {
+
+    private ThemeUtils() {
+        // utility class -> private constructor
+    }
 
     public static int primaryAccentColor(Context context) {
         OCCapability capability = getCapability(context);

+ 7 - 4
src/main/java/com/owncloud/android/utils/UriUtils.java

@@ -40,12 +40,15 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 /**
  * A helper class for some Uri operations.
  */
-public class UriUtils {
+public final class UriUtils {
 
     public static final String TAG = UriUtils.class.getSimpleName();
 
     public static final String URI_CONTENT_SCHEME = "content://";
 
+    private UriUtils() {
+        // utility class -> private constructor
+    }
 
     /**
      * Get the value of the data column for this Uri. This is useful for
@@ -57,7 +60,7 @@ public class UriUtils {
      * @param selectionArgs (Optional) Selection arguments used in the query.
      * @return The value of the _data column, which is typically a file path.
      */
-    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
+    public static String getDataColumn(Context context, Uri uri, String selection, String... selectionArgs) {
 
         Cursor cursor = null;
         final String column = "_data";
@@ -150,7 +153,7 @@ public class UriUtils {
                 final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                         Long.valueOf(id));
 
-                return UriUtils.getDataColumn(context, contentUri, null, null);
+                return UriUtils.getDataColumn(context, contentUri, null, (String) null);
             }
             // MediaProvider
             else if (UriUtils.isMediaDocument(uri)) {
@@ -185,7 +188,7 @@ public class UriUtils {
                 return uri.getLastPathSegment();
             }
 
-            return UriUtils.getDataColumn(context, uri, null, null);
+            return UriUtils.getDataColumn(context, uri, null, (String) null);
         }
         // File
         else if ("file".equalsIgnoreCase(uri.getScheme())) {

+ 1 - 1
src/main/java/org/nextcloud/providers/cursors/FileCursor.java

@@ -37,7 +37,7 @@ public class FileCursor extends MatrixCursor {
             Document.COLUMN_FLAGS, Document.COLUMN_LAST_MODIFIED
     };
 
-    public FileCursor(String[] projection) {
+    public FileCursor(String... projection) {
         super(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION);
     }
 

+ 1 - 1
src/main/java/org/nextcloud/providers/cursors/RootCursor.java

@@ -41,7 +41,7 @@ public class RootCursor extends MatrixCursor {
             Root.COLUMN_FLAGS
     };
 
-    public RootCursor(String[] projection) {
+    public RootCursor(String... projection) {
         super(projection != null ? projection : DEFAULT_ROOT_PROJECTION);
     }