소스 검색

Merge pull request #1357 from nextcloud/codacyFixes

Codacy: fix further issues
Mario Đanić 7 년 전
부모
커밋
f838dd7b43
19개의 변경된 파일721개의 추가작업 그리고 576개의 파일을 삭제
  1. 1 1
      src/main/java/com/owncloud/android/MainApp.java
  2. 3 54
      src/main/java/com/owncloud/android/authentication/AccountUtils.java
  3. 9 58
      src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java
  4. 130 0
      src/main/java/com/owncloud/android/authentication/AuthenticatorUrlUtils.java
  5. 4 4
      src/main/java/com/owncloud/android/files/services/IndexedForest.java
  6. 6 7
      src/main/java/com/owncloud/android/media/MediaService.java
  7. 11 9
      src/main/java/com/owncloud/android/operations/GetServerInfoOperation.java
  8. 3 2
      src/main/java/com/owncloud/android/operations/UpdateOCVersionOperation.java
  9. 0 2
      src/main/java/com/owncloud/android/providers/FileContentProvider.java
  10. 434 357
      src/main/java/com/owncloud/android/ui/activity/Preferences.java
  11. 1 1
      src/main/java/com/owncloud/android/ui/activity/SyncedFoldersActivity.java
  12. 2 3
      src/main/java/com/owncloud/android/ui/activity/UploadFilesActivity.java
  13. 2 2
      src/main/java/com/owncloud/android/ui/activity/UploadListActivity.java
  14. 14 14
      src/main/java/com/owncloud/android/ui/adapter/AccountListAdapter.java
  15. 19 49
      src/main/java/com/owncloud/android/ui/adapter/ExpandableUploadListAdapter.java
  16. 73 0
      src/main/java/com/owncloud/android/ui/adapter/ProgressListener.java
  17. 6 4
      src/main/java/com/owncloud/android/ui/dialog/ShareLinkToDialog.java
  18. 2 3
      src/main/java/com/owncloud/android/ui/fragment/SearchShareesFragment.java
  19. 1 6
      src/main/java/com/owncloud/android/ui/fragment/ShareFileFragment.java

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

@@ -123,7 +123,7 @@ public class MainApp extends MultiDexApplication {
 
 
         if (BuildConfig.DEBUG || getApplicationContext().getResources().getBoolean(R.bool.logger_enabled) ||
-                appPrefs.getBoolean(Preferences.EXPERT_MODE, false)) {
+                appPrefs.getBoolean(Preferences.PREFERENCE_EXPERT_MODE, false)) {
             // use app writable dir, no permissions needed
             Log_OC.startLogging(getAppContext());
             Log_OC.d("Debug", "start logging");

+ 3 - 54
src/main/java/com/owncloud/android/authentication/AccountUtils.java

@@ -1,4 +1,4 @@
-/**
+/*
  *   ownCloud Android client application
  *
  *   Copyright (C) 2012  Bartek Przybylski
@@ -30,7 +30,6 @@ import android.support.annotation.Nullable;
 import com.owncloud.android.MainApp;
 import com.owncloud.android.datamodel.ArbitraryDataProvider;
 import com.owncloud.android.datamodel.FileDataStorageManager;
-import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
 import com.owncloud.android.lib.common.utils.Log_OC;
@@ -41,15 +40,8 @@ import com.owncloud.android.ui.activity.ManageAccountsActivity;
 import java.util.Locale;
 
 public class AccountUtils {
-
     private static final String TAG = AccountUtils.class.getSimpleName();
 
-    public static final String WEBDAV_PATH_4_0_AND_LATER = "/remote.php/webdav";
-    public static final String DAV_PATH = "/remote.php/dav";
-    private static final String ODAV_PATH = "/remote.php/odav";
-    private static final String SAML_SSO_PATH = "/remote.php/webdav";
-    public static final String STATUS_PATH = "/status.php";
-
     public static final int ACCOUNT_VERSION = 1;
     public static final int ACCOUNT_VERSION_WITH_PROPER_ID = 2;
     public static final String ACCOUNT_USES_STANDARD_PASSWORD = "ACCOUNT_USES_STANDARD_PASSWORD";
@@ -63,8 +55,7 @@ public class AccountUtils {
      *                      {@link Account} available, if valid (still registered in the system as ownCloud 
      *                      account). If none is available and valid, returns null.
      */
-    public static @Nullable
-    Account getCurrentOwnCloudAccount(Context context) {
+    public static @Nullable Account getCurrentOwnCloudAccount(Context context) {
         Account[] ocAccounts = getAccounts(context);
         Account defaultAccount = null;
 
@@ -145,7 +136,7 @@ public class AccountUtils {
     
     /**
      * Returns owncloud account identified by accountName or null if it does not exist.
-     * @param context
+     * @param context the context
      * @param accountName name of account to be returned
      * @return owncloud account named accountName
      */
@@ -201,48 +192,6 @@ public class AccountUtils {
         appPrefs.apply();
     }
 
-    /**
-     * Returns the proper URL path to access the WebDAV interface of an ownCloud server,
-     * according to its version and the authorization method used.
-     * 
-     * @param   version         Version of ownCloud server.
-     * @param   authTokenType   Authorization token type, matching some of the AUTH_TOKEN_TYPE_* constants in
-     *                          {@link AccountAuthenticator}.
-     * @return                  WebDAV path for given OC version and authorization method, null if OC version
-     *                          is unknown; versions prior to ownCloud 4 are not supported anymore
-     */
-    public static String getWebdavPath(OwnCloudVersion version, String authTokenType) {
-        if (version != null) {
-            if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(authTokenType)) {
-                return ODAV_PATH;
-            }
-            if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(authTokenType)) {
-                return SAML_SSO_PATH;
-            }
-
-            return WEBDAV_PATH_4_0_AND_LATER;
-        }
-        return null;
-    }
-
-    
-    public static String trimWebdavSuffix(String url) {
-        while(url.endsWith("/")) {
-            url = url.substring(0, url.length() - 1);
-        }
-        int pos = url.lastIndexOf(WEBDAV_PATH_4_0_AND_LATER);
-        if (pos >= 0) {
-            url = url.substring(0, pos);
-
-        } else {
-            pos = url.lastIndexOf(ODAV_PATH);
-            if (pos >= 0) {
-                url = url.substring(0, pos);
-            }
-        }
-        return url;
-    }
-
     /**
      * Access the version of the OC server corresponding to an account SAVED IN THE ACCOUNTMANAGER
      *

+ 9 - 58
src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java

@@ -463,12 +463,11 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, dataString);
 
         if (loginUrlInfo != null) {
-            mServerInfo.mBaseUrl = normalizeUrlSuffix(loginUrlInfo.serverAddress);
+            mServerInfo.mBaseUrl = AuthenticatorUrlUtils.normalizeUrlSuffix(loginUrlInfo.serverAddress);
             webViewUser = loginUrlInfo.username;
             webViewPassword = loginUrlInfo.password;
             checkOcServer();
         }
-
     }
 
     private void populateLoginFields(String dataString) throws IllegalArgumentException {
@@ -690,7 +689,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
                 public void afterTextChanged(Editable s) {
                     if (mOkButton.isEnabled() &&
                             !mServerInfo.mBaseUrl.equals(
-                                    normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
+                                    AuthenticatorUrlUtils.normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
                         mOkButton.setEnabled(false);
                     }
                 }
@@ -1077,7 +1076,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      */
     private void onUrlInputFocusLost() {
         if (!mServerInfo.mBaseUrl.equals(
-                normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
+                AuthenticatorUrlUtils.normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
             // check server again only if the user changed something in the field
             checkOcServer();
         } else {
@@ -1103,7 +1102,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
         if (uri.length() != 0) {
             if (mHostUrlInput != null) {
-                uri = stripIndexPhpOrAppsFiles(uri, mHostUrlInput);
+                uri = AuthenticatorUrlUtils.stripIndexPhpOrAppsFiles(uri);
+                mHostUrlInput.setText(uri);
             }
 
             // Handle internationalized domain names
@@ -1121,7 +1121,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
             Intent getServerInfoIntent = new Intent();
             getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
-            getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL, normalizeUrlSuffix(uri));
+            getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL,
+                    AuthenticatorUrlUtils.normalizeUrlSuffix(uri));
 
             if (mOperationsServiceBinder != null) {
                 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
@@ -1309,7 +1310,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
         /// Show SAML-based SSO web dialog
         String targetUrl = mServerInfo.mBaseUrl
-                + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
+                + AuthenticatorUrlUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
         SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);
         dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
     }
@@ -1483,56 +1484,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         );
     }
 
-
-    // TODO remove, if possible
-    private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
-
-        if (url != null && url.length() > 0) {
-            url = url.trim();
-            if (!url.toLowerCase().startsWith(HTTP_PROTOCOL) &&
-                    !url.toLowerCase().startsWith(HTTP_PROTOCOL)) {
-                if (sslWhenUnprefixed) {
-                    url = HTTPS_PROTOCOL + url;
-                } else {
-                    url = HTTP_PROTOCOL + url;
-                }
-            }
-
-            url = normalizeUrlSuffix(url);
-        }
-        return (url != null ? url : "");
-    }
-
-
-    private String normalizeUrlSuffix(String url) {
-        if (url.endsWith("/")) {
-            url = url.substring(0, url.length() - 1);
-        }
-        url = trimUrlWebdav(url);
-        return url;
-    }
-
-    private String stripIndexPhpOrAppsFiles(String url, EditText mHostUrlInput) {
-        if (url.endsWith("/index.php")) {
-            url = url.substring(0, url.lastIndexOf("/index.php"));
-            mHostUrlInput.setText(url);
-        } else if (url.contains("/index.php/apps/")) {
-            url = url.substring(0, url.lastIndexOf("/index.php/apps/"));
-            mHostUrlInput.setText(url);
-        }
-
-        return url;
-    }
-
-    // TODO remove, if possible
-    private String trimUrlWebdav(String url) {
-        if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)) {
-            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());
-        }
-        return url;
-    }
-
-
     /**
      * Chooses the right icon and text to show to the user for the received operation result.
      *
@@ -1880,7 +1831,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
         String lastPermanentLocation = authResult.getLastPermanentLocation();
         if (lastPermanentLocation != null) {
-            mServerInfo.mBaseUrl = AccountUtils.trimWebdavSuffix(lastPermanentLocation);
+            mServerInfo.mBaseUrl = AuthenticatorUrlUtils.trimWebdavSuffix(lastPermanentLocation);
         }
 
         Uri uri = Uri.parse(mServerInfo.mBaseUrl);

+ 130 - 0
src/main/java/com/owncloud/android/authentication/AuthenticatorUrlUtils.java

@@ -0,0 +1,130 @@
+/*
+ * Nextcloud Android client application
+ *
+ * @author Andy Scherzinger
+ * Copyright (C) 2017 Andy Scherzinger
+ * Copyright (C) 2012 Bartek Przybylski
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package com.owncloud.android.authentication;
+
+import com.owncloud.android.MainApp;
+import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
+import com.owncloud.android.lib.resources.status.OwnCloudVersion;
+
+/**
+ * Helper class for authenticator-URL related logic.
+ */
+public abstract class AuthenticatorUrlUtils {
+    public static final String WEBDAV_PATH_4_0_AND_LATER = "/remote.php/webdav";
+
+    private static final String HTTPS_PROTOCOL = "https://";
+    private static final String HTTP_PROTOCOL = "http://";
+
+    private static final String ODAV_PATH = "/remote.php/odav";
+    private static final String SAML_SSO_PATH = "/remote.php/webdav";
+
+    /**
+     * Returns the proper URL path to access the WebDAV interface of an ownCloud server,
+     * according to its version and the authorization method used.
+     *
+     * @param   version         Version of ownCloud server.
+     * @param   authTokenType   Authorization token type, matching some of the AUTH_TOKEN_TYPE_* constants in
+     *                          {@link AccountAuthenticator}.
+     * @return                  WebDAV path for given OC version and authorization method, null if OC version
+     *                          is unknown; versions prior to ownCloud 4 are not supported anymore
+     */
+    public static String getWebdavPath(OwnCloudVersion version, String authTokenType) {
+        if (version != null) {
+            if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(authTokenType)) {
+                return ODAV_PATH;
+            }
+            if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(authTokenType)) {
+                return SAML_SSO_PATH;
+            }
+
+            return WEBDAV_PATH_4_0_AND_LATER;
+        }
+        return null;
+    }
+
+    public static String normalizeUrlSuffix(String url) {
+        String normalizedUrl = url;
+        if (normalizedUrl.endsWith("/")) {
+            normalizedUrl = normalizedUrl.substring(0, normalizedUrl.length() - 1);
+        }
+        return trimUrlWebdav(normalizedUrl);
+    }
+
+    public static String normalizeUrl(String url, boolean sslWhenUnprefixed) {
+        String normalizedUrl = url;
+
+        if (normalizedUrl != null && normalizedUrl.length() > 0) {
+            normalizedUrl = normalizedUrl.trim();
+
+            if (!normalizedUrl.toLowerCase().startsWith(HTTP_PROTOCOL) &&
+                    !normalizedUrl.toLowerCase().startsWith(HTTP_PROTOCOL)) {
+                if (sslWhenUnprefixed) {
+                    normalizedUrl = HTTPS_PROTOCOL + normalizedUrl;
+                } else {
+                    normalizedUrl = HTTP_PROTOCOL + normalizedUrl;
+                }
+            }
+
+            normalizedUrl = normalizeUrlSuffix(normalizedUrl);
+        }
+        return (normalizedUrl != null ? normalizedUrl : "");
+    }
+
+    public static String trimWebdavSuffix(String url) {
+        String trimmedUrl = url;
+        while(trimmedUrl.endsWith("/")) {
+            trimmedUrl = trimmedUrl.substring(0, url.length() - 1);
+        }
+
+        int pos = trimmedUrl.lastIndexOf(WEBDAV_PATH_4_0_AND_LATER);
+        if (pos >= 0) {
+            trimmedUrl = trimmedUrl.substring(0, pos);
+
+        } else {
+            pos = trimmedUrl.lastIndexOf(ODAV_PATH);
+            if (pos >= 0) {
+                trimmedUrl = trimmedUrl.substring(0, pos);
+            }
+        }
+
+        return trimmedUrl;
+    }
+
+    private static String trimUrlWebdav(String url) {
+        if (url.toLowerCase().endsWith(WEBDAV_PATH_4_0_AND_LATER)) {
+            return url.substring(0, url.length() - WEBDAV_PATH_4_0_AND_LATER.length());
+        }
+
+        return url;
+    }
+
+    public static String stripIndexPhpOrAppsFiles(String url) {
+        String strippedUrl = url;
+        if (strippedUrl.endsWith("/index.php")) {
+            strippedUrl = strippedUrl.substring(0, strippedUrl.lastIndexOf("/index.php"));
+        } else if (strippedUrl.contains("/index.php/apps/")) {
+            strippedUrl = strippedUrl.substring(0, strippedUrl.lastIndexOf("/index.php/apps/"));
+        }
+
+        return strippedUrl;
+    }
+}

+ 4 - 4
src/main/java/com/owncloud/android/files/services/IndexedForest.java

@@ -45,10 +45,10 @@ public class IndexedForest<V> {
 
     @SuppressWarnings("PMD.ShortClassName")
     private class Node<V> {
-        String mKey = null;
-        Node<V> mParent = null;
-        Set<Node<V>> mChildren = new HashSet<>();    // TODO be careful with hash()
-        V mPayload = null;
+        private String mKey = null;
+        private Node<V> mParent = null;
+        private Set<Node<V>> mChildren = new HashSet<>();    // TODO be careful with hash()
+        private V mPayload = null;
 
         // payload is optional
         public Node(String key, V payload) {

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

@@ -112,10 +112,6 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
     /** Current focus state */
     private AudioFocus mAudioFocus = AudioFocus.NO_FOCUS;
 
-
-    /** 'True' when the current song is streaming from the network */
-    private boolean mIsStreaming = false;
-
     /** Wifi lock kept to prevents the device from shutting off the radio when streaming a file. */
     private WifiLock mWifiLock;
 
@@ -447,14 +443,14 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
             createMediaPlayerIfNeeded();
             mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
             String url = mFile.getStoragePath();
+
             /* Streaming is not possible right now
             if (url == null || url.length() <= 0) {
                 url = AccountUtils.constructFullURLForAccount(this, mAccount) + mFile.getRemotePath();
             }
             mIsStreaming = url.startsWith("http:") || url.startsWith("https:");
             */
-            mIsStreaming = false;
-
+            //mIsStreaming = false;
             mPlayer.setDataSource(url);
 
             mState = State.PREPARING;
@@ -464,9 +460,12 @@ public class MediaService extends Service implements OnCompletionListener, OnPre
             mPlayer.prepareAsync();
 
             // prevent the Wifi from going to sleep when streaming
+            /*
             if (mIsStreaming) {
                 mWifiLock.acquire();
-            } else if (mWifiLock.isHeld()) {
+            } else
+            */
+            if (mWifiLock.isHeld()) {
                 mWifiLock.release();
             }
 

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

@@ -23,7 +23,7 @@ package com.owncloud.android.operations;
 
 import android.content.Context;
 
-import com.owncloud.android.authentication.AccountUtils;
+import com.owncloud.android.authentication.AuthenticatorUrlUtils;
 import com.owncloud.android.lib.common.OwnCloudClient;
 import com.owncloud.android.lib.common.operations.RemoteOperation;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
@@ -109,20 +109,22 @@ public class GetServerInfoOperation extends RemoteOperation {
                 new DetectAuthenticationMethodOperation(mContext);
         return operation.execute(client);
     }
-    
+
 
     private String trimWebdavSuffix(String url) {
-        if (url == null) {
-            url = "";
+	    String trimmedUrl = url;
+        if (trimmedUrl == null) {
+            trimmedUrl = "";
         } else {
-            if (url.endsWith("/")) {
-                url = url.substring(0, url.length() - 1);
+            if (trimmedUrl.endsWith("/")) {
+                trimmedUrl = trimmedUrl.substring(0, trimmedUrl.length() - 1);
             }
-            if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)){
-                url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());
+            if (trimmedUrl.toLowerCase().endsWith(AuthenticatorUrlUtils.WEBDAV_PATH_4_0_AND_LATER)) {
+                trimmedUrl = trimmedUrl.substring(0,
+                        trimmedUrl.length() - AuthenticatorUrlUtils.WEBDAV_PATH_4_0_AND_LATER.length());
             }
         }
-        return url;
+        return trimmedUrl;
     }
 
     

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

@@ -24,7 +24,6 @@ import android.accounts.Account;
 import android.accounts.AccountManager;
 import android.content.Context;
 
-import com.owncloud.android.authentication.AccountUtils;
 import com.owncloud.android.lib.common.OwnCloudClient;
 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
 import com.owncloud.android.lib.common.operations.RemoteOperation;
@@ -46,6 +45,8 @@ public class UpdateOCVersionOperation extends RemoteOperation {
 
     private static final String TAG = UpdateOCVersionOperation.class.getSimpleName();
 
+    private static final String STATUS_PATH = "/status.php";
+
     private Account mAccount;
     private Context mContext;
     private OwnCloudVersion mOwnCloudVersion;
@@ -62,7 +63,7 @@ public class UpdateOCVersionOperation extends RemoteOperation {
     protected RemoteOperationResult run(OwnCloudClient client) {
         AccountManager accountMngr = AccountManager.get(mContext); 
         String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
-        statUrl += AccountUtils.STATUS_PATH;
+        statUrl += STATUS_PATH;
         RemoteOperationResult result = null;
         GetMethod getMethod = null;
 

+ 0 - 2
src/main/java/com/owncloud/android/providers/FileContentProvider.java

@@ -1348,8 +1348,6 @@ public class FileContentProvider extends ContentProvider {
      * structure to include in it the path to the server instance. Updating the account names and path to local files
      * in the files table is a must to keep the existing account working and the database clean.
      *
-     * See {@link com.owncloud.android.authentication.AccountUtils#updateAccountVersion(android.content.Context)}
-     *
      * @param db Database where table of files is included.
      */
     private void updateAccountName(SQLiteDatabase db) {

+ 434 - 357
src/main/java/com/owncloud/android/ui/activity/Preferences.java

@@ -1,4 +1,4 @@
-/**
+/*
  *   ownCloud Android client application
  *
  *   @author Bartek Przybylski
@@ -86,8 +86,7 @@ public class Preferences extends PreferenceActivity
     private static final String TAG = Preferences.class.getSimpleName();
 
     public final static String PREFERENCE_USE_FINGERPRINT = "use_fingerprint";
-
-    public static final String EXPERT_MODE = "expert_mode";
+    public static final String PREFERENCE_EXPERT_MODE = "expert_mode";
 
     private static final String SCREEN_NAME = "Settings";
 
@@ -96,6 +95,8 @@ public class Preferences extends PreferenceActivity
 
     private static final int ACTION_REQUEST_CODE_DAVDROID_SETUP = 10;
 
+    private static final String DAV_PATH = "/remote.php/dav";
+
     public static final String SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI = "SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI";
 
     /**
@@ -132,296 +133,214 @@ public class Preferences extends PreferenceActivity
         super.onCreate(savedInstanceState);
         addPreferencesFromResource(R.xml.preferences);
 
-        ActionBar actionBar = getDelegate().getSupportActionBar();
-        actionBar.setDisplayHomeAsUpEnabled(true);
-        ThemeUtils.setColoredTitle(actionBar, getString(R.string.actionbar_settings));
-        actionBar.setBackgroundDrawable(new ColorDrawable(ThemeUtils.primaryColor()));
-        getWindow().getDecorView().setBackgroundDrawable(new ColorDrawable(ResourcesCompat
-                .getColor(getResources(), R.color.background_color, null)));
-
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
-            getWindow().setStatusBarColor(ThemeUtils.primaryDarkColor());
-        }
-
-        Drawable backArrow = getResources().getDrawable(R.drawable.ic_arrow_back);
-        actionBar.setHomeAsUpIndicator(ThemeUtils.tintDrawable(backArrow, ThemeUtils.fontColor()));
-
-        int accentColor = ThemeUtils.primaryAccentColor();
-
         // retrieve user's base uri
         setupBaseUri();
 
-        // For adding content description tag to a title field in the action bar
-        int actionBarTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
-        View actionBarTitleView = getWindow().getDecorView().findViewById(actionBarTitleId);
-        if (actionBarTitleView != null) {    // it's null in Android 2.x
-            getWindow().getDecorView().findViewById(actionBarTitleId).
-                    setContentDescription(getString(R.string.actionbar_settings));
-        }
-        // Load package info
-        String temp;
-        try {
-            PackageInfo pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
-            temp = pkg.versionName;
-        } catch (NameNotFoundException e) {
-            temp = "";
-            Log_OC.e(TAG, "Error while showing about dialog", e);
-        }
-        final String appVersion = temp;
+        setupActionBar();
 
         // Register context menu for list of preferences.
         registerForContextMenu(getListView());
 
-        // General
-        PreferenceCategory preferenceCategoryGeneral = (PreferenceCategory) findPreference("general");
-        preferenceCategoryGeneral.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_general),
-                accentColor));
-
-        // Synced folders
-        PreferenceCategory preferenceCategorySyncedFolders =
-                (PreferenceCategory) findPreference("synced_folders_category");
-        preferenceCategorySyncedFolders.setTitle(ThemeUtils.getColoredTitle(getString(R.string.drawer_synced_folders),
-                accentColor));
+        int accentColor = ThemeUtils.primaryAccentColor();
+        String appVersion = getAppVersion();
         PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("preference_screen");
 
-        if (!getResources().getBoolean(R.bool.syncedFolder_light)) {
-            preferenceScreen.removePreference(preferenceCategorySyncedFolders);
-        } else {
-            // Upload on WiFi
-            final ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
-            final Account account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
+        // General
+        setupGeneralCategory(accentColor);
 
-            final SwitchPreference pUploadOnWifiCheckbox = (SwitchPreference) findPreference("synced_folder_on_wifi");
-            pUploadOnWifiCheckbox.setChecked(
-                    arbitraryDataProvider.getBooleanValue(account, SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI));
+        // Synced folders
+        setupAutoUploadCategory(accentColor, preferenceScreen);
 
-            pUploadOnWifiCheckbox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
-                @Override
-                public boolean onPreferenceClick(Preference preference) {
-                    arbitraryDataProvider.storeOrUpdateKeyValue(account.name, SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI,
-                            String.valueOf(pUploadOnWifiCheckbox.isChecked()));
+        // Details
+        setupDetailsCategory(accentColor, preferenceScreen);
 
-                    return true;
-                }
-            });
+        // More
+        setupMoreCategory(accentColor, appVersion);
 
-            Preference pSyncedFolder = findPreference("synced_folders_configure_folders");
-            if (pSyncedFolder != null) {
-                if (getResources().getBoolean(R.bool.syncedFolder_light)
-                        && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
-                    pSyncedFolder.setOnPreferenceClickListener(new OnPreferenceClickListener() {
-                        @Override
-                        public boolean onPreferenceClick(Preference preference) {
-                            Intent syncedFoldersIntent = new Intent(getApplicationContext(), SyncedFoldersActivity.class);
-                            syncedFoldersIntent.putExtra(SyncedFoldersActivity.EXTRA_SHOW_SIDEBAR, false);
-                            startActivity(syncedFoldersIntent);
-                            return true;
-                        }
-                    });
-                } else {
-                    preferenceCategorySyncedFolders.removePreference(pSyncedFolder);
-                }
-            }
-        }
+        // About
+        setupAboutCategory(accentColor, appVersion);
+    }
 
-        PreferenceCategory preferenceCategoryDetails = (PreferenceCategory) findPreference("details");
-        preferenceCategoryDetails.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_details),
+    private void setupAboutCategory(int accentColor, String appVersion) {
+        PreferenceCategory preferenceCategoryAbout = (PreferenceCategory) findPreference("about");
+        preferenceCategoryAbout.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_about),
                 accentColor));
 
-        boolean fPassCodeEnabled = getResources().getBoolean(R.bool.passcode_enabled);
-        pCode = (SwitchPreference) findPreference(PassCodeActivity.PREFERENCE_SET_PASSCODE);
-        if (pCode != null && fPassCodeEnabled) {
-            pCode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
-                @Override
-                public boolean onPreferenceChange(Preference preference, Object newValue) {
-                    Intent i = new Intent(getApplicationContext(), PassCodeActivity.class);
-                    Boolean incoming = (Boolean) newValue;
-
-                    i.setAction(
-                            incoming ? PassCodeActivity.ACTION_REQUEST_WITH_RESULT :
-                                    PassCodeActivity.ACTION_CHECK_WITH_RESULT
-                    );
-
-                    startActivityForResult(i, incoming ? ACTION_REQUEST_PASSCODE :
-                            ACTION_CONFIRM_PASSCODE);
-
-                    // Don't update just yet, we will decide on it in onActivityResult
-                    return false;
-                }
-            });
-        } else {
-            preferenceCategoryDetails.removePreference(pCode);
+        /* About App */
+        pAboutApp = findPreference("about_app");
+        if (pAboutApp != null) {
+            pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
+            pAboutApp.setSummary(String.format(getString(R.string.about_version), appVersion));
         }
 
-        boolean fPrintEnabled = getResources().getBoolean(R.bool.fingerprint_enabled);
-        fPrint = (SwitchPreference) findPreference(PREFERENCE_USE_FINGERPRINT);
-        if (fPrint != null) {
-            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
-                if (FingerprintActivity.isFingerprintCapable(MainApp.getAppContext()) && fPrintEnabled) {
-                    final Activity activity = this;
-                    fPrint.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
-                        @Override
-                        public boolean onPreferenceChange(Preference preference, Object newValue) {
-                            Boolean incoming = (Boolean) newValue;
+        // license
+        boolean licenseEnabled = getResources().getBoolean(R.bool.license_enabled);
+        Preference licensePreference = findPreference("license");
+        if (licensePreference != null) {
+            String licenseUrl = getString(R.string.license_url);
 
-                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
-                                if (FingerprintActivity.isFingerprintReady(MainApp.getAppContext())) {
-                                    SharedPreferences appPrefs =
-                                            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
-                                    SharedPreferences.Editor editor = appPrefs.edit();
-                                    editor.putBoolean("use_fingerprint", incoming);
-                                    editor.apply();
-                                    return true;
-                                } else {
-                                    if (incoming) {
-                                        DisplayUtils.showSnackMessage(activity, R.string.prefs_fingerprint_notsetup);
-                                        fPrint.setChecked(false);
-                                    }
-                                    SharedPreferences appPrefs =
-                                            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
-                                    SharedPreferences.Editor editor = appPrefs.edit();
-                                    editor.putBoolean("use_fingerprint", false);
-                                    editor.apply();
-                                    return false;
-                                }
-                            } else {
-                                return false;
-                            }
-                        }
-                    });
-                    if (!FingerprintActivity.isFingerprintReady(MainApp.getAppContext())) {
-                        fPrint.setChecked(false);
+            if (licenseEnabled && !licenseUrl.isEmpty()) {
+                licensePreference.setSummary(R.string.prefs_gpl_v2);
+                licensePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+                    @Override
+                    public boolean onPreferenceClick(Preference preference) {
+                        Uri uriUrl = Uri.parse(licenseUrl);
+                        Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
+                        startActivity(intent);
+                        return true;
                     }
-
-                } else {
-                    preferenceCategoryDetails.removePreference(fPrint);
-                }
+                });
             } else {
-                preferenceCategoryDetails.removePreference(fPrint);
+                preferenceCategoryAbout.removePreference(licensePreference);
             }
         }
 
-        boolean fShowHiddenFilesEnabled = getResources().getBoolean(R.bool.show_hidden_files_enabled);
-        mShowHiddenFiles = (SwitchPreference) findPreference("show_hidden_files");
-
-        if (fShowHiddenFilesEnabled) {
-            mShowHiddenFiles.setOnPreferenceClickListener(new OnPreferenceClickListener() {
-                @Override
-                public boolean onPreferenceClick(Preference preference) {
-                    SharedPreferences appPrefs =
-                            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
-                    SharedPreferences.Editor editor = appPrefs.edit();
-                    editor.putBoolean("show_hidden_files_pref", mShowHiddenFiles.isChecked());
-                    editor.apply();
-                    return true;
-                }
-            });
-        } else {
-            preferenceCategoryDetails.removePreference(mShowHiddenFiles);
-        }
-
-        mExpertMode = (SwitchPreference) findPreference(EXPERT_MODE);
-
-        if (getResources().getBoolean(R.bool.syncedFolder_light)) {
-            preferenceCategoryDetails.removePreference(mExpertMode);
-        } else {
-            mExpertMode = (SwitchPreference) findPreference(EXPERT_MODE);
-            mExpertMode.setOnPreferenceClickListener(new OnPreferenceClickListener() {
-                @Override
-                public boolean onPreferenceClick(Preference preference) {
-                    SharedPreferences appPrefs =
-                            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
-                    SharedPreferences.Editor editor = appPrefs.edit();
-                    editor.putBoolean(EXPERT_MODE, mExpertMode.isChecked());
-                    editor.apply();
-
-                    if (mExpertMode.isChecked()) {
-                        Log_OC.startLogging(getApplicationContext());
-                    } else {
-                        if (!BuildConfig.DEBUG &&
-                                !getApplicationContext().getResources().getBoolean(R.bool.logger_enabled)) {
-                            Log_OC.stopLogging();
-                        }
-                    }
-
-                    return true;
-                }
-            });
-        }
-
-        PreferenceCategory preferenceCategoryMore = (PreferenceCategory) findPreference("more");
-        preferenceCategoryMore.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_more),
-                accentColor));
-
-        boolean calendarContactsEnabled = getResources().getBoolean(R.bool.davdroid_integration_enabled);
-        Preference pCalendarContacts = findPreference("calendar_contacts");
-        if (pCalendarContacts != null) {
-            if (calendarContactsEnabled) {
-                final Activity activity = this;
-                pCalendarContacts.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+        // privacy
+        boolean privacyEnabled = getResources().getBoolean(R.bool.privacy_enabled);
+        Preference privacyPreference = findPreference("privacy");
+        if (privacyPreference != null) {
+            if (privacyEnabled) {
+                privacyPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                     @Override
                     public boolean onPreferenceClick(Preference preference) {
-                        try {
-                            launchDavDroidLogin();
-                        } catch (Throwable t) {
-                            Log_OC.e(TAG, "Base Uri for account could not be resolved to call DAVdroid!", t);
-                            DisplayUtils.showSnackMessage(
-                                    activity,
-                                    R.string.prefs_calendar_contacts_address_resolve_error
-                            );
+                        String privacyUrl = getString(R.string.privacy_url);
+                        if (privacyUrl.length() > 0) {
+                            Intent externalWebViewIntent =
+                                    new Intent(getApplicationContext(),ExternalSiteWebView.class);
+                            externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE,
+                                    getResources().getString(R.string.privacy));
+                            externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, privacyUrl);
+                            externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, false);
+                            externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, -1);
+                            startActivity(externalWebViewIntent);
                         }
                         return true;
                     }
                 });
             } else {
-                preferenceCategoryMore.removePreference(pCalendarContacts);
+                preferenceCategoryAbout.removePreference(privacyPreference);
             }
         }
 
-        boolean contactsBackupEnabled = !getResources().getBoolean(R.bool.show_drawer_contacts_backup)
-                && getResources().getBoolean(R.bool.contacts_backup);
-        Preference pContactsBackup = findPreference("contacts");
-        if (pCalendarContacts != null) {
-            if (contactsBackupEnabled) {
-                pContactsBackup.setOnPreferenceClickListener(new OnPreferenceClickListener() {
-                    @Override
+        // source code
+        boolean sourcecodeEnabled = getResources().getBoolean(R.bool.sourcecode_enabled);
+        Preference sourcecodePreference = findPreference("sourcecode");
+        if (sourcecodePreference != null) {
+            String sourcecodeUrl = getString(R.string.sourcecode_url);
+            if (sourcecodeEnabled && !sourcecodeUrl.isEmpty()) {
+                sourcecodePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+                    @Override
                     public boolean onPreferenceClick(Preference preference) {
-                        Intent contactsIntent = new Intent(getApplicationContext(), ContactsPreferenceActivity.class);
-                        contactsIntent.putExtra(ContactsPreferenceActivity.EXTRA_SHOW_SIDEBAR, false);
-                        startActivity(contactsIntent);
+                        Uri uriUrl = Uri.parse(sourcecodeUrl);
+                        Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
+                        startActivity(intent);
                         return true;
                     }
                 });
             } else {
-                preferenceCategoryMore.removePreference(pContactsBackup);
+                preferenceCategoryAbout.removePreference(sourcecodePreference);
             }
         }
+    }
 
-        if (!fShowHiddenFilesEnabled && !fPrintEnabled && !fPassCodeEnabled) {
-            preferenceScreen.removePreference(preferenceCategoryDetails);
-        }
+    private void setupMoreCategory(int accentColor, String appVersion) {
+        PreferenceCategory preferenceCategoryMore = (PreferenceCategory) findPreference("more");
+        preferenceCategoryMore.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_more),
+                accentColor));
 
-        boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
-        Preference pHelp = findPreference("help");
-        if (pHelp != null) {
-            if (helpEnabled) {
-                pHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+        setupCalendarPreference(preferenceCategoryMore);
+
+        setupContactsBackupPreference(preferenceCategoryMore);
+
+        setupHelpPreference(preferenceCategoryMore);
+
+        setupRecommendPreference(preferenceCategoryMore);
+
+        setupFeedbackPreference(appVersion, preferenceCategoryMore);
+
+        setupLoggingPreference(preferenceCategoryMore);
+
+        setupImprintPreference(preferenceCategoryMore);
+
+        loadExternalSettingLinks(preferenceCategoryMore);
+    }
+
+    private void setupImprintPreference(PreferenceCategory preferenceCategoryMore) {
+        boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
+        Preference pImprint = findPreference("imprint");
+        if (pImprint != null) {
+            if (imprintEnabled) {
+                pImprint.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                     @Override
                     public boolean onPreferenceClick(Preference preference) {
-                        String helpWeb = getString(R.string.url_help);
-                        if (helpWeb != null && helpWeb.length() > 0) {
-                            Uri uriUrl = Uri.parse(helpWeb);
+                        String imprintWeb = getString(R.string.url_imprint);
+                        if (imprintWeb != null && imprintWeb.length() > 0) {
+                            Uri uriUrl = Uri.parse(imprintWeb);
                             Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
                             startActivity(intent);
                         }
+                        //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
                         return true;
                     }
                 });
             } else {
-                preferenceCategoryMore.removePreference(pHelp);
+                preferenceCategoryMore.removePreference(pImprint);
+            }
+        }
+    }
+
+    private void setupLoggingPreference(PreferenceCategory preferenceCategoryMore) {
+        SharedPreferences appPrefs =
+                PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
+
+        boolean loggerEnabled = getResources().getBoolean(R.bool.logger_enabled) || BuildConfig.DEBUG ||
+                appPrefs.getBoolean(PREFERENCE_EXPERT_MODE, false);
+        Preference pLogger = findPreference("logger");
+        if (pLogger != null) {
+            if (loggerEnabled) {
+                pLogger.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+                    @Override
+                    public boolean onPreferenceClick(Preference preference) {
+                        Intent loggerIntent = new Intent(getApplicationContext(), LogHistoryActivity.class);
+                        startActivity(loggerIntent);
+
+                        return true;
+                    }
+                });
+            } else {
+                preferenceCategoryMore.removePreference(pLogger);
+            }
+        }
+    }
+
+    private void setupFeedbackPreference(String appVersion, PreferenceCategory preferenceCategoryMore) {
+        boolean feedbackEnabled = getResources().getBoolean(R.bool.feedback_enabled);
+        Preference pFeedback = findPreference("feedback");
+        if (pFeedback != null) {
+            if (feedbackEnabled) {
+                pFeedback.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+                    @Override
+                    public boolean onPreferenceClick(Preference preference) {
+                        String feedbackMail = getString(R.string.mail_feedback);
+                        String feedback = getText(R.string.prefs_feedback) + " - android v" + appVersion;
+                        Intent intent = new Intent(Intent.ACTION_SENDTO);
+                        intent.setType("text/plain");
+                        intent.putExtra(Intent.EXTRA_SUBJECT, feedback);
+
+                        intent.setData(Uri.parse(feedbackMail));
+                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                        startActivity(intent);
+
+                        return true;
+                    }
+                });
+            } else {
+                preferenceCategoryMore.removePreference(pFeedback);
             }
         }
+    }
 
+    private void setupRecommendPreference(PreferenceCategory preferenceCategoryMore) {
         boolean recommendEnabled = getResources().getBoolean(R.bool.recommend_enabled);
         Preference pRecommend = findPreference("recommend");
         if (pRecommend != null) {
@@ -456,75 +375,279 @@ public class Preferences extends PreferenceActivity
                 preferenceCategoryMore.removePreference(pRecommend);
             }
         }
+    }
 
-        boolean feedbackEnabled = getResources().getBoolean(R.bool.feedback_enabled);
-        Preference pFeedback = findPreference("feedback");
-        if (pFeedback != null) {
-            if (feedbackEnabled) {
-                pFeedback.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+    private void setupHelpPreference(PreferenceCategory preferenceCategoryMore) {
+        boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
+        Preference pHelp = findPreference("help");
+        if (pHelp != null) {
+            if (helpEnabled) {
+                pHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                     @Override
                     public boolean onPreferenceClick(Preference preference) {
-                        String feedbackMail = getString(R.string.mail_feedback);
-                        String feedback = getText(R.string.prefs_feedback) + " - android v" + appVersion;
-                        Intent intent = new Intent(Intent.ACTION_SENDTO);
-                        intent.setType("text/plain");
-                        intent.putExtra(Intent.EXTRA_SUBJECT, feedback);
-
-                        intent.setData(Uri.parse(feedbackMail));
-                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-                        startActivity(intent);
-
+                        String helpWeb = getString(R.string.url_help);
+                        if (helpWeb != null && helpWeb.length() > 0) {
+                            Uri uriUrl = Uri.parse(helpWeb);
+                            Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
+                            startActivity(intent);
+                        }
                         return true;
                     }
                 });
             } else {
-                preferenceCategoryMore.removePreference(pFeedback);
+                preferenceCategoryMore.removePreference(pHelp);
             }
         }
+    }
 
-        SharedPreferences appPrefs =
-                PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
-
-        boolean loggerEnabled = getResources().getBoolean(R.bool.logger_enabled) || BuildConfig.DEBUG ||
-                appPrefs.getBoolean(EXPERT_MODE, false);
-        Preference pLogger = findPreference("logger");
-        if (pLogger != null) {
-            if (loggerEnabled) {
-                pLogger.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+    private void setupContactsBackupPreference(PreferenceCategory preferenceCategoryMore) {
+        boolean contactsBackupEnabled = !getResources().getBoolean(R.bool.show_drawer_contacts_backup)
+                && getResources().getBoolean(R.bool.contacts_backup);
+        Preference pContactsBackup = findPreference("contacts");
+        if (pContactsBackup != null) {
+            if (contactsBackupEnabled) {
+                pContactsBackup.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                     @Override
                     public boolean onPreferenceClick(Preference preference) {
-                        Intent loggerIntent = new Intent(getApplicationContext(), LogHistoryActivity.class);
-                        startActivity(loggerIntent);
-
+                        Intent contactsIntent = new Intent(getApplicationContext(), ContactsPreferenceActivity.class);
+                        contactsIntent.putExtra(ContactsPreferenceActivity.EXTRA_SHOW_SIDEBAR, false);
+                        startActivity(contactsIntent);
                         return true;
                     }
                 });
             } else {
-                preferenceCategoryMore.removePreference(pLogger);
+                preferenceCategoryMore.removePreference(pContactsBackup);
             }
         }
+    }
 
-        boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
-        Preference pImprint = findPreference("imprint");
-        if (pImprint != null) {
-            if (imprintEnabled) {
-                pImprint.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+    private void setupCalendarPreference(PreferenceCategory preferenceCategoryMore) {
+        boolean calendarContactsEnabled = getResources().getBoolean(R.bool.davdroid_integration_enabled);
+        Preference pCalendarContacts = findPreference("calendar_contacts");
+        if (pCalendarContacts != null) {
+            if (calendarContactsEnabled) {
+                final Activity activity = this;
+                pCalendarContacts.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                     @Override
                     public boolean onPreferenceClick(Preference preference) {
-                        String imprintWeb = getString(R.string.url_imprint);
-                        if (imprintWeb != null && imprintWeb.length() > 0) {
-                            Uri uriUrl = Uri.parse(imprintWeb);
-                            Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
-                            startActivity(intent);
+                        try {
+                            launchDavDroidLogin();
+                        } catch (Throwable t) {
+                            Log_OC.e(TAG, "Base Uri for account could not be resolved to call DAVdroid!", t);
+                            DisplayUtils.showSnackMessage(
+                                    activity,
+                                    R.string.prefs_calendar_contacts_address_resolve_error
+                            );
                         }
-                        //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
                         return true;
                     }
                 });
             } else {
-                preferenceCategoryMore.removePreference(pImprint);
+                preferenceCategoryMore.removePreference(pCalendarContacts);
             }
         }
+    }
+
+    private void setupDetailsCategory(int accentColor, PreferenceScreen preferenceScreen) {
+        PreferenceCategory preferenceCategoryDetails = (PreferenceCategory) findPreference("details");
+        preferenceCategoryDetails.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_details),
+                accentColor));
+
+        boolean fPassCodeEnabled = getResources().getBoolean(R.bool.passcode_enabled);
+        boolean fPrintEnabled = getResources().getBoolean(R.bool.fingerprint_enabled);
+        boolean fShowHiddenFilesEnabled = getResources().getBoolean(R.bool.show_hidden_files_enabled);
+
+        setupPasscodePreference(preferenceCategoryDetails, fPassCodeEnabled);
+
+        setupFingerprintPreference(preferenceCategoryDetails, fPrintEnabled);
+
+        setupHiddenFilesPreference(preferenceCategoryDetails, fShowHiddenFilesEnabled);
+
+        setupExpertModePreference(preferenceCategoryDetails);
+
+        if (!fShowHiddenFilesEnabled && !fPrintEnabled && !fPassCodeEnabled) {
+            preferenceScreen.removePreference(preferenceCategoryDetails);
+        }
+    }
+
+    private void setupExpertModePreference(PreferenceCategory preferenceCategoryDetails) {
+        mExpertMode = (SwitchPreference) findPreference(PREFERENCE_EXPERT_MODE);
+
+        if (getResources().getBoolean(R.bool.syncedFolder_light)) {
+            preferenceCategoryDetails.removePreference(mExpertMode);
+        } else {
+            mExpertMode = (SwitchPreference) findPreference(PREFERENCE_EXPERT_MODE);
+            mExpertMode.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+                @Override
+                public boolean onPreferenceClick(Preference preference) {
+                    SharedPreferences appPrefs =
+                            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
+                    SharedPreferences.Editor editor = appPrefs.edit();
+                    editor.putBoolean(PREFERENCE_EXPERT_MODE, mExpertMode.isChecked());
+                    editor.apply();
+
+                    if (mExpertMode.isChecked()) {
+                        Log_OC.startLogging(getApplicationContext());
+                    } else {
+                        if (!BuildConfig.DEBUG &&
+                                !getApplicationContext().getResources().getBoolean(R.bool.logger_enabled)) {
+                            Log_OC.stopLogging();
+                        }
+                    }
+
+                    return true;
+                }
+            });
+        }
+    }
+
+    private void setupHiddenFilesPreference(PreferenceCategory preferenceCategoryDetails,
+                                            boolean fShowHiddenFilesEnabled) {
+        mShowHiddenFiles = (SwitchPreference) findPreference("show_hidden_files");
+        if (fShowHiddenFilesEnabled) {
+            mShowHiddenFiles.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+                @Override
+                public boolean onPreferenceClick(Preference preference) {
+                    SharedPreferences appPrefs =
+                            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
+                    SharedPreferences.Editor editor = appPrefs.edit();
+                    editor.putBoolean("show_hidden_files_pref", mShowHiddenFiles.isChecked());
+                    editor.apply();
+                    return true;
+                }
+            });
+        } else {
+            preferenceCategoryDetails.removePreference(mShowHiddenFiles);
+        }
+    }
+
+    private void setupFingerprintPreference(PreferenceCategory preferenceCategoryDetails, boolean fPrintEnabled) {
+        fPrint = (SwitchPreference) findPreference(PREFERENCE_USE_FINGERPRINT);
+        if (fPrint != null) {
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+                if (FingerprintActivity.isFingerprintCapable(MainApp.getAppContext()) && fPrintEnabled) {
+                    final Activity activity = this;
+                    fPrint.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
+                        @Override
+                        public boolean onPreferenceChange(Preference preference, Object newValue) {
+                            Boolean incoming = (Boolean) newValue;
+
+                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+                                if (FingerprintActivity.isFingerprintReady(MainApp.getAppContext())) {
+                                    SharedPreferences appPrefs =
+                                            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
+                                    SharedPreferences.Editor editor = appPrefs.edit();
+                                    editor.putBoolean(PREFERENCE_USE_FINGERPRINT, incoming);
+                                    editor.apply();
+                                    return true;
+                                } else {
+                                    if (incoming) {
+                                        DisplayUtils.showSnackMessage(activity, R.string.prefs_fingerprint_notsetup);
+                                        fPrint.setChecked(false);
+                                    }
+                                    SharedPreferences appPrefs =
+                                            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
+                                    SharedPreferences.Editor editor = appPrefs.edit();
+                                    editor.putBoolean(PREFERENCE_USE_FINGERPRINT, false);
+                                    editor.apply();
+                                    return false;
+                                }
+                            } else {
+                                return false;
+                            }
+                        }
+                    });
+                    if (!FingerprintActivity.isFingerprintReady(MainApp.getAppContext())) {
+                        fPrint.setChecked(false);
+                    }
+
+                } else {
+                    preferenceCategoryDetails.removePreference(fPrint);
+                }
+            } else {
+                preferenceCategoryDetails.removePreference(fPrint);
+            }
+        }
+    }
+
+    private void setupPasscodePreference(PreferenceCategory preferenceCategoryDetails, boolean fPassCodeEnabled) {
+        pCode = (SwitchPreference) findPreference(PassCodeActivity.PREFERENCE_SET_PASSCODE);
+        if (pCode != null && fPassCodeEnabled) {
+            pCode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
+                @Override
+                public boolean onPreferenceChange(Preference preference, Object newValue) {
+                    Intent i = new Intent(getApplicationContext(), PassCodeActivity.class);
+                    Boolean incoming = (Boolean) newValue;
+
+                    i.setAction(
+                            incoming ? PassCodeActivity.ACTION_REQUEST_WITH_RESULT :
+                                    PassCodeActivity.ACTION_CHECK_WITH_RESULT
+                    );
+
+                    startActivityForResult(i, incoming ? ACTION_REQUEST_PASSCODE :
+                            ACTION_CONFIRM_PASSCODE);
+
+                    // Don't update just yet, we will decide on it in onActivityResult
+                    return false;
+                }
+            });
+        } else {
+            preferenceCategoryDetails.removePreference(pCode);
+        }
+    }
+
+    private void setupAutoUploadCategory(int accentColor, PreferenceScreen preferenceScreen) {
+        PreferenceCategory preferenceCategorySyncedFolders =
+                (PreferenceCategory) findPreference("synced_folders_category");
+        preferenceCategorySyncedFolders.setTitle(ThemeUtils.getColoredTitle(getString(R.string.drawer_synced_folders),
+                accentColor));
+
+        if (!getResources().getBoolean(R.bool.syncedFolder_light)) {
+            preferenceScreen.removePreference(preferenceCategorySyncedFolders);
+        } else {
+            // Upload on WiFi
+            final ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
+            final Account account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
+
+            final SwitchPreference pUploadOnWifiCheckbox = (SwitchPreference) findPreference("synced_folder_on_wifi");
+            pUploadOnWifiCheckbox.setChecked(
+                    arbitraryDataProvider.getBooleanValue(account, SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI));
+
+            pUploadOnWifiCheckbox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+                @Override
+                public boolean onPreferenceClick(Preference preference) {
+                    arbitraryDataProvider.storeOrUpdateKeyValue(account.name, SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI,
+                            String.valueOf(pUploadOnWifiCheckbox.isChecked()));
+
+                    return true;
+                }
+            });
+
+            Preference pSyncedFolder = findPreference("synced_folders_configure_folders");
+            if (pSyncedFolder != null) {
+                if (getResources().getBoolean(R.bool.syncedFolder_light)
+                        && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+                    pSyncedFolder.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+                        @Override
+                        public boolean onPreferenceClick(Preference preference) {
+                            Intent syncedFoldersIntent =
+                                    new Intent(getApplicationContext(), SyncedFoldersActivity.class);
+                            syncedFoldersIntent.putExtra(SyncedFoldersActivity.EXTRA_SHOW_SIDEBAR, false);
+                            startActivity(syncedFoldersIntent);
+                            return true;
+                        }
+                    });
+                } else {
+                    preferenceCategorySyncedFolders.removePreference(pSyncedFolder);
+                }
+            }
+        }
+    }
+
+    private void setupGeneralCategory(int accentColor) {
+        PreferenceCategory preferenceCategoryGeneral = (PreferenceCategory) findPreference("general");
+        preferenceCategoryGeneral.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_general),
+                accentColor));
 
         mPrefStoragePath = (ListPreference) findPreference(PreferenceKeys.STORAGE_PATH);
         if (mPrefStoragePath != null) {
@@ -557,90 +680,43 @@ public class Preferences extends PreferenceActivity
             });
         }
 
-        // About category
-        PreferenceCategory preferenceCategoryAbout = (PreferenceCategory) findPreference("about");
-        preferenceCategoryAbout.setTitle(ThemeUtils.getColoredTitle(getString(R.string.prefs_category_about),
-                accentColor));
+        loadStoragePath();
+    }
 
-        /* About App */
-        pAboutApp = findPreference("about_app");
-        if (pAboutApp != null) {
-            pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
-            pAboutApp.setSummary(String.format(getString(R.string.about_version), appVersion));
+    private String getAppVersion() {
+        String temp;
+        try {
+            PackageInfo pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
+            temp = pkg.versionName;
+        } catch (NameNotFoundException e) {
+            temp = "";
+            Log_OC.e(TAG, "Error while showing about dialog", e);
         }
+        return temp;
+    }
 
-        // source code
-        boolean sourcecodeEnabled = getResources().getBoolean(R.bool.sourcecode_enabled);
-        Preference sourcecodePreference = findPreference("sourcecode");
-        if (sourcecodePreference != null) {
-            String sourcecodeUrl = getString(R.string.sourcecode_url);
+    private void setupActionBar() {
+        ActionBar actionBar = getDelegate().getSupportActionBar();
+        actionBar.setDisplayHomeAsUpEnabled(true);
+        ThemeUtils.setColoredTitle(actionBar, getString(R.string.actionbar_settings));
+        actionBar.setBackgroundDrawable(new ColorDrawable(ThemeUtils.primaryColor()));
+        getWindow().getDecorView().setBackgroundDrawable(new ColorDrawable(ResourcesCompat
+                .getColor(getResources(), R.color.background_color, null)));
 
-            if (sourcecodeEnabled && !sourcecodeUrl.isEmpty()) {
-                sourcecodePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
-                    @Override
-                    public boolean onPreferenceClick(Preference preference) {
-                        Uri uriUrl = Uri.parse(sourcecodeUrl);
-                        Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
-                        startActivity(intent);
-                        return true;
-                    }
-                });
-            } else {
-                preferenceCategoryAbout.removePreference(sourcecodePreference);
-            }
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+            getWindow().setStatusBarColor(ThemeUtils.primaryDarkColor());
         }
 
-        // license
-        boolean licenseEnabled = getResources().getBoolean(R.bool.license_enabled);
-        Preference licensePreference = findPreference("license");
-        if (licensePreference != null) {
-            String licenseUrl = getString(R.string.license_url);
-
-            if (licenseEnabled && !licenseUrl.isEmpty()) {
-                licensePreference.setSummary(R.string.prefs_gpl_v2);
-                licensePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
-                    @Override
-                    public boolean onPreferenceClick(Preference preference) {
-                        Uri uriUrl = Uri.parse(licenseUrl);
-                        Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
-                        startActivity(intent);
-                        return true;
-                    }
-                });
-            } else {
-                preferenceCategoryAbout.removePreference(licensePreference);
-            }
-        }
+        Drawable backArrow = getResources().getDrawable(R.drawable.ic_arrow_back);
+        actionBar.setHomeAsUpIndicator(ThemeUtils.tintDrawable(backArrow, ThemeUtils.fontColor()));
 
-        // privacy
-        boolean privacyEnabled = getResources().getBoolean(R.bool.privacy_enabled);
-        Preference privacyPreference = findPreference("privacy");
-        if (privacyPreference != null) {
-            if (privacyEnabled) {
-                privacyPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
-                    @Override
-                    public boolean onPreferenceClick(Preference preference) {
-                        String privacyUrl = getString(R.string.privacy_url);
-                        if (privacyUrl.length() > 0) {
-                            Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
-                            externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE,
-                                    getResources().getString(R.string.privacy));
-                            externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, privacyUrl);
-                            externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, false);
-                            externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, -1);
-                            startActivity(externalWebViewIntent);
-                        }
-                        return true;
-                    }
-                });
-            } else {
-                preferenceCategoryAbout.removePreference(privacyPreference);
-            }
+        // For adding content description tag to a title field in the action bar
+        int actionBarTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
+        View actionBarTitleView = getWindow().getDecorView().findViewById(actionBarTitleId);
+        if (actionBarTitleView != null) {    // it's null in Android 2.x
+            getWindow().getDecorView().findViewById(actionBarTitleId).
+                    setContentDescription(getString(R.string.actionbar_settings));
         }
-
-        loadExternalSettingLinks(preferenceCategoryMore);
-
-        loadStoragePath();
     }
 
     private void launchDavDroidLogin()
@@ -655,7 +731,7 @@ public class Preferences extends PreferenceActivity
         if (getPackageManager().resolveActivity(davDroidLoginIntent, 0) != null) {
             // arguments
             if (mUri != null) {
-                davDroidLoginIntent.putExtra("url", mUri.toString() + AccountUtils.DAV_PATH);
+                davDroidLoginIntent.putExtra("url", mUri.toString() + DAV_PATH);
             }
             davDroidLoginIntent.putExtra("username", AccountUtils.getAccountUsername(account.name));
             //loginIntent.putExtra("password", "...");
@@ -849,7 +925,8 @@ public class Preferences extends PreferenceActivity
                     p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                         @Override
                         public boolean onPreferenceClick(Preference preference) {
-                            Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
+                            Intent externalWebViewIntent =
+                                    new Intent(getApplicationContext(), ExternalSiteWebView.class);
                             externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE, link.name);
                             externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, link.url);
                             externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, false);

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

@@ -125,7 +125,7 @@ public class SyncedFoldersActivity extends FileActivity implements SyncedFolderA
 
 
         findViewById(R.id.toolbar).post(() -> {
-            if (!appPrefs.getBoolean("expert_mode", false)) {
+            if (!appPrefs.getBoolean(Preferences.PREFERENCE_EXPERT_MODE, false)) {
                 findViewById(R.id.app_bar).getLayoutParams().height = findViewById(R.id.toolbar).getHeight();
 
                 AppBarLayout.LayoutParams p = (AppBarLayout.LayoutParams) mCollapsingToolbarLayout.getLayoutParams();

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

@@ -79,7 +79,6 @@ public class UploadFilesActivity extends FileActivity implements
     private boolean mSelectAll = false;
     private boolean mLocalFolderPickerMode = false;
     private LocalFileListFragment mFileListFragment;
-    private Button mCancelBtn;
     protected Button mUploadBtn;
     private Spinner mBehaviourSpinner;
     private Account mAccountOnCreation;
@@ -151,8 +150,8 @@ public class UploadFilesActivity extends FileActivity implements
         mFileListFragment = (LocalFileListFragment) getSupportFragmentManager().findFragmentById(R.id.local_files_list);
         
         // Set input controllers
-        mCancelBtn = (Button) findViewById(R.id.upload_files_btn_cancel);
-        mCancelBtn.setOnClickListener(this);
+        findViewById(R.id.upload_files_btn_cancel).setOnClickListener(this);
+
         mUploadBtn = (AppCompatButton) findViewById(R.id.upload_files_btn_upload);
         mUploadBtn.getBackground().setColorFilter(ThemeUtils.primaryAccentColor(), PorterDuff.Mode.SRC_ATOP);
         mUploadBtn.setOnClickListener(this);

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

@@ -61,7 +61,7 @@ import com.owncloud.android.utils.MimeTypeUtil;
 
 import java.io.File;
 
-import static com.owncloud.android.ui.activity.Preferences.EXPERT_MODE;
+import static com.owncloud.android.ui.activity.Preferences.PREFERENCE_EXPERT_MODE;
 
 /**
  * Activity listing pending, active, and completed uploads. User can delete
@@ -255,7 +255,7 @@ public class UploadListActivity extends FileActivity implements UploadListFragme
     public boolean onCreateOptionsMenu(Menu menu) {
         SharedPreferences appPrefs =
                 PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
-        if (appPrefs.getBoolean(EXPERT_MODE, false)) {
+        if (appPrefs.getBoolean(PREFERENCE_EXPERT_MODE, false)) {
             MenuInflater inflater = getMenuInflater();
             inflater.inflate(R.menu.upload_list_menu, menu);
             mMenu = menu;

+ 14 - 14
src/main/java/com/owncloud/android/ui/adapter/AccountListAdapter.java

@@ -65,26 +65,26 @@ public class AccountListAdapter extends ArrayAdapter<AccountListItem> implements
     @Override
     public View getView(final int position, View convertView, ViewGroup parent) {
         AccountViewHolderItem viewHolder;
+        View view = convertView;
 
-        if (convertView == null) {
+        if (view == null) {
             LayoutInflater inflater = mContext.getLayoutInflater();
-            convertView = inflater.inflate(R.layout.account_item, parent, false);
+            view = inflater.inflate(R.layout.account_item, parent, false);
 
             viewHolder = new AccountViewHolderItem();
-            viewHolder.imageViewItem = (ImageView) convertView.findViewById(R.id.user_icon);
-            viewHolder.checkViewItem = (ImageView) convertView.findViewById(R.id.ticker);
+            viewHolder.imageViewItem = (ImageView) view.findViewById(R.id.user_icon);
+            viewHolder.checkViewItem = (ImageView) view.findViewById(R.id.ticker);
             viewHolder.checkViewItem.setImageDrawable(mTintedCheck);
-            viewHolder.usernameViewItem = (TextView) convertView.findViewById(R.id.user_name);
-            viewHolder.accountViewItem = (TextView) convertView.findViewById(R.id.account);
+            viewHolder.usernameViewItem = (TextView) view.findViewById(R.id.user_name);
+            viewHolder.accountViewItem = (TextView) view.findViewById(R.id.account);
 
-            convertView.setTag(viewHolder);
+            view.setTag(viewHolder);
         } else {
-            viewHolder = (AccountViewHolderItem) convertView.getTag();
+            viewHolder = (AccountViewHolderItem) view.getTag();
         }
 
         AccountListItem accountListItem = mValues.get(position);
 
-
         if (accountListItem != null) {
             // create account item
             if (AccountListItem.TYPE_ACCOUNT == accountListItem.getType()) {
@@ -111,7 +111,7 @@ public class AccountListAdapter extends ArrayAdapter<AccountListItem> implements
             }
         }
 
-        return convertView;
+        return view;
     }
 
     @NonNull
@@ -192,10 +192,10 @@ public class AccountListAdapter extends ArrayAdapter<AccountListItem> implements
      * Account ViewHolderItem to get smooth scrolling.
      */
     private static class AccountViewHolderItem {
-        ImageView imageViewItem;
-        ImageView checkViewItem;
+        private ImageView imageViewItem;
+        private ImageView checkViewItem;
 
-        TextView usernameViewItem;
-        TextView accountViewItem;
+        private TextView usernameViewItem;
+        private TextView accountViewItem;
     }
 }

+ 19 - 49
src/main/java/com/owncloud/android/ui/adapter/ExpandableUploadListAdapter.java

@@ -44,7 +44,6 @@ import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus;
 import com.owncloud.android.db.OCUpload;
 import com.owncloud.android.db.UploadResult;
 import com.owncloud.android.files.services.FileUploader;
-import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
 import com.owncloud.android.lib.common.utils.Log_OC;
 import com.owncloud.android.ui.activity.FileActivity;
 import com.owncloud.android.utils.DisplayUtils;
@@ -52,7 +51,6 @@ import com.owncloud.android.utils.MimeTypeUtil;
 import com.owncloud.android.utils.ThemeUtils;
 
 import java.io.File;
-import java.lang.ref.WeakReference;
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.Observable;
@@ -81,8 +79,8 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
     }
 
     abstract class UploadGroup implements Refresh {
-        OCUpload[] items;
-        String name;
+        private OCUpload[] items;
+        private String name;
 
         public UploadGroup(String groupName) {
             this.name = groupName;
@@ -93,6 +91,14 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
             return name;
         }
 
+        public OCUpload[] getItems() {
+            return items;
+        }
+
+        public void setItems(OCUpload[] items) {
+            this.items = items;
+        }
+
         public int getGroupItemCount() {
             return items == null ? 0 : items.length;
         }
@@ -147,31 +153,33 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
         mParentActivity = parentActivity;
         mUploadsStorageManager = new UploadsStorageManager(mParentActivity.getContentResolver(), parentActivity.getApplicationContext());
         mUploadGroups = new UploadGroup[3];
+
         mUploadGroups[0] = new UploadGroup(mParentActivity.getString(R.string.uploads_view_group_current_uploads)) {
             @Override
             public void refresh() {
-                items = mUploadsStorageManager.getCurrentAndPendingUploadsForCurrentAccount();
-                Arrays.sort(items, comparator);
+                setItems(mUploadsStorageManager.getCurrentAndPendingUploadsForCurrentAccount());
+                Arrays.sort(getItems(), comparator);
             }
         };
+
         mUploadGroups[1] = new UploadGroup(mParentActivity.getString(R.string.uploads_view_group_failed_uploads)) {
             @Override
             public void refresh() {
-                items = mUploadsStorageManager.getFailedButNotDelayedUploadsForCurrentAccount();
-                Arrays.sort(items, comparator);
+                setItems(mUploadsStorageManager.getFailedButNotDelayedUploadsForCurrentAccount());
+                Arrays.sort(getItems(), comparator);
             }
         };
+
         mUploadGroups[2] = new UploadGroup(mParentActivity.getString(R.string.uploads_view_group_finished_uploads)) {
             @Override
             public void refresh() {
-                items = mUploadsStorageManager.getFinishedUploadsForCurrentAccount();
-                Arrays.sort(items, comparator);
+                setItems(mUploadsStorageManager.getFinishedUploadsForCurrentAccount());
+                Arrays.sort(getItems(), comparator);
             }
         };
         loadUploadItemsFromDb();
     }
 
-
     @Override
     public void registerDataSetObserver(DataSetObserver observer) {
         super.registerDataSetObserver(observer);
@@ -718,44 +726,6 @@ public class ExpandableUploadListAdapter extends BaseExpandableListAdapter imple
         return true;
     }
 
-    public class ProgressListener implements OnDatatransferProgressListener {
-        int mLastPercent = 0;
-        OCUpload mUpload = null;
-        WeakReference<ProgressBar> mProgressBar = null;
-
-        public ProgressListener(OCUpload upload, ProgressBar progressBar) {
-            mUpload = upload;
-            mProgressBar = new WeakReference<ProgressBar>(progressBar);
-        }
-
-        @Override
-        public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String
-                filename) {
-            int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
-            if (percent != mLastPercent) {
-                ProgressBar pb = mProgressBar.get();
-                if (pb != null) {
-                    pb.setProgress(percent);
-                    pb.postInvalidate();
-                }
-            }
-            mLastPercent = percent;
-        }
-
-        public boolean isWrapping(ProgressBar progressBar) {
-            ProgressBar wrappedProgressBar = mProgressBar.get();
-            return (
-                    wrappedProgressBar != null &&
-                            wrappedProgressBar == progressBar   // on purpose; don't replace with equals
-            );
-        }
-
-        public OCUpload getUpload() {
-            return mUpload;
-        }
-
-    }
-
     public void addBinder() {
         notifyDataSetChanged();
     }

+ 73 - 0
src/main/java/com/owncloud/android/ui/adapter/ProgressListener.java

@@ -0,0 +1,73 @@
+/*
+ * Nextcloud Android client application
+ *
+ * @author Andy Scherzinger
+ * Copyright (C) 2016 Andy Scherzinger
+ * Copyright (C) 2016 Nextcloud
+ * Copyright (C) 2016 ownCloud GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.owncloud.android.ui.adapter;
+
+import android.widget.ProgressBar;
+
+import com.owncloud.android.db.OCUpload;
+import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
+
+import java.lang.ref.WeakReference;
+
+/**
+ * Progress listener for file transfers.
+ */
+public class ProgressListener implements OnDatatransferProgressListener {
+    private int mLastPercent = 0;
+    private OCUpload mUpload = null;
+    private WeakReference<ProgressBar> mProgressBar = null;
+
+    public ProgressListener(OCUpload upload, ProgressBar progressBar) {
+        mUpload = upload;
+        mProgressBar = new WeakReference<>(progressBar);
+    }
+
+    @Override
+    public void onTransferProgress(
+            long progressRate,
+            long totalTransferredSoFar,
+            long totalToTransfer,
+            String fileAbsoluteName) {
+        int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
+
+        if (percent != mLastPercent) {
+            ProgressBar progressBar = mProgressBar.get();
+            if (progressBar != null) {
+                progressBar.setProgress(percent);
+                progressBar.postInvalidate();
+            }
+        }
+
+        mLastPercent = percent;
+    }
+
+    public boolean isWrapping(ProgressBar progressBar) {
+        ProgressBar wrappedProgressBar = mProgressBar.get();
+        return (
+                wrappedProgressBar != null &&
+                        wrappedProgressBar == progressBar   // on purpose; don't replace with equals
+        );
+    }
+
+    public OCUpload getUpload() {
+        return mUpload;
+    }
+}

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

@@ -154,11 +154,13 @@ public class ShareLinkToDialog  extends DialogFragment {
         
         @Override
         public @NonNull View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
-            if (convertView == null) {
-                convertView = newView(parent);
+            View view = convertView;
+
+            if (view == null) {
+                view = newView(parent);
             }
-            bindView(position, convertView);
-            return convertView;
+            bindView(position, view);
+            return view;
         }
         
         private View newView(ViewGroup parent) {

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

@@ -72,7 +72,6 @@ public class SearchShareesFragment extends Fragment implements ShareUserListAdap
 
     // other members
     private ArrayList<OCShare> mShares;
-    private ShareUserListAdapter mUserGroupsAdapter = null;
     private ShareFragmentListener mListener;
 
 
@@ -183,7 +182,7 @@ public class SearchShareesFragment extends Fragment implements ShareUserListAdap
     private void updateListOfUserGroups() {
         // Update list of users/groups
         // TODO Refactoring: create a new {@link ShareUserListAdapter} instance with every call should not be needed
-        mUserGroupsAdapter = new ShareUserListAdapter(
+        ShareUserListAdapter userGroupsAdapter = new ShareUserListAdapter(
                 getActivity().getApplicationContext(),
                 R.layout.share_user_item, mShares, this
         );
@@ -193,7 +192,7 @@ public class SearchShareesFragment extends Fragment implements ShareUserListAdap
 
         if (mShares.size() > 0) {
             usersList.setVisibility(View.VISIBLE);
-            usersList.setAdapter(mUserGroupsAdapter);
+            usersList.setAdapter(userGroupsAdapter);
 
         } else {
             usersList.setVisibility(View.GONE);

+ 1 - 6
src/main/java/com/owncloud/android/ui/fragment/ShareFileFragment.java

@@ -118,11 +118,6 @@ public class ShareFileFragment extends Fragment implements ShareUserListAdapter.
      */
     private OCCapability mCapabilities;
 
-    /**
-     * Adapter to show private shares.
-     */
-    private ShareUserListAdapter mUserGroupsAdapter = null;
-
     /**
      * Public share bound to the file.
      */
@@ -651,7 +646,7 @@ public class ShareFileFragment extends Fragment implements ShareUserListAdapter.
     private void updateListOfUserGroups() {
         // Update list of users/groups
         // TODO Refactoring: create a new {@link ShareUserListAdapter} instance with every call should not be needed
-        mUserGroupsAdapter = new ShareUserListAdapter(
+        ShareUserListAdapter mUserGroupsAdapter = new ShareUserListAdapter(
                 getActivity(),
                 R.layout.share_user_item,
                 mPrivateShares,