Переглянути джерело

Merge pull request #3873 from nextcloud/codacy

Further code improvements
Andy Scherzinger 6 роки тому
батько
коміт
b52ce7e85c

+ 1 - 1
scripts/analysis/findbugs-results.txt

@@ -1 +1 @@
-477
+470

+ 0 - 2
src/main/java/com/nextcloud/client/di/ComponentsModule.java

@@ -33,7 +33,6 @@ import com.owncloud.android.ui.activity.FileDisplayActivity;
 import com.owncloud.android.ui.activity.FilePickerActivity;
 import com.owncloud.android.ui.activity.FilePickerActivity;
 import com.owncloud.android.ui.activity.FirstRunActivity;
 import com.owncloud.android.ui.activity.FirstRunActivity;
 import com.owncloud.android.ui.activity.FolderPickerActivity;
 import com.owncloud.android.ui.activity.FolderPickerActivity;
-import com.owncloud.android.ui.activity.HookActivity;
 import com.owncloud.android.ui.activity.LogHistoryActivity;
 import com.owncloud.android.ui.activity.LogHistoryActivity;
 import com.owncloud.android.ui.activity.ManageAccountsActivity;
 import com.owncloud.android.ui.activity.ManageAccountsActivity;
 import com.owncloud.android.ui.activity.ManageSpaceActivity;
 import com.owncloud.android.ui.activity.ManageSpaceActivity;
@@ -84,7 +83,6 @@ abstract class ComponentsModule {
     @ContributesAndroidInjector abstract FilePickerActivity filePickerActivity();
     @ContributesAndroidInjector abstract FilePickerActivity filePickerActivity();
     @ContributesAndroidInjector abstract FirstRunActivity firstRunActivity();
     @ContributesAndroidInjector abstract FirstRunActivity firstRunActivity();
     @ContributesAndroidInjector abstract FolderPickerActivity folderPickerActivity();
     @ContributesAndroidInjector abstract FolderPickerActivity folderPickerActivity();
-    @ContributesAndroidInjector abstract HookActivity hookActivity();
     @ContributesAndroidInjector abstract LogHistoryActivity logHistoryActivity();
     @ContributesAndroidInjector abstract LogHistoryActivity logHistoryActivity();
     @ContributesAndroidInjector abstract ManageAccountsActivity manageAccountsActivity();
     @ContributesAndroidInjector abstract ManageAccountsActivity manageAccountsActivity();
     @ContributesAndroidInjector abstract ManageSpaceActivity manageSpaceActivity();
     @ContributesAndroidInjector abstract ManageSpaceActivity manageSpaceActivity();

+ 7 - 7
src/main/java/com/owncloud/android/datamodel/FileDataStorageManager.java

@@ -369,8 +369,9 @@ public class FileDataStorageManager {
 
 
                     if (file.isDown()) {
                     if (file.isDown()) {
                         String path = file.getStoragePath();
                         String path = file.getStoragePath();
-                        new File(path).delete();
-                        triggerMediaScan(path); // notify MediaScanner about removed file
+                        if (new File(path).delete()) {
+                            triggerMediaScan(path); // notify MediaScanner about removed file
+                        }
                     }
                     }
                 }
                 }
             }
             }
@@ -726,8 +727,8 @@ public class FileDataStorageManager {
             if (localFile.exists()) {
             if (localFile.exists()) {
                 File targetFile = new File(targetLocalPath);
                 File targetFile = new File(targetLocalPath);
                 File targetFolder = targetFile.getParentFile();
                 File targetFolder = targetFile.getParentFile();
-                if (!targetFolder.exists()) {
-                    targetFolder.mkdirs();
+                if (!targetFolder.exists() && !targetFolder.mkdirs()) {
+                    Log_OC.e(TAG, "Unable to create parent folder " + targetFolder.getAbsolutePath());
                 }
                 }
                 renamed = localFile.renameTo(targetFile);
                 renamed = localFile.renameTo(targetFile);
             }
             }
@@ -745,7 +746,6 @@ public class FileDataStorageManager {
                 }
                 }
             }
             }
         }
         }
-
     }
     }
 
 
     public void copyLocalFile(OCFile file, String targetPath) {
     public void copyLocalFile(OCFile file, String targetPath) {
@@ -758,8 +758,8 @@ public class FileDataStorageManager {
             if (localFile.exists()) {
             if (localFile.exists()) {
                 File targetFile = new File(defaultSavePath + targetPath);
                 File targetFile = new File(defaultSavePath + targetPath);
                 File targetFolder = targetFile.getParentFile();
                 File targetFolder = targetFile.getParentFile();
-                if (!targetFolder.exists()) {
-                    targetFolder.mkdirs();
+                if (!targetFolder.exists() && !targetFolder.mkdirs()) {
+                    Log_OC.e(TAG, "Unable to create parent folder " + targetFolder.getAbsolutePath());
                 }
                 }
                 copied = FileStorageUtils.copyFile(localFile, targetFile);
                 copied = FileStorageUtils.copyFile(localFile, targetFile);
             }
             }

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

@@ -61,6 +61,8 @@ import java.io.IOException;
 import java.lang.ref.WeakReference;
 import java.lang.ref.WeakReference;
 
 
 import androidx.core.app.NotificationCompat;
 import androidx.core.app.NotificationCompat;
+import lombok.Getter;
+import lombok.Setter;
 
 
 
 
 /**
 /**
@@ -101,10 +103,10 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     private static final float DUCK_VOLUME = 0.1f;
     private static final float DUCK_VOLUME = 0.1f;
 
 
     /** Media player instance */
     /** Media player instance */
-    private MediaPlayer mPlayer;
+    @Getter private MediaPlayer player;
 
 
     /** Reference to the system AudioManager */
     /** Reference to the system AudioManager */
-    private AudioManager mAudioManager;
+    private AudioManager audioManager;
 
 
 
 
     /** Values to indicate the state of the service */
     /** Values to indicate the state of the service */
@@ -116,7 +118,7 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     }
     }
 
 
     /** Current state */
     /** Current state */
-    private State mState = State.STOPPED;
+    @Getter private State state = State.STOPPED;
 
 
     /** Possible focus values */
     /** Possible focus values */
     enum AudioFocus {
     enum AudioFocus {
@@ -126,36 +128,36 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     }
     }
 
 
     /** Current focus state */
     /** Current focus state */
-    private AudioFocus mAudioFocus = AudioFocus.NO_FOCUS;
+    private AudioFocus audioFocus = AudioFocus.NO_FOCUS;
 
 
     /** Wifi lock kept to prevents the device from shutting off the radio when streaming a file. */
     /** Wifi lock kept to prevents the device from shutting off the radio when streaming a file. */
-    private WifiLock mWifiLock;
+    private WifiLock wifiLock;
 
 
     private static final String MEDIA_WIFI_LOCK_TAG = MY_PACKAGE + ".WIFI_LOCK";
     private static final String MEDIA_WIFI_LOCK_TAG = MY_PACKAGE + ".WIFI_LOCK";
 
 
     /** Notification to keep in the notification bar while a song is playing */
     /** Notification to keep in the notification bar while a song is playing */
-    private NotificationManager mNotificationManager;
+    private NotificationManager notificationManager;
 
 
     /** File being played */
     /** File being played */
-    private OCFile mFile;
+    @Getter private OCFile currentFile;
 
 
     /** Account holding the file being played */
     /** Account holding the file being played */
-    private Account mAccount;
+    private Account account;
 
 
     /** Flag signaling if the audio should be played immediately when the file is prepared */
     /** Flag signaling if the audio should be played immediately when the file is prepared */
-    protected boolean mPlayOnPrepared;
+    protected boolean playOnPrepared;
 
 
     /** Position, in milliseconds, where the audio should be started */
     /** Position, in milliseconds, where the audio should be started */
-    private int mStartPosition;
+    private int startPosition;
 
 
     /** Interface to access the service through binding */
     /** Interface to access the service through binding */
-    private IBinder mBinder;
+    private IBinder binder;
 
 
     /** Control panel shown to the user to control the playback, to register through binding */
     /** Control panel shown to the user to control the playback, to register through binding */
-    private MediaControlView mMediaController;
+    @Getter @Setter private MediaControlView mediaController;
 
 
     /** Notification builder to create notifications, new reuse way since Android 6 */
     /** Notification builder to create notifications, new reuse way since Android 6 */
-    private NotificationCompat.Builder mNotificationBuilder;
+    private NotificationCompat.Builder notificationBuilder;
 
 
     /**
     /**
      * Helper method to get an error message suitable to show to users for errors occurred in media playback,
      * Helper method to get an error message suitable to show to users for errors occurred in media playback,
@@ -236,14 +238,14 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
         super.onCreate();
         super.onCreate();
         Log_OC.d(TAG, "Creating ownCloud media service");
         Log_OC.d(TAG, "Creating ownCloud media service");
 
 
-        mWifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)).
+        wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)).
                 createWifiLock(WifiManager.WIFI_MODE_FULL, MEDIA_WIFI_LOCK_TAG);
                 createWifiLock(WifiManager.WIFI_MODE_FULL, MEDIA_WIFI_LOCK_TAG);
 
 
-        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
-        mNotificationBuilder = new NotificationCompat.Builder(this);
-        mNotificationBuilder.setColor(ThemeUtils.primaryColor(this));
-        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
-        mBinder = new MediaServiceBinder(this);
+        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+        notificationBuilder = new NotificationCompat.Builder(this);
+        notificationBuilder.setColor(ThemeUtils.primaryColor(this));
+        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
+        binder = new MediaServiceBinder(this);
     }
     }
 
 
 
 
@@ -255,10 +257,9 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     @Override
     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
     public int onStartCommand(Intent intent, int flags, int startId) {
         String action = intent.getAction();
         String action = intent.getAction();
-        if (action.equals(ACTION_PLAY_FILE)) {
+        if (ACTION_PLAY_FILE.equals(action)) {
             processPlayFileRequest(intent);
             processPlayFileRequest(intent);
-
-        } else if (action.equals(ACTION_STOP_ALL)) {
+        } else if (ACTION_STOP_ALL.equals(action)) {
             processStopRequest(true);
             processStopRequest(true);
         }
         }
 
 
@@ -274,11 +275,11 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      * @param intent    Intent received in the request with the data to identify the file to play.
      * @param intent    Intent received in the request with the data to identify the file to play.
      */
      */
     private void processPlayFileRequest(Intent intent) {
     private void processPlayFileRequest(Intent intent) {
-        if (mState != State.PREPARING) {
-            mFile = intent.getExtras().getParcelable(EXTRA_FILE);
-            mAccount = intent.getExtras().getParcelable(EXTRA_ACCOUNT);
-            mPlayOnPrepared = intent.getExtras().getBoolean(EXTRA_PLAY_ON_LOAD, false);
-            mStartPosition = intent.getExtras().getInt(EXTRA_START_POSITION, 0);
+        if (state != State.PREPARING) {
+            currentFile = intent.getExtras().getParcelable(EXTRA_FILE);
+            account = intent.getExtras().getParcelable(EXTRA_ACCOUNT);
+            playOnPrepared = intent.getExtras().getBoolean(EXTRA_PLAY_ON_LOAD, false);
+            startPosition = intent.getExtras().getInt(EXTRA_START_POSITION, 0);
             tryToGetAudioFocus();
             tryToGetAudioFocus();
             playMedia();
             playMedia();
         }
         }
@@ -293,14 +294,14 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
         tryToGetAudioFocus();
         tryToGetAudioFocus();
 
 
         // actually play the song
         // actually play the song
-        if (mState == State.STOPPED) {
+        if (state == State.STOPPED) {
             // (re)start playback
             // (re)start playback
             playMedia();
             playMedia();
 
 
-        } else if (mState == State.PAUSED) {
+        } else if (state == State.PAUSED) {
             // continue playback
             // continue playback
-            mState = State.PLAYING;
-            setUpAsForeground(String.format(getString(R.string.media_state_playing), mFile.getFileName()));
+            state = State.PLAYING;
+            setUpAsForeground(String.format(getString(R.string.media_state_playing), currentFile.getFileName()));
             configAndStartMediaPlayer();
             configAndStartMediaPlayer();
         }
         }
     }
     }
@@ -311,19 +312,19 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      * if needed. reset the existing media player if one already exists.
      * if needed. reset the existing media player if one already exists.
      */
      */
     protected void createMediaPlayerIfNeeded() {
     protected void createMediaPlayerIfNeeded() {
-        if (mPlayer == null) {
-            mPlayer = new MediaPlayer();
+        if (player == null) {
+            player = new MediaPlayer();
 
 
             // make sure the CPU won't go to sleep while media is playing
             // make sure the CPU won't go to sleep while media is playing
-            mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
+            player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
 
 
             // the media player will notify the service when it's ready preparing, and when it's done playing
             // the media player will notify the service when it's ready preparing, and when it's done playing
-            mPlayer.setOnPreparedListener(this);
-            mPlayer.setOnCompletionListener(this);
-            mPlayer.setOnErrorListener(this);
+            player.setOnPreparedListener(this);
+            player.setOnCompletionListener(this);
+            player.setOnErrorListener(this);
 
 
         } else {
         } else {
-            mPlayer.reset();
+            player.reset();
         }
         }
     }
     }
 
 
@@ -331,9 +332,9 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      * Processes a request to pause the current playback
      * Processes a request to pause the current playback
      */
      */
     protected void processPauseRequest() {
     protected void processPauseRequest() {
-        if (mState == State.PLAYING) {
-            mState = State.PAUSED;
-            mPlayer.pause();
+        if (state == State.PLAYING) {
+            state = State.PAUSED;
+            player.pause();
             releaseResources(false); // retain media player in pause
             releaseResources(false); // retain media player in pause
             // TODO polite audio focus, instead of keep it owned; or not?
             // TODO polite audio focus, instead of keep it owned; or not?
         }
         }
@@ -343,13 +344,13 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     /**
     /**
      * Processes a request to stop the playback.
      * Processes a request to stop the playback.
      *
      *
-     * @param   force       When 'true', the playback is stopped no matter the value of mState
+     * @param   force       When 'true', the playback is stopped no matter the value of state
      */
      */
     protected void processStopRequest(boolean force) {
     protected void processStopRequest(boolean force) {
-        if (mState != State.PREPARING || force) {
-            mState = State.STOPPED;
-            mFile = null;
-            mAccount = null;
+        if (state != State.PREPARING || force) {
+            state = State.STOPPED;
+            currentFile = null;
+            account = null;
             releaseResources(true);
             releaseResources(true);
             giveUpAudioFocus();
             giveUpAudioFocus();
             stopSelf();     // service is no longer necessary
             stopSelf();     // service is no longer necessary
@@ -368,15 +369,15 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
         stopForeground(true);
         stopForeground(true);
 
 
         // stop and release the Media Player, if it's available
         // stop and release the Media Player, if it's available
-        if (releaseMediaPlayer && mPlayer != null) {
-            mPlayer.reset();
-            mPlayer.release();
-            mPlayer = null;
+        if (releaseMediaPlayer && player != null) {
+            player.reset();
+            player.release();
+            player = null;
         }
         }
 
 
         // release the Wifi lock, if holding it
         // release the Wifi lock, if holding it
-        if (mWifiLock.isHeld()) {
-            mWifiLock.release();
+        if (wifiLock.isHeld()) {
+            wifiLock.release();
         }
         }
     }
     }
 
 
@@ -384,11 +385,11 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      * Fully releases the audio focus.
      * Fully releases the audio focus.
      */
      */
     private void giveUpAudioFocus() {
     private void giveUpAudioFocus() {
-        if (mAudioFocus == AudioFocus.FOCUS
-                && mAudioManager != null
-                && AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.abandonAudioFocus(this)) {
+        if (audioFocus == AudioFocus.FOCUS
+                && audioManager != null
+                && AudioManager.AUDIOFOCUS_REQUEST_GRANTED == audioManager.abandonAudioFocus(this)) {
 
 
-            mAudioFocus = AudioFocus.NO_FOCUS;
+            audioFocus = AudioFocus.NO_FOCUS;
         }
         }
     }
     }
 
 
@@ -397,25 +398,25 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      * Reconfigures MediaPlayer according to audio focus settings and starts/restarts it.
      * Reconfigures MediaPlayer according to audio focus settings and starts/restarts it.
      */
      */
     protected void configAndStartMediaPlayer() {
     protected void configAndStartMediaPlayer() {
-        if (mPlayer == null) {
-            throw new IllegalStateException("mPlayer is NULL");
+        if (player == null) {
+            throw new IllegalStateException("player is NULL");
         }
         }
 
 
-        if (mAudioFocus == AudioFocus.NO_FOCUS) {
-            if (mPlayer.isPlaying()) {
-                mPlayer.pause();        // have to be polite; but mState is not changed, to resume when focus is received again
+        if (audioFocus == AudioFocus.NO_FOCUS) {
+            if (player.isPlaying()) {
+                player.pause();        // have to be polite; but state is not changed, to resume when focus is received again
             }
             }
 
 
         } else {
         } else {
-            if (mAudioFocus == AudioFocus.NO_FOCUS_CAN_DUCK) {
-                mPlayer.setVolume(DUCK_VOLUME, DUCK_VOLUME);
+            if (audioFocus == AudioFocus.NO_FOCUS_CAN_DUCK) {
+                player.setVolume(DUCK_VOLUME, DUCK_VOLUME);
 
 
             } else {
             } else {
-                mPlayer.setVolume(1.0f, 1.0f); // full volume
+                player.setVolume(1.0f, 1.0f); // full volume
             }
             }
 
 
-            if (!mPlayer.isPlaying()) {
-                mPlayer.start();
+            if (!player.isPlaying()) {
+                player.start();
             }
             }
         }
         }
     }
     }
@@ -425,13 +426,13 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      * Requests the audio focus to the Audio Manager
      * Requests the audio focus to the Audio Manager
      */
      */
     private void tryToGetAudioFocus() {
     private void tryToGetAudioFocus() {
-        if (mAudioFocus != AudioFocus.FOCUS
-                && mAudioManager != null
-                && AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus(this,
-                AudioManager.STREAM_MUSIC,
-                AudioManager.AUDIOFOCUS_GAIN)
+        if (audioFocus != AudioFocus.FOCUS
+                && audioManager != null
+                && AudioManager.AUDIOFOCUS_REQUEST_GRANTED == audioManager.requestAudioFocus(this,
+                                                                                             AudioManager.STREAM_MUSIC,
+                                                                                             AudioManager.AUDIOFOCUS_GAIN)
                 ) {
                 ) {
-            mAudioFocus = AudioFocus.FOCUS;
+            audioFocus = AudioFocus.FOCUS;
         }
         }
     }
     }
 
 
@@ -440,60 +441,60 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      * Starts playing the current media file.
      * Starts playing the current media file.
      */
      */
     protected void playMedia() {
     protected void playMedia() {
-        mState = State.STOPPED;
+        state = State.STOPPED;
         releaseResources(false); // release everything except MediaPlayer
         releaseResources(false); // release everything except MediaPlayer
 
 
         try {
         try {
-            if (mFile == null) {
+            if (currentFile == null) {
                 Toast.makeText(this, R.string.media_err_nothing_to_play, Toast.LENGTH_LONG).show();
                 Toast.makeText(this, R.string.media_err_nothing_to_play, Toast.LENGTH_LONG).show();
                 processStopRequest(true);
                 processStopRequest(true);
                 return;
                 return;
 
 
-            } else if (mAccount == null) {
+            } else if (account == null) {
                 Toast.makeText(this, R.string.media_err_not_in_owncloud, Toast.LENGTH_LONG).show();
                 Toast.makeText(this, R.string.media_err_not_in_owncloud, Toast.LENGTH_LONG).show();
                 processStopRequest(true);
                 processStopRequest(true);
                 return;
                 return;
             }
             }
 
 
             createMediaPlayerIfNeeded();
             createMediaPlayerIfNeeded();
-            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
+            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
 
 
-            if (mFile.isDown()) {
-                mPlayer.setDataSource(mFile.getStoragePath());
+            if (currentFile.isDown()) {
+                player.setDataSource(currentFile.getStoragePath());
                 preparePlayer();
                 preparePlayer();
             } else {
             } else {
-                OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, getBaseContext());
+                OwnCloudAccount ocAccount = new OwnCloudAccount(account, getBaseContext());
                 OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton().
                 OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton().
                         getClientFor(ocAccount, getBaseContext());
                         getClientFor(ocAccount, getBaseContext());
 
 
-                new LoadStreamUrl(this, client).execute(mFile.getLocalId());
+                new LoadStreamUrl(this, client).execute(currentFile.getLocalId());
             }
             }
         } catch (AccountUtils.AccountNotFoundException | OperationCanceledException | AuthenticatorException e) {
         } catch (AccountUtils.AccountNotFoundException | OperationCanceledException | AuthenticatorException e) {
             Log_OC.e(TAG, "Loading stream url not possible: " + e.getMessage());
             Log_OC.e(TAG, "Loading stream url not possible: " + e.getMessage());
         } catch (SecurityException | IOException | IllegalStateException | IllegalArgumentException e) {
         } catch (SecurityException | IOException | IllegalStateException | IllegalArgumentException e) {
-            Log_OC.e(TAG, e.getClass().getSimpleName() + " playing " + mAccount.name + mFile.getRemotePath(), e);
-            Toast.makeText(this, String.format(getString(R.string.media_err_playing), mFile.getFileName()),
+            Log_OC.e(TAG, e.getClass().getSimpleName() + " playing " + account.name + currentFile.getRemotePath(), e);
+            Toast.makeText(this, String.format(getString(R.string.media_err_playing), currentFile.getFileName()),
                     Toast.LENGTH_LONG).show();
                     Toast.LENGTH_LONG).show();
             processStopRequest(true);
             processStopRequest(true);
         }
         }
     }
     }
 
 
     private void preparePlayer() {
     private void preparePlayer() {
-        mState = State.PREPARING;
-        setUpAsForeground(String.format(getString(R.string.media_state_loading), mFile.getFileName()));
+        state = State.PREPARING;
+        setUpAsForeground(String.format(getString(R.string.media_state_loading), currentFile.getFileName()));
 
 
         // starts preparing the media player in background
         // starts preparing the media player in background
-        mPlayer.prepareAsync();
+        player.prepareAsync();
     }
     }
 
 
     /** Called when media player is done playing current song. */
     /** Called when media player is done playing current song. */
     public void onCompletion(MediaPlayer player) {
     public void onCompletion(MediaPlayer player) {
-        Toast.makeText(this, String.format(getString(R.string.media_event_done), mFile.getFileName()), Toast.LENGTH_LONG).show();
-        if (mMediaController != null) {
+        Toast.makeText(this, String.format(getString(R.string.media_event_done), currentFile.getFileName()), Toast.LENGTH_LONG).show();
+        if (mediaController != null) {
             // somebody is still bound to the service
             // somebody is still bound to the service
             player.seekTo(0);
             player.seekTo(0);
             processPauseRequest();
             processPauseRequest();
-            mMediaController.updatePausePlay();
+            mediaController.updatePausePlay();
         } else {
         } else {
             // nobody is bound
             // nobody is bound
             processStopRequest(true);
             processStopRequest(true);
@@ -507,19 +508,19 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      * Time to start.
      * Time to start.
      */
      */
     public void onPrepared(MediaPlayer player) {
     public void onPrepared(MediaPlayer player) {
-        mState = State.PLAYING;
-        updateNotification(String.format(getString(R.string.media_state_playing), mFile.getFileName()));
-        if (mMediaController != null) {
-            mMediaController.setEnabled(true);
+        state = State.PLAYING;
+        updateNotification(String.format(getString(R.string.media_state_playing), currentFile.getFileName()));
+        if (mediaController != null) {
+            mediaController.setEnabled(true);
         }
         }
-        player.seekTo(mStartPosition);
+        player.seekTo(startPosition);
         configAndStartMediaPlayer();
         configAndStartMediaPlayer();
-        if (!mPlayOnPrepared) {
+        if (!playOnPrepared) {
             processPauseRequest();
             processPauseRequest();
         }
         }
 
 
-        if (mMediaController != null) {
-            mMediaController.updatePausePlay();
+        if (mediaController != null) {
+            mediaController.updatePausePlay();
         }
         }
     }
     }
 
 
@@ -532,24 +533,24 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
 
 
         // TODO check if updating the Intent is really necessary
         // TODO check if updating the Intent is really necessary
         Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
         Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
-        showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, mFile);
-        showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
+        showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, currentFile);
+        showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, account);
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 
 
-        mNotificationBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),
-                (int) System.currentTimeMillis(),
-                showDetailsIntent,
-                PendingIntent.FLAG_UPDATE_CURRENT));
-        mNotificationBuilder.setWhen(System.currentTimeMillis());
-        mNotificationBuilder.setTicker(ticker);
-        mNotificationBuilder.setContentTitle(ticker);
-        mNotificationBuilder.setContentText(content);
+        notificationBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),
+                                                                       (int) System.currentTimeMillis(),
+                                                                       showDetailsIntent,
+                                                                       PendingIntent.FLAG_UPDATE_CURRENT));
+        notificationBuilder.setWhen(System.currentTimeMillis());
+        notificationBuilder.setTicker(ticker);
+        notificationBuilder.setContentTitle(ticker);
+        notificationBuilder.setContentText(content);
 
 
         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
-            mNotificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA);
+            notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA);
         }
         }
 
 
-        mNotificationManager.notify(R.string.media_notif_ticker, mNotificationBuilder.build());
+        notificationManager.notify(R.string.media_notif_ticker, notificationBuilder.build());
     }
     }
 
 
 
 
@@ -565,28 +566,28 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
 
 
         /// creates status notification
         /// creates status notification
         // TODO put a progress bar to follow the playback progress
         // TODO put a progress bar to follow the playback progress
-        mNotificationBuilder.setSmallIcon(R.drawable.ic_play_arrow);
+        notificationBuilder.setSmallIcon(R.drawable.ic_play_arrow);
         //mNotification.tickerText = text;
         //mNotification.tickerText = text;
-        mNotificationBuilder.setWhen(System.currentTimeMillis());
-        mNotificationBuilder.setOngoing(true);
+        notificationBuilder.setWhen(System.currentTimeMillis());
+        notificationBuilder.setOngoing(true);
 
 
         /// includes a pending intent in the notification showing the details view of the file
         /// includes a pending intent in the notification showing the details view of the file
         Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
         Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
-        showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, mFile);
-        showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
+        showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, currentFile);
+        showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, account);
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-        mNotificationBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),
-                (int) System.currentTimeMillis(),
-                showDetailsIntent,
-                PendingIntent.FLAG_UPDATE_CURRENT));
-        mNotificationBuilder.setContentTitle(ticker);
-        mNotificationBuilder.setContentText(content);
+        notificationBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(),
+                                                                       (int) System.currentTimeMillis(),
+                                                                       showDetailsIntent,
+                                                                       PendingIntent.FLAG_UPDATE_CURRENT));
+        notificationBuilder.setContentTitle(ticker);
+        notificationBuilder.setContentText(content);
 
 
         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
-            mNotificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA);
+            notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA);
         }
         }
 
 
-        startForeground(R.string.media_notif_ticker, mNotificationBuilder.build());
+        startForeground(R.string.media_notif_ticker, notificationBuilder.build());
     }
     }
 
 
     /**
     /**
@@ -613,18 +614,18 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     public void onAudioFocusChange(int focusChange) {
     public void onAudioFocusChange(int focusChange) {
         if (focusChange > 0) {
         if (focusChange > 0) {
             // focus gain; check AudioManager.AUDIOFOCUS_* values
             // focus gain; check AudioManager.AUDIOFOCUS_* values
-            mAudioFocus = AudioFocus.FOCUS;
+            audioFocus = AudioFocus.FOCUS;
             // restart media player with new focus settings
             // restart media player with new focus settings
-            if (mState == State.PLAYING) {
+            if (state == State.PLAYING) {
                 configAndStartMediaPlayer();
                 configAndStartMediaPlayer();
             }
             }
 
 
         } else if (focusChange < 0) {
         } else if (focusChange < 0) {
             // focus loss; check AudioManager.AUDIOFOCUS_* values
             // focus loss; check AudioManager.AUDIOFOCUS_* values
             boolean canDuck = AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK == focusChange;
             boolean canDuck = AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK == focusChange;
-            mAudioFocus = canDuck ? AudioFocus.NO_FOCUS_CAN_DUCK : AudioFocus.NO_FOCUS;
+            audioFocus = canDuck ? AudioFocus.NO_FOCUS_CAN_DUCK : AudioFocus.NO_FOCUS;
             // start/restart/pause media player with new focus settings
             // start/restart/pause media player with new focus settings
-            if (mPlayer != null && mPlayer.isPlaying()) {
+            if (player != null && player.isPlaying()) {
                 configAndStartMediaPlayer();
                 configAndStartMediaPlayer();
             }
             }
         }
         }
@@ -638,7 +639,7 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      */
      */
     @Override
     @Override
     public void onDestroy() {
     public void onDestroy() {
-        mState = State.STOPPED;
+        state = State.STOPPED;
         releaseResources(true);
         releaseResources(true);
         giveUpAudioFocus();
         giveUpAudioFocus();
         stopForeground(true);
         stopForeground(true);
@@ -651,7 +652,7 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      */
      */
     @Override
     @Override
     public IBinder onBind(Intent arg) {
     public IBinder onBind(Intent arg) {
-        return mBinder;
+        return binder;
     }
     }
 
 
 
 
@@ -662,53 +663,12 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
      */
      */
     @Override
     @Override
     public boolean onUnbind(Intent intent) {
     public boolean onUnbind(Intent intent) {
-        if (mState == State.PAUSED || mState == State.STOPPED) {
+        if (state == State.PAUSED || state == State.STOPPED) {
             processStopRequest(false);
             processStopRequest(false);
         }
         }
         return false;   // not accepting rebinding (default behaviour)
         return false;   // not accepting rebinding (default behaviour)
     }
     }
 
 
-
-    /**
-     * Accesses the current MediaPlayer instance in the service.
-     *
-     * To be handled carefully. Visibility is protected to be accessed only
-     *
-     * @return Current MediaPlayer instance handled by MediaService.
-     */
-    protected MediaPlayer getPlayer() {
-        return mPlayer;
-    }
-
-
-    /**
-     * Accesses the current OCFile loaded in the service.
-     *
-     * @return The current OCFile loaded in the service.
-     */
-    protected OCFile getCurrentFile() {
-        return mFile;
-    }
-
-
-    /**
-     * Accesses the current {@link State} of the MediaService.
-     *
-     * @return The current {@link State} of the MediaService.
-     */
-    protected State getState() {
-        return mState;
-    }
-
-
-    protected void setMediaController(MediaControlView mediaController) {
-        mMediaController = mediaController;
-    }
-
-    protected MediaControlView getMediaController() {
-        return mMediaController;
-    }
-
     private static class LoadStreamUrl extends AsyncTask<String, Void, String> {
     private static class LoadStreamUrl extends AsyncTask<String, Void, String> {
 
 
         private OwnCloudClient client;
         private OwnCloudClient client;
@@ -738,10 +698,10 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
             if (mediaService != null && mediaService.getCurrentFile() != null) {
             if (mediaService != null && mediaService.getCurrentFile() != null) {
                 if (url != null) {
                 if (url != null) {
                     try {
                     try {
-                        mediaService.mPlayer.setDataSource(url);
+                        mediaService.player.setDataSource(url);
 
 
                         // prevent the Wifi from going to sleep when streaming
                         // prevent the Wifi from going to sleep when streaming
-                        mediaService.mWifiLock.acquire();
+                        mediaService.wifiLock.acquire();
                         mediaService.preparePlayer();
                         mediaService.preparePlayer();
                     } catch (IOException e) {
                     } catch (IOException e) {
                         Log_OC.e(TAG, "Streaming not possible: " + e.getMessage());
                         Log_OC.e(TAG, "Streaming not possible: " + e.getMessage());

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

@@ -118,7 +118,7 @@ public class MediaServiceBinder extends Binder implements MediaController.MediaP
     @Override
     @Override
     public boolean isPlaying() {
     public boolean isPlaying() {
         MediaService.State currentState = mService.getState();
         MediaService.State currentState = mService.getState();
-        return currentState == State.PLAYING || (currentState == State.PREPARING && mService.mPlayOnPrepared);
+        return currentState == State.PLAYING || (currentState == State.PREPARING && mService.playOnPrepared);
     }
     }
 
 
 
 

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

@@ -45,26 +45,27 @@ import java.util.Iterator;
 import java.util.Set;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 
+import lombok.Getter;
+
 /**
 /**
- * Remote mDownloadOperation performing the download of a file to an ownCloud server
+ * Remote DownloadOperation performing the download of a file to an ownCloud server
  */
  */
 public class DownloadFileOperation extends RemoteOperation {
 public class DownloadFileOperation extends RemoteOperation {
-
     private static final String TAG = DownloadFileOperation.class.getSimpleName();
     private static final String TAG = DownloadFileOperation.class.getSimpleName();
-    private Account mAccount;
 
 
-    private OCFile mFile;
-    private String mBehaviour;
-    private Context mContext;
-    private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<>();
-    private long mModificationTimestamp;
-    private String mEtag = "";
-    private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
+    @Getter private Account account;
+    @Getter private OCFile file;
+    @Getter private String behaviour;
+    @Getter private String etag = "";
+    @Getter private String activityName;
+    @Getter private String packageName;
 
 
-    private DownloadFileRemoteOperation mDownloadOperation;
-    private String mActivityName;
-    private String mPackageName;
+    private Context context;
+    private Set<OnDatatransferProgressListener> dataTransferListeners = new HashSet<>();
+    private long modificationTimestamp;
+    private DownloadFileRemoteOperation downloadOperation;
 
 
+    private final AtomicBoolean cancellationRequested = new AtomicBoolean(false);
 
 
     public DownloadFileOperation(Account account, OCFile file, String behaviour, String activityName,
     public DownloadFileOperation(Account account, OCFile file, String behaviour, String activityName,
                                  String packageName, Context context) {
                                  String packageName, Context context) {
@@ -77,60 +78,47 @@ public class DownloadFileOperation extends RemoteOperation {
                     "creation");
                     "creation");
         }
         }
 
 
-        mAccount = account;
-        mFile = file;
-        mBehaviour = behaviour;
-        mActivityName = activityName;
-        mPackageName = packageName;
-        mContext = context;
-    }
-
-
-    public Account getAccount() {
-        return mAccount;
-    }
-
-    public OCFile getFile() {
-        return mFile;
-    }
-
-    public String getBehaviour() {
-        return mBehaviour;
+        this.account = account;
+        this.file = file;
+        this.behaviour = behaviour;
+        this.activityName = activityName;
+        this.packageName = packageName;
+        this.context = context;
     }
     }
 
 
     public String getSavePath() {
     public String getSavePath() {
-        if (mFile.getStoragePath() != null) {
-            File path = new File(mFile.getStoragePath());  // re-downloads should be done over the original file
+        if (file.getStoragePath() != null) {
+            File path = new File(file.getStoragePath());  // re-downloads should be done over the original file
             if (path.canWrite()) {
             if (path.canWrite()) {
                 return path.getAbsolutePath();
                 return path.getAbsolutePath();
             }
             }
         }
         }
-        return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
+        return FileStorageUtils.getDefaultSavePathFor(account.name, file);
     }
     }
 
 
     public String getTmpPath() {
     public String getTmpPath() {
-        return FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
+        return FileStorageUtils.getTemporalPath(account.name) + file.getRemotePath();
     }
     }
 
 
     public String getTmpFolder() {
     public String getTmpFolder() {
-        return FileStorageUtils.getTemporalPath(mAccount.name);
+        return FileStorageUtils.getTemporalPath(account.name);
     }
     }
 
 
     public String getRemotePath() {
     public String getRemotePath() {
-        return mFile.getRemotePath();
+        return file.getRemotePath();
     }
     }
 
 
     public String getMimeType() {
     public String getMimeType() {
-        String mimeType = mFile.getMimeType();
+        String mimeType = file.getMimeType();
         if (mimeType == null || mimeType.length() <= 0) {
         if (mimeType == null || mimeType.length() <= 0) {
             try {
             try {
                 mimeType = MimeTypeMap.getSingleton()
                 mimeType = MimeTypeMap.getSingleton()
                     .getMimeTypeFromExtension(
                     .getMimeTypeFromExtension(
-                            mFile.getRemotePath().substring(
-                                    mFile.getRemotePath().lastIndexOf('.') + 1));
+                        file.getRemotePath().substring(
+                            file.getRemotePath().lastIndexOf('.') + 1));
             } catch (IndexOutOfBoundsException e) {
             } catch (IndexOutOfBoundsException e) {
                 Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " +
                 Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " +
-                        mFile.getRemotePath());
+                        file.getRemotePath());
             }
             }
         }
         }
         if (mimeType == null) {
         if (mimeType == null) {
@@ -140,22 +128,18 @@ public class DownloadFileOperation extends RemoteOperation {
     }
     }
 
 
     public long getSize() {
     public long getSize() {
-        return mFile.getFileLength();
+        return file.getFileLength();
     }
     }
 
 
     public long getModificationTimestamp() {
     public long getModificationTimestamp() {
-        return mModificationTimestamp > 0 ? mModificationTimestamp : mFile.getModificationTimestamp();
-    }
-
-    public String getEtag() {
-        return mEtag;
+        return modificationTimestamp > 0 ? modificationTimestamp : file.getModificationTimestamp();
     }
     }
 
 
     @Override
     @Override
     protected RemoteOperationResult run(OwnCloudClient client) {
     protected RemoteOperationResult run(OwnCloudClient client) {
         /// perform the download
         /// perform the download
-        synchronized(mCancellationRequested) {
-            if (mCancellationRequested.get()) {
+        synchronized(cancellationRequested) {
+            if (cancellationRequested.get()) {
                 return new RemoteOperationResult(new OperationCancelledException());
                 return new RemoteOperationResult(new OperationCancelledException());
             }
             }
         }
         }
@@ -169,36 +153,38 @@ public class DownloadFileOperation extends RemoteOperation {
 
 
         String tmpFolder =  getTmpFolder();
         String tmpFolder =  getTmpFolder();
 
 
-        mDownloadOperation = new DownloadFileRemoteOperation(mFile.getRemotePath(), tmpFolder);
-        Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
+        downloadOperation = new DownloadFileRemoteOperation(file.getRemotePath(), tmpFolder);
+        Iterator<OnDatatransferProgressListener> listener = dataTransferListeners.iterator();
         while (listener.hasNext()) {
         while (listener.hasNext()) {
-            mDownloadOperation.addDatatransferProgressListener(listener.next());
+            downloadOperation.addDatatransferProgressListener(listener.next());
         }
         }
-        result = mDownloadOperation.execute(client, client.isUseNextcloudUserAgent());
+        result = downloadOperation.execute(client, client.isUseNextcloudUserAgent());
 
 
         if (result.isSuccess()) {
         if (result.isSuccess()) {
-            mModificationTimestamp = mDownloadOperation.getModificationTimestamp();
-            mEtag = mDownloadOperation.getEtag();
+            modificationTimestamp = downloadOperation.getModificationTimestamp();
+            etag = downloadOperation.getEtag();
             newFile = new File(getSavePath());
             newFile = new File(getSavePath());
-            newFile.getParentFile().mkdirs();
+            if (!newFile.getParentFile().mkdirs()) {
+                Log_OC.e(TAG, "Unable to create parent folder " + newFile.getParentFile().getAbsolutePath());
+            }
 
 
             // decrypt file
             // decrypt file
-            if (mFile.isEncrypted() && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
-                FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(mAccount, mContext.getContentResolver());
+            if (file.isEncrypted() && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
+                FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(account, context.getContentResolver());
 
 
-                OCFile parent = fileDataStorageManager.getFileByPath(mFile.getParentRemotePath());
+                OCFile parent = fileDataStorageManager.getFileByPath(file.getParentRemotePath());
 
 
-                DecryptedFolderMetadata metadata = EncryptionUtils.downloadFolderMetadata(parent, client, mContext, mAccount);
+                DecryptedFolderMetadata metadata = EncryptionUtils.downloadFolderMetadata(parent, client, context, account);
 
 
                 if (metadata == null) {
                 if (metadata == null) {
                     return new RemoteOperationResult(RemoteOperationResult.ResultCode.METADATA_NOT_FOUND);
                     return new RemoteOperationResult(RemoteOperationResult.ResultCode.METADATA_NOT_FOUND);
                 }
                 }
                 byte[] key = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
                 byte[] key = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
-                        .get(mFile.getEncryptedFileName()).getEncrypted().getKey());
+                        .get(file.getEncryptedFileName()).getEncrypted().getKey());
                 byte[] iv = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
                 byte[] iv = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
-                        .get(mFile.getEncryptedFileName()).getInitializationVector());
+                        .get(file.getEncryptedFileName()).getInitializationVector());
                 byte[] authenticationTag = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
                 byte[] authenticationTag = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
-                        .get(mFile.getEncryptedFileName()).getAuthenticationTag());
+                        .get(file.getEncryptedFileName()).getAuthenticationTag());
 
 
                 try {
                 try {
                     byte[] decryptedBytes = EncryptionUtils.decryptFile(tmpFile, key, iv, authenticationTag);
                     byte[] decryptedBytes = EncryptionUtils.decryptFile(tmpFile, key, iv, authenticationTag);
@@ -211,42 +197,34 @@ public class DownloadFileOperation extends RemoteOperation {
                 }
                 }
             }
             }
             moved = tmpFile.renameTo(newFile);
             moved = tmpFile.renameTo(newFile);
-            newFile.setLastModified(mFile.getModificationTimestamp());
+            newFile.setLastModified(file.getModificationTimestamp());
             if (!moved) {
             if (!moved) {
                 result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
                 result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
             }
             }
         }
         }
-        Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " +
+        Log_OC.i(TAG, "Download of " + file.getRemotePath() + " to " + getSavePath() + ": " +
                 result.getLogMessage());
                 result.getLogMessage());
 
 
         return result;
         return result;
     }
     }
 
 
     public void cancel() {
     public void cancel() {
-        mCancellationRequested.set(true);   // atomic set; there is no need of synchronizing it
-        if (mDownloadOperation != null) {
-            mDownloadOperation.cancel();
+        cancellationRequested.set(true);   // atomic set; there is no need of synchronizing it
+        if (downloadOperation != null) {
+            downloadOperation.cancel();
         }
         }
     }
     }
 
 
 
 
     public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
     public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
-        synchronized (mDataTransferListeners) {
-            mDataTransferListeners.add(listener);
+        synchronized (dataTransferListeners) {
+            dataTransferListeners.add(listener);
         }
         }
     }
     }
 
 
     public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
     public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
-        synchronized (mDataTransferListeners) {
-            mDataTransferListeners.remove(listener);
+        synchronized (dataTransferListeners) {
+            dataTransferListeners.remove(listener);
         }
         }
     }
     }
-
-    public String getActivityName() {
-        return mActivityName;
-    }
-
-    public String getPackageName() {
-        return mPackageName;
-    }
 }
 }

+ 33 - 35
src/main/java/com/owncloud/android/operations/RenameFileOperation.java

@@ -34,6 +34,8 @@ import com.owncloud.android.utils.FileStorageUtils;
 import java.io.File;
 import java.io.File;
 import java.io.IOException;
 import java.io.IOException;
 
 
+import lombok.Getter;
+
 
 
 /**
 /**
  * Remote operation performing the rename of a remote file (or folder?) in the ownCloud server.
  * Remote operation performing the rename of a remote file (or folder?) in the ownCloud server.
@@ -42,10 +44,9 @@ public class RenameFileOperation extends SyncOperation {
 
 
     private static final String TAG = RenameFileOperation.class.getSimpleName();
     private static final String TAG = RenameFileOperation.class.getSimpleName();
 
 
-    private OCFile mFile;
-    private String mRemotePath;
-    private String mNewName;
-    private String mNewRemotePath;
+    @Getter private OCFile file;
+    private String remotePath;
+    private String newName;
 
 
     /**
     /**
      * Constructor
      * Constructor
@@ -55,16 +56,10 @@ public class RenameFileOperation extends SyncOperation {
      * @param newName               New name to set as the name of file.
      * @param newName               New name to set as the name of file.
      */
      */
     public RenameFileOperation(String remotePath, String newName) {
     public RenameFileOperation(String remotePath, String newName) {
-        mRemotePath = remotePath;
-        mNewName = newName;
-        mNewRemotePath = null;
-    }
-
-    public OCFile getFile() {
-        return mFile;
+        this.remotePath = remotePath;
+        this.newName = newName;
     }
     }
 
 
-
     /**
     /**
      * Performs the rename operation.
      * Performs the rename operation.
      *
      *
@@ -73,32 +68,33 @@ public class RenameFileOperation extends SyncOperation {
     @Override
     @Override
     protected RemoteOperationResult run(OwnCloudClient client) {
     protected RemoteOperationResult run(OwnCloudClient client) {
         RemoteOperationResult result = null;
         RemoteOperationResult result = null;
+        String newRemotePath = null;
 
 
-        mFile = getStorageManager().getFileByPath(mRemotePath);
+        file = getStorageManager().getFileByPath(remotePath);
 
 
         // check if the new name is valid in the local file system
         // check if the new name is valid in the local file system
         try {
         try {
             if (!isValidNewName()) {
             if (!isValidNewName()) {
                 return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME);
                 return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME);
             }
             }
-            String parent = new File(mFile.getRemotePath()).getParent();
+            String parent = new File(file.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;
+            newRemotePath =  parent + newName;
+            if (file.isFolder()) {
+                newRemotePath += OCFile.PATH_SEPARATOR;
             }
             }
 
 
             // check local overwrite
             // check local overwrite
-            if (getStorageManager().getFileByPath(mNewRemotePath) != null) {
+            if (getStorageManager().getFileByPath(newRemotePath) != null) {
                 return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
                 return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
             }
             }
 
 
-            result = new RenameFileRemoteOperation(mFile.getFileName(), mFile.getRemotePath(), mNewName,
-                mFile.isFolder()).execute(client);
+            result = new RenameFileRemoteOperation(file.getFileName(), file.getRemotePath(), newName,
+                                                   file.isFolder()).execute(client);
 
 
             if (result.isSuccess()) {
             if (result.isSuccess()) {
-                if (mFile.isFolder()) {
-                    getStorageManager().moveLocalFile(mFile, mNewRemotePath, parent);
+                if (file.isFolder()) {
+                    getStorageManager().moveLocalFile(file, newRemotePath, parent);
                     //saveLocalDirectory();
                     //saveLocalDirectory();
 
 
                 } else {
                 } else {
@@ -107,8 +103,8 @@ public class RenameFileOperation extends SyncOperation {
             }
             }
 
 
         } catch (IOException e) {
         } catch (IOException e) {
-            Log_OC.e(TAG, "Rename " + mFile.getRemotePath() + " to " + ((mNewRemotePath==null) ?
-                    mNewName : mNewRemotePath) + ": " +
+            Log_OC.e(TAG, "Rename " + file.getRemotePath() + " to " + ((newRemotePath ==null) ?
+                newName : newRemotePath) + ": " +
                     (result!= null ? result.getLogMessage() : ""), e);
                     (result!= null ? result.getLogMessage() : ""), e);
         }
         }
 
 
@@ -116,19 +112,19 @@ public class RenameFileOperation extends SyncOperation {
     }
     }
 
 
     private void saveLocalFile() {
     private void saveLocalFile() {
-        mFile.setFileName(mNewName);
+        file.setFileName(newName);
 
 
         // try to rename the local copy of the file
         // try to rename the local copy of the file
-        if (mFile.isDown()) {
-            String oldPath = mFile.getStoragePath();
+        if (file.isDown()) {
+            String oldPath = file.getStoragePath();
             File f = new File(oldPath);
             File f = new File(oldPath);
             String parentStoragePath = f.getParent();
             String parentStoragePath = f.getParent();
             if (!parentStoragePath.endsWith(File.separator)) {
             if (!parentStoragePath.endsWith(File.separator)) {
                 parentStoragePath += File.separator;
                 parentStoragePath += File.separator;
             }
             }
-            if (f.renameTo(new File(parentStoragePath + mNewName))) {
-                String newPath = parentStoragePath + mNewName;
-                mFile.setStoragePath(newPath);
+            if (f.renameTo(new File(parentStoragePath + newName))) {
+                String newPath = parentStoragePath + newName;
+                file.setStoragePath(newPath);
 
 
                 // notify MediaScanner about removed file
                 // notify MediaScanner about removed file
                 getStorageManager().deleteFileInMediaScan(oldPath);
                 getStorageManager().deleteFileInMediaScan(oldPath);
@@ -140,7 +136,7 @@ public class RenameFileOperation extends SyncOperation {
             // TODO - study conditions when this could be a problem
             // TODO - study conditions when this could be a problem
         }
         }
 
 
-        getStorageManager().saveFile(mFile);
+        getStorageManager().saveFile(file);
     }
     }
 
 
     /**
     /**
@@ -161,14 +157,16 @@ public class RenameFileOperation extends SyncOperation {
      */
      */
     private boolean isValidNewName() throws IOException {
     private boolean isValidNewName() throws IOException {
         // check tricky names
         // check tricky names
-        if (mNewName == null || mNewName.length() <= 0 || mNewName.contains(File.separator)) {
+        if (newName == null || newName.length() <= 0 || newName.contains(File.separator)) {
             return false;
             return false;
         }
         }
         // create a test file
         // create a test file
         String tmpFolderName = FileStorageUtils.getTemporalPath("");
         String tmpFolderName = FileStorageUtils.getTemporalPath("");
-        File testFile = new File(tmpFolderName + mNewName);
+        File testFile = new File(tmpFolderName + newName);
         File tmpFolder = testFile.getParentFile();
         File tmpFolder = testFile.getParentFile();
-        tmpFolder.mkdirs();
+        if (! tmpFolder.mkdirs()) {
+            Log_OC.e(TAG, "Unable to create parent folder " + tmpFolder.getAbsolutePath());
+        }
         if (!tmpFolder.isDirectory()) {
         if (!tmpFolder.isDirectory()) {
             throw new IOException("Unexpected error: temporal directory could not be created");
             throw new IOException("Unexpected error: temporal directory could not be created");
         }
         }
@@ -176,7 +174,7 @@ public class RenameFileOperation extends SyncOperation {
             testFile.createNewFile();   // return value is ignored; it could be 'false' because
             testFile.createNewFile();   // return value is ignored; it could be 'false' because
             // the file already existed, that doesn't invalidate the name
             // the file already existed, that doesn't invalidate the name
         } catch (IOException e) {
         } catch (IOException e) {
-            Log_OC.i(TAG, "Test for validity of name " + mNewName + " in the file system failed");
+            Log_OC.i(TAG, "Test for validity of name " + newName + " in the file system failed");
             return false;
             return false;
         }
         }
         boolean result = testFile.exists() && testFile.isFile();
         boolean result = testFile.exists() && testFile.isFile();

+ 9 - 15
src/main/java/com/owncloud/android/operations/common/SyncOperation.java

@@ -1,4 +1,4 @@
-/**
+/*
  *   ownCloud Android client application
  *   ownCloud Android client application
  *
  *
  *   @author David A. Velasco
  *   @author David A. Velasco
@@ -29,6 +29,8 @@ import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
 import com.owncloud.android.lib.common.operations.RemoteOperation;
 import com.owncloud.android.lib.common.operations.RemoteOperation;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
 
 
+import lombok.Getter;
+
 
 
 /**
 /**
  * Operation which execution involves both interactions with an ownCloud server and
  * Operation which execution involves both interactions with an ownCloud server and
@@ -37,15 +39,9 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  * Provides methods to execute the operation both synchronously or asynchronously.
  * Provides methods to execute the operation both synchronously or asynchronously.
  */
  */
 public abstract class SyncOperation extends RemoteOperation {
 public abstract class SyncOperation extends RemoteOperation {
-	
     //private static final String TAG = SyncOperation.class.getSimpleName();
     //private static final String TAG = SyncOperation.class.getSimpleName();
 
 
-    private FileDataStorageManager mStorageManager;
-    
-    public FileDataStorageManager getStorageManager() {
-        return mStorageManager;
-    }
-	
+    @Getter private FileDataStorageManager storageManager;
 
 
     /**
     /**
      * Synchronously executes the operation on the received ownCloud account.
      * Synchronously executes the operation on the received ownCloud account.
@@ -68,8 +64,8 @@ public abstract class SyncOperation extends RemoteOperation {
             throw new IllegalArgumentException("Trying to execute a sync operation with a " +
             throw new IllegalArgumentException("Trying to execute a sync operation with a " +
                     "storage manager for a NULL account");
                     "storage manager for a NULL account");
         }
         }
-        mStorageManager = storageManager;
-        return super.execute(mStorageManager.getAccount(), context);
+        this.storageManager = storageManager;
+        return super.execute(this.storageManager.getAccount(), context);
     }
     }
     
     
 	
 	
@@ -89,7 +85,7 @@ public abstract class SyncOperation extends RemoteOperation {
             throw new IllegalArgumentException("Trying to execute a sync operation with a " +
             throw new IllegalArgumentException("Trying to execute a sync operation with a " +
                     "NULL storage manager");
                     "NULL storage manager");
         }
         }
-        mStorageManager = storageManager;
+        this.storageManager = storageManager;
 		return super.execute(client);
 		return super.execute(client);
 	}
 	}
 
 
@@ -119,7 +115,7 @@ public abstract class SyncOperation extends RemoteOperation {
             throw new IllegalArgumentException("Trying to execute a sync operation with a
             throw new IllegalArgumentException("Trying to execute a sync operation with a
              storage manager for a NULL account");
              storage manager for a NULL account");
         }
         }
-        mStorageManager = storageManager;
+        storageManager = storageManager;
         return super.execute(storageManager.getAccount(), context, listener, listenerHandler,
         return super.execute(storageManager.getAccount(), context, listener, listenerHandler,
          callerActivity);
          callerActivity);
     }
     }
@@ -142,9 +138,7 @@ public abstract class SyncOperation extends RemoteOperation {
             throw new IllegalArgumentException("Trying to execute a sync operation " +
             throw new IllegalArgumentException("Trying to execute a sync operation " +
                     "with a NULL storage manager");
                     "with a NULL storage manager");
         }
         }
-        mStorageManager = storageManager;
+        this.storageManager = storageManager;
         return super.execute(client, listener, listenerHandler);
         return super.execute(client, listener, listenerHandler);
 	}
 	}
-
-	
 }
 }

+ 18 - 50
src/main/java/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java

@@ -1,10 +1,12 @@
-/**
+/*
  *   ownCloud Android client application
  *   ownCloud Android client application
  *
  *
  *   @author sassman
  *   @author sassman
  *   @author David A. Velasco
  *   @author David A. Velasco
+ *   @author Andy Scherzinger
  *   Copyright (C) 2011  Bartek Przybylski
  *   Copyright (C) 2011  Bartek Przybylski
  *   Copyright (C) 2015 ownCloud Inc.
  *   Copyright (C) 2015 ownCloud Inc.
+ *   Copyright (C) 2019 Andy Scherzinger
  *
  *
  *   This program is free software: you can redistribute it and/or modify
  *   This program is free software: you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License version 2,
  *   it under the terms of the GNU General Public License version 2,
@@ -17,7 +19,6 @@
  *
  *
  *   You should have received a copy of the GNU General Public License
  *   You should have received a copy of the GNU General Public License
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
  */
  */
 
 
 package com.owncloud.android.syncadapter;
 package com.owncloud.android.syncadapter;
@@ -38,74 +39,41 @@ import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundExce
 
 
 import java.io.IOException;
 import java.io.IOException;
 
 
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.Setter;
+
 /**
 /**
  * Base synchronization adapter for ownCloud designed to be subclassed for different
  * Base synchronization adapter for ownCloud designed to be subclassed for different
  * resource types, like FileSync, ConcatsSync, CalendarSync, etc..
  * resource types, like FileSync, ConcatsSync, CalendarSync, etc..
  * 
  * 
  * Implements the standard {@link AbstractThreadedSyncAdapter}.
  * Implements the standard {@link AbstractThreadedSyncAdapter}.
  */
  */
-public abstract class AbstractOwnCloudSyncAdapter extends
+abstract class AbstractOwnCloudSyncAdapter extends
         AbstractThreadedSyncAdapter {
         AbstractThreadedSyncAdapter {
 
 
-    private AccountManager accountManager;
-    private Account account;
-    private ContentProviderClient mContentProviderClient;
-    private FileDataStorageManager mStoreManager;
+    @Getter @Setter private AccountManager accountManager;
+    @Getter @Setter private Account account;
+    @Getter @Setter private ContentProviderClient contentProviderClient;
+    @Getter @Setter private FileDataStorageManager storageManager;
 
 
-    private OwnCloudClient mClient;
+    @Getter(AccessLevel.PROTECTED) private OwnCloudClient client;
 
 
-    public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {
+    AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {
         super(context, autoInitialize);
         super(context, autoInitialize);
         this.setAccountManager(AccountManager.get(context));
         this.setAccountManager(AccountManager.get(context));
     }
     }
 
 
-    public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize,
+    AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize,
                                        boolean allowParallelSyncs) {
                                        boolean allowParallelSyncs) {
         super(context, autoInitialize, allowParallelSyncs);
         super(context, autoInitialize, allowParallelSyncs);
         this.setAccountManager(AccountManager.get(context));
         this.setAccountManager(AccountManager.get(context));
     }
     }
 
 
-    public AccountManager getAccountManager() {
-        return accountManager;
-    }
-
-    public void setAccountManager(AccountManager accountManager) {
-        this.accountManager = accountManager;
-    }
-
-    public Account getAccount() {
-        return account;
-    }
-
-    public void setAccount(Account account) {
-        this.account = account;
-    }
-
-    public ContentProviderClient getContentProviderClient() {
-        return mContentProviderClient;
-    }
-
-    public void setContentProviderClient(ContentProviderClient contentProvider) {
-        this.mContentProviderClient = contentProvider;
-    }
-
-    public void setStorageManager(FileDataStorageManager storage_manager) {
-        mStoreManager = storage_manager;
-    }
-
-    public FileDataStorageManager getStorageManager() {
-        return mStoreManager;
-    }
-
-    protected void initClientForCurrentAccount() throws OperationCanceledException,
+    void initClientForCurrentAccount() throws OperationCanceledException,
             AuthenticatorException, IOException, AccountNotFoundException {
             AuthenticatorException, IOException, AccountNotFoundException {
         OwnCloudAccount ocAccount = new OwnCloudAccount(account, getContext());
         OwnCloudAccount ocAccount = new OwnCloudAccount(account, getContext());
-        mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
+        client = OwnCloudClientManagerFactory.getDefaultSingleton().
                 getClientFor(ocAccount, getContext());
                 getClientFor(ocAccount, getContext());
     }
     }
-    
-    protected OwnCloudClient getClient() {
-        return mClient;
-    }
-    
-}
+}

+ 7 - 8
src/main/java/com/owncloud/android/syncadapter/FileSyncService.java

@@ -1,4 +1,4 @@
-/**
+/*
  *   ownCloud Android client application
  *   ownCloud Android client application
  *
  *
  *   @author Bartek Przybylski
  *   @author Bartek Przybylski
@@ -17,7 +17,6 @@
  *
  *
  *   You should have received a copy of the GNU General Public License
  *   You should have received a copy of the GNU General Public License
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
  */
  */
 package com.owncloud.android.syncadapter;
 package com.owncloud.android.syncadapter;
 
 
@@ -33,18 +32,18 @@ import android.os.IBinder;
 public class FileSyncService extends Service {
 public class FileSyncService extends Service {
     
     
     // Storage for an instance of the sync adapter
     // Storage for an instance of the sync adapter
-    private static FileSyncAdapter sSyncAdapter;
+    private static FileSyncAdapter syncAdapter;
     // Object to use as a thread-safe lock
     // Object to use as a thread-safe lock
-    private static final Object sSyncAdapterLock = new Object();
+    private static final Object syncAdapterLock = new Object();
     
     
     /*
     /*
      * {@inheritDoc}
      * {@inheritDoc}
      */
      */
     @Override
     @Override
     public void onCreate() {
     public void onCreate() {
-        synchronized (sSyncAdapterLock) {
-            if (sSyncAdapter == null) {
-                sSyncAdapter = new FileSyncAdapter(getApplicationContext(), true);
+        synchronized (syncAdapterLock) {
+            if (syncAdapter == null) {
+                syncAdapter = new FileSyncAdapter(getApplicationContext(), true);
             }
             }
         }
         }
     }
     }
@@ -54,7 +53,7 @@ public class FileSyncService extends Service {
      */
      */
     @Override
     @Override
     public IBinder onBind(Intent intent) {
     public IBinder onBind(Intent intent) {
-       return sSyncAdapter.getSyncAdapterBinder();
+       return syncAdapter.getSyncAdapterBinder();
     }
     }
     
     
 }
 }

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

@@ -34,11 +34,6 @@ public abstract class BaseActivity extends AppCompatActivity {
      */
      */
     private OCCapability mCapabilities;
     private OCCapability mCapabilities;
 
 
-    /**
-     * Flag to signal that the activity will is finishing to enforce the creation of an ownCloud {@link Account}.
-     */
-    private boolean mRedirectingToSetupAccount;
-
     /**
     /**
      * Flag to signal when the value of mAccount was set.
      * Flag to signal when the value of mAccount was set.
      */
      */
@@ -117,7 +112,6 @@ public abstract class BaseActivity extends AppCompatActivity {
         if (newAccount == null) {
         if (newAccount == null) {
             /// no account available: force account creation
             /// no account available: force account creation
             createAccount(true);
             createAccount(true);
-            mRedirectingToSetupAccount = true;
             mAccountWasSet = false;
             mAccountWasSet = false;
             mAccountWasRestored = false;
             mAccountWasRestored = false;
 
 
@@ -193,13 +187,6 @@ public abstract class BaseActivity extends AppCompatActivity {
         }
         }
     }
     }
 
 
-    /**
-     * @return 'True' when the Activity is finishing to enforce the setup of a new account.
-     */
-    protected boolean isRedirectingToSetupAccount() {
-        return mRedirectingToSetupAccount;
-    }
-
     public FileDataStorageManager getStorageManager() {
     public FileDataStorageManager getStorageManager() {
         return mStorageManager;
         return mStorageManager;
     }
     }
@@ -211,6 +198,7 @@ public abstract class BaseActivity extends AppCompatActivity {
      */
      */
     protected void onAccountCreationSuccessful(AccountManagerFuture<Bundle> future) {
     protected void onAccountCreationSuccessful(AccountManagerFuture<Bundle> future) {
         // no special handling in base activity
         // no special handling in base activity
+        Log_OC.d(TAG,"onAccountCreationSuccessful");
     }
     }
 
 
     /**
     /**
@@ -232,7 +220,6 @@ public abstract class BaseActivity extends AppCompatActivity {
 
 
         @Override
         @Override
         public void run(AccountManagerFuture<Bundle> future) {
         public void run(AccountManagerFuture<Bundle> future) {
-            BaseActivity.this.mRedirectingToSetupAccount = false;
             boolean accountWasSet = false;
             boolean accountWasSet = false;
             if (future != null) {
             if (future != null) {
                 try {
                 try {

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

@@ -150,7 +150,7 @@ import androidx.fragment.app.FragmentTransaction;
  * Displays, what files the user has available in his ownCloud. This is the main view.
  * Displays, what files the user has available in his ownCloud. This is the main view.
  */
  */
 
 
-public class FileDisplayActivity extends HookActivity
+public class FileDisplayActivity extends FileActivity
         implements FileFragment.ContainerActivity,
         implements FileFragment.ContainerActivity,
         OnEnforceableRefreshListener, SortingOrderDialogFragment.OnSortingOrderListener,
         OnEnforceableRefreshListener, SortingOrderDialogFragment.OnSortingOrderListener,
         SendShareDialog.SendShareDialogDownloader, Injectable {
         SendShareDialog.SendShareDialogDownloader, Injectable {

+ 49 - 44
src/main/java/com/owncloud/android/ui/activity/LogHistoryActivity.java

@@ -27,8 +27,6 @@ import android.os.AsyncTask;
 import android.os.Build;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Bundle;
 import android.view.MenuItem;
 import android.view.MenuItem;
-import android.view.View;
-import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.Button;
 import android.widget.TextView;
 import android.widget.TextView;
 
 
@@ -51,6 +49,10 @@ import androidx.core.content.FileProvider;
 import androidx.fragment.app.Fragment;
 import androidx.fragment.app.Fragment;
 import androidx.fragment.app.FragmentManager;
 import androidx.fragment.app.FragmentManager;
 import androidx.fragment.app.FragmentTransaction;
 import androidx.fragment.app.FragmentTransaction;
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import butterknife.OnClick;
+import butterknife.Unbinder;
 
 
 
 
 public class LogHistoryActivity extends ToolbarActivity {
 public class LogHistoryActivity extends ToolbarActivity {
@@ -63,52 +65,44 @@ public class LogHistoryActivity extends ToolbarActivity {
 
 
     private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
     private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
 
 
-    private String mLogPath = Log_OC.getLogPath();
-    private File logDIR;
-    private String mLogText;
+    private Unbinder unbinder;
 
 
+    private String logPath = Log_OC.getLogPath();
+    private File logDir;
+    private String logText;
+
+    @BindView(R.id.deleteLogHistoryButton)
+    Button deleteHistoryButton;
+
+    @BindView(R.id.sendLogHistoryButton)
+    Button sendHistoryButton;
+
+    @BindView(R.id.logTV)
+    TextView logTV;
 
 
     @Override
     @Override
     protected void onCreate(Bundle savedInstanceState) {
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         super.onCreate(savedInstanceState);
 
 
         setContentView(R.layout.log_send_file);
         setContentView(R.layout.log_send_file);
+        unbinder = ButterKnife.bind(this);
+
         setupToolbar();
         setupToolbar();
 
 
         setTitle(getText(R.string.actionbar_logger));
         setTitle(getText(R.string.actionbar_logger));
         if (getSupportActionBar() != null) {
         if (getSupportActionBar() != null) {
             getSupportActionBar().setDisplayHomeAsUpEnabled(true);
             getSupportActionBar().setDisplayHomeAsUpEnabled(true);
         }
         }
-        Button deleteHistoryButton = findViewById(R.id.deleteLogHistoryButton);
-        Button sendHistoryButton = findViewById(R.id.sendLogHistoryButton);
+
         sendHistoryButton.getBackground().setColorFilter(ThemeUtils.primaryColor(this), PorterDuff.Mode.SRC_ATOP);
         sendHistoryButton.getBackground().setColorFilter(ThemeUtils.primaryColor(this), PorterDuff.Mode.SRC_ATOP);
         deleteHistoryButton.setTextColor(ThemeUtils.primaryColor(this, true));
         deleteHistoryButton.setTextColor(ThemeUtils.primaryColor(this, true));
-        TextView logTV = findViewById(R.id.logTV);
-
-        deleteHistoryButton.setOnClickListener(new OnClickListener() {
-
-            @Override
-            public void onClick(View v) {
-
-                Log_OC.deleteHistoryLogging();
-                finish();
-            }
-        });
-
-        sendHistoryButton.setOnClickListener(new OnClickListener() {
-
-            @Override
-            public void onClick(View v) {
-                sendMail();
-            }
-        });
 
 
         if (savedInstanceState == null) {
         if (savedInstanceState == null) {
-            if (mLogPath != null) {
-                logDIR = new File(mLogPath);
+            if (logPath != null) {
+                logDir = new File(logPath);
             }
             }
 
 
-            if (logDIR != null && logDIR.isDirectory()) {
+            if (logDir != null && logDir.isDirectory()) {
                 // Show a dialog while log data is being loaded
                 // Show a dialog while log data is being loaded
                 showLoadingDialog();
                 showLoadingDialog();
 
 
@@ -117,8 +111,8 @@ public class LogHistoryActivity extends ToolbarActivity {
                 task.execute();
                 task.execute();
             }
             }
         } else {
         } else {
-            mLogText = savedInstanceState.getString(KEY_LOG_TEXT);
-            logTV.setText(mLogText);
+            logText = savedInstanceState.getString(KEY_LOG_TEXT);
+            logTV.setText(logText);
         }
         }
     }
     }
 
 
@@ -136,18 +130,24 @@ public class LogHistoryActivity extends ToolbarActivity {
         return retval;
         return retval;
     }
     }
 
 
+    @OnClick(R.id.deleteLogHistoryButton)
+    void deleteHistoryLogging() {
+        Log_OC.deleteHistoryLogging();
+        finish();
+    }
 
 
     /**
     /**
      * Start activity for sending email with logs attached
      * Start activity for sending email with logs attached
      */
      */
-    private void sendMail() {
+    @OnClick(R.id.sendLogHistoryButton)
+    void sendMail() {
         String emailAddress = getString(R.string.mail_logger);
         String emailAddress = getString(R.string.mail_logger);
 
 
         ArrayList<Uri> uris = new ArrayList<>();
         ArrayList<Uri> uris = new ArrayList<>();
 
 
         // Convert from paths to Android friendly Parcelable Uri's
         // Convert from paths to Android friendly Parcelable Uri's
         for (String file : Log_OC.getLogFileNames()) {
         for (String file : Log_OC.getLogFileNames()) {
-            File logFile = new File(mLogPath, file);
+            File logFile = new File(logPath, file);
             if (logFile.exists()) {
             if (logFile.exists()) {
                 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                     uris.add(Uri.fromFile(logFile));
                     uris.add(Uri.fromFile(logFile));
@@ -168,7 +168,7 @@ public class LogHistoryActivity extends ToolbarActivity {
         try {
         try {
             startActivity(intent);
             startActivity(intent);
         } catch (ActivityNotFoundException e) {
         } catch (ActivityNotFoundException e) {
-            Snackbar.make(findViewById(android.R.id.content),R.string.log_send_no_mail_app,Snackbar.LENGTH_LONG).show();
+            Snackbar.make(findViewById(android.R.id.content), R.string.log_send_no_mail_app, Snackbar.LENGTH_LONG).show();
             Log_OC.i(TAG, "Could not find app for sending log history.");
             Log_OC.i(TAG, "Could not find app for sending log history.");
         }
         }
 
 
@@ -182,7 +182,7 @@ public class LogHistoryActivity extends ToolbarActivity {
 
 
         LoadingLogTask(TextView logTV) {
         LoadingLogTask(TextView logTV) {
             // Use of a WeakReference to ensure the TextView can be garbage collected
             // Use of a WeakReference to ensure the TextView can be garbage collected
-            textViewReference  = new WeakReference<>(logTV);
+            textViewReference = new WeakReference<>(logTV);
         }
         }
 
 
         protected String doInBackground(String... args) {
         protected String doInBackground(String... args) {
@@ -193,8 +193,8 @@ public class LogHistoryActivity extends ToolbarActivity {
             if (result != null) {
             if (result != null) {
                 final TextView logTV = textViewReference.get();
                 final TextView logTV = textViewReference.get();
                 if (logTV != null) {
                 if (logTV != null) {
-                    mLogText = result;
-                    logTV.setText(mLogText);
+                    logText = result;
+                    logTV.setText(logText);
                     dismissLoadingDialog();
                     dismissLoadingDialog();
                 }
                 }
             }
             }
@@ -214,8 +214,8 @@ public class LogHistoryActivity extends ToolbarActivity {
             try {
             try {
                 String line;
                 String line;
 
 
-                for (int i = logFileName.length-1; i >= 0; i--) {
-                    File file = new File(mLogPath,logFileName[i]);
+                for (int i = logFileName.length - 1; i >= 0; i--) {
+                    File file = new File(logPath, logFileName[i]);
                     if (file.exists()) {
                     if (file.exists()) {
                         // Check if FileReader is ready
                         // Check if FileReader is ready
                         try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file),
                         try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file),
@@ -231,8 +231,7 @@ public class LogHistoryActivity extends ToolbarActivity {
                         }
                         }
                     }
                     }
                 }
                 }
-            }
-            catch (IOException e) {
+            } catch (IOException e) {
                 Log_OC.d(TAG, e.getMessage());
                 Log_OC.d(TAG, e.getMessage());
 
 
             } finally {
             } finally {
@@ -248,7 +247,7 @@ public class LogHistoryActivity extends ToolbarActivity {
 
 
             return text.toString();
             return text.toString();
         }
         }
-   }
+    }
 
 
     /**
     /**
      * Show loading dialog
      * Show loading dialog
@@ -264,7 +263,7 @@ public class LogHistoryActivity extends ToolbarActivity {
     /**
     /**
      * Dismiss loading dialog
      * Dismiss loading dialog
      */
      */
-    public void dismissLoadingDialog(){
+    public void dismissLoadingDialog() {
         Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
         Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
         if (frag != null) {
         if (frag != null) {
             LoadingDialog loading = (LoadingDialog) frag;
             LoadingDialog loading = (LoadingDialog) frag;
@@ -278,7 +277,13 @@ public class LogHistoryActivity extends ToolbarActivity {
 
 
         if (isChangingConfigurations()) {
         if (isChangingConfigurations()) {
             // global state
             // global state
-            outState.putString(KEY_LOG_TEXT, mLogText);
+            outState.putString(KEY_LOG_TEXT, logText);
         }
         }
     }
     }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        unbinder.unbind();
+    }
 }
 }

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

@@ -132,9 +132,7 @@ public class ManageSpaceActivity extends AppCompatActivity implements Injectable
                 ).show();
                 ).show();
             } else {
             } else {
                 finish();
                 finish();
-                System.exit(0);
             }
             }
-
         }
         }
 
 
         public boolean clearApplicationData() {
         public boolean clearApplicationData() {

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

@@ -114,6 +114,7 @@ import java.util.Calendar;
 import java.util.HashMap;
 import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.List;
+import java.util.Map;
 import java.util.Stack;
 import java.util.Stack;
 import java.util.Vector;
 import java.util.Vector;
 
 
@@ -767,9 +768,9 @@ public class ReceiveExternalFilesActivity extends FileActivity
 
 
                 files = sortFileList(files);
                 files = sortFileList(files);
 
 
-                List<HashMap<String, Object>> data = new LinkedList<>();
+                List<Map<String, Object>> data = new LinkedList<>();
                 for (OCFile f : files) {
                 for (OCFile f : files) {
-                    HashMap<String, Object> h = new HashMap<>();
+                    Map<String, Object> h = new HashMap<>();
                     h.put("dirname", f);
                     h.put("dirname", f);
                     data.add(h);
                     data.add(h);
                 }
                 }