浏览代码

- requested changes by review by davivel

tobiasKaminsky 10 年之前
父节点
当前提交
bc3f8b3354

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

@@ -20,8 +20,9 @@ package com.owncloud.android.datamodel;
 
 import java.io.File;
 
-import com.owncloud.android.utils.Log_OC;
+import third_parties.daveKoeller.AlphanumComparator;
 
+import com.owncloud.android.utils.Log_OC;
 
 import android.os.Parcel;
 import android.os.Parcelable;

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

@@ -493,7 +493,7 @@ OnSslUntrustedCertListener, SwipeRefreshLayout.OnRefreshListener {
         }
         case R.id.action_sort: {
             SharedPreferences appPreferences = PreferenceManager
-                    .getDefaultSharedPreferences(getApplicationContext());
+                    .getDefaultSharedPreferences(this);
             
             // Read sorting order, default to sort by name ascending
             Integer sortOrder = appPreferences

+ 419 - 408
src/com/owncloud/android/ui/adapter/FileListListAdapter.java

@@ -22,6 +22,7 @@ import java.util.Collections;
 import java.util.Comparator;
 import java.util.Vector;
 
+import third_parties.daveKoeller.AlphanumComparator;
 import android.accounts.Account;
 import android.content.Context;
 import android.content.SharedPreferences;
@@ -37,7 +38,6 @@ import android.widget.TextView;
 
 import com.owncloud.android.R;
 import com.owncloud.android.authentication.AccountUtils;
-import com.owncloud.android.datamodel.AlphanumComparator;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
@@ -45,8 +45,6 @@ import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
 import com.owncloud.android.ui.activity.ComponentsGetter;
 import com.owncloud.android.utils.DisplayUtils;
 import com.owncloud.android.utils.FileStorageUtils;
-import com.owncloud.android.utils.Log_OC;
-
 
 /**
  * This Adapter populates a ListView with all files and folders in an ownCloud
@@ -56,409 +54,422 @@ import com.owncloud.android.utils.Log_OC;
  * 
  */
 public class FileListListAdapter extends BaseAdapter implements ListAdapter {
-    private final static String PERMISSION_SHARED_WITH_ME = "S";
-
-    private Context mContext;
-    private OCFile mFile = null;
-    private Vector<OCFile> mFiles = null;
-    private boolean mJustFolders;
-
-    private FileDataStorageManager mStorageManager;
-    private Account mAccount;
-    private ComponentsGetter mTransferServiceGetter;
-    private Integer sortOrder;
-    private Boolean sortAscending;
-    private SharedPreferences appPreferences;
-    
-    public FileListListAdapter(
-            boolean justFolders, 
-            Context context, 
-            ComponentsGetter transferServiceGetter
-            ) {
-        mJustFolders = justFolders;
-        mContext = context;
-        mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
-        mTransferServiceGetter = transferServiceGetter;
-        
-        appPreferences = PreferenceManager
-                .getDefaultSharedPreferences(mContext);
-        
-        // Read sorting order, default to sort by name ascending
-        sortOrder = appPreferences
-                .getInt("sortOrder", 0);
-        sortAscending = appPreferences.getBoolean("sortAscending", true);
-        
-    }
-
-    @Override
-    public boolean areAllItemsEnabled() {
-        return true;
-    }
-
-    @Override
-    public boolean isEnabled(int position) {
-        return true;
-    }
-
-    @Override
-    public int getCount() {
-        return mFiles != null ? mFiles.size() : 0;
-    }
-
-    @Override
-    public Object getItem(int position) {
-        if (mFiles == null || mFiles.size() <= position)
-            return null;
-        return mFiles.get(position);
-    }
-
-    @Override
-    public long getItemId(int position) {
-        if (mFiles == null || mFiles.size() <= position)
-            return 0;
-        return mFiles.get(position).getFileId();
-    }
-
-    @Override
-    public int getItemViewType(int position) {
-        return 0;
-    }
-
-    @Override
-    public View getView(int position, View convertView, ViewGroup parent) {
-        View view = convertView;
-        if (view == null) {
-            LayoutInflater inflator = (LayoutInflater) mContext
-                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-            view = inflator.inflate(R.layout.list_item, null);
-        }
-    
-        if (mFiles != null && mFiles.size() > position) {
-            OCFile file = mFiles.get(position);
-            TextView fileName = (TextView) view.findViewById(R.id.Filename);
-            String name = file.getFileName();
-
-            fileName.setText(name);
-            ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
-            ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
-            ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);
-            sharedWithMeIconV.setVisibility(View.GONE);
-
-            ImageView localStateView = (ImageView) view.findViewById(R.id.imageView2);
-            localStateView.bringToFront();
-            FileDownloaderBinder downloaderBinder = mTransferServiceGetter.getFileDownloaderBinder();
-            FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
-            if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) {
-                localStateView.setImageResource(R.drawable.downloading_file_indicator);
-                localStateView.setVisibility(View.VISIBLE);
-            } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
-                localStateView.setImageResource(R.drawable.uploading_file_indicator);
-                localStateView.setVisibility(View.VISIBLE);
-            } else if (file.isDown()) {
-                localStateView.setImageResource(R.drawable.local_file_indicator);
-                localStateView.setVisibility(View.VISIBLE);
-            } else {
-                localStateView.setVisibility(View.INVISIBLE);
-            }
-            
-            TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
-            TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
-            ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
-            
-            if (!file.isFolder()) {
-                fileSizeV.setVisibility(View.VISIBLE);
-                fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
-                lastModV.setVisibility(View.VISIBLE);
-                lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
-                // this if-else is needed even thoe fav icon is visible by default
-                // because android reuses views in listview
-                if (!file.keepInSync()) {
-                    view.findViewById(R.id.imageView3).setVisibility(View.GONE);
-                } else {
-                    view.findViewById(R.id.imageView3).setVisibility(View.VISIBLE);
-                }
-                
-                ListView parentList = (ListView)parent;
-                if (parentList.getChoiceMode() == ListView.CHOICE_MODE_NONE) { 
-                    checkBoxV.setVisibility(View.GONE);
-                } else {
-                    if (parentList.isItemChecked(position)) {
-                        checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
-                    } else {
-                        checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
-                    }
-                    checkBoxV.setVisibility(View.VISIBLE);
-                }
-
-                fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
-
-                if (checkIfFileIsSharedWithMe(file)) {
-                    sharedWithMeIconV.setVisibility(View.VISIBLE);
-                }
-            } 
-            else {
-                if (FileStorageUtils.getDefaultSavePathFor(mAccount.name, file) != null){
-                    fileSizeV.setVisibility(View.VISIBLE);
-                    fileSizeV.setText(getFolderSizeHuman(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file)));
-                } else {
-                    fileSizeV.setVisibility(View.INVISIBLE);
-                }
-                
-                lastModV.setVisibility(View.VISIBLE);
-                lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
-                checkBoxV.setVisibility(View.GONE);
-                view.findViewById(R.id.imageView3).setVisibility(View.GONE);
-
-                if (checkIfFileIsSharedWithMe(file)) {
-                    fileIcon.setImageResource(R.drawable.shared_with_me_folder);
-                    sharedWithMeIconV.setVisibility(View.VISIBLE);
-                } else {
-                    fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
-                }
-
-                // If folder is sharedByLink, icon folder must be changed to
-                // folder-public one
-                if (file.isShareByLink()) {
-                    fileIcon.setImageResource(R.drawable.folder_public);
-                }
-            }
-
-            if (file.isShareByLink()) {
-                sharedIconV.setVisibility(View.VISIBLE);
-            } else {
-                sharedIconV.setVisibility(View.GONE);
-            }
-        }
-
-        return view;
-    }
-    
-    /**
-     * Local Folder size in human readable format
-     * @param path String
-     * @return Size in human readable format
-     */
-    private String getFolderSizeHuman(String path) {
-
-        File dir = new File(path);
-
-        if(dir.exists()) {
-            long bytes = getFolderSize(dir);
-            if (bytes < 1024) return bytes + " B";
-            int exp = (int) (Math.log(bytes) / Math.log(1024));
-            String pre = ("KMGTPE").charAt(exp-1) + "";
-
-            return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre);
-        }
-
-        return "0 B";
-    }
-
-    /**
-     * Local Folder size
-     * @param dir File
-     * @return Size in bytes
-     */
-    private long getFolderSize(File dir) {
-        if (dir.exists()) {
-            long result = 0;
-            File[] fileList = dir.listFiles();
-            for(int i = 0; i < fileList.length; i++) {
-                if(fileList[i].isDirectory()) {
-                    result += getFolderSize(fileList[i]);
-                } else {
-                    result += fileList[i].length();
-                }
-            }
-            return result;
-        }
-        return 0;
-    } 
-
-    @Override
-    public int getViewTypeCount() {
-        return 1;
-    }
-
-    @Override
-    public boolean hasStableIds() {
-        return true;
-    }
-
-    @Override
-    public boolean isEmpty() {
-        return (mFiles == null || mFiles.isEmpty());
-    }
-
-    /**
-     * Change the adapted directory for a new one
-     * @param directory                 New file to adapt. Can be NULL, meaning "no content to adapt".
-     * @param updatedStorageManager     Optional updated storage manager; used to replace mStorageManager if is different (and not NULL)
-     */
-    public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager) {
-        mFile = directory;
-        if (updatedStorageManager != null && updatedStorageManager != mStorageManager) {
-            mStorageManager = updatedStorageManager;
-            mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
-        }
-        if (mStorageManager != null) {
-            mFiles = mStorageManager.getFolderContent(mFile);
-            if (mJustFolders) {
-                mFiles = getFolders(mFiles);
-            }
-        } else {
-            mFiles = null;
-        }
-
-        sortDirectory();
-    }
-    
-    /**
-     * Sorts all filenames, regarding last user decision 
-     */
-    private void sortDirectory(){
-        switch (sortOrder){
-        case 0:
-            sortByName(sortAscending);
-            break;
-        case 1:
-            sortByDate(sortAscending);
-            break;
-        case 2: 
-            sortBySize(sortAscending);
-            break;
-        }
-        
-        notifyDataSetChanged();
-    }
-    
-    
-    /**
-     * Filter for getting only the folders
-     * @param files
-     * @return Vector<OCFile>
-     */
-    public Vector<OCFile> getFolders(Vector<OCFile> files) {
-        Vector<OCFile> ret = new Vector<OCFile>(); 
-        OCFile current = null; 
-        for (int i=0; i<files.size(); i++) {
-            current = files.get(i);
-            if (current.isFolder()) {
-                ret.add(current);
-            }
-        }
-        return ret;
-    }
-    
-    
-    /**
-     * Check if parent folder does not include 'S' permission and if file/folder
-     * is shared with me
-     * 
-     * @param file: OCFile
-     * @return boolean: True if it is shared with me and false if it is not
-     */
-    private boolean checkIfFileIsSharedWithMe(OCFile file) {
-        return (mFile.getPermissions() != null && !mFile.getPermissions().contains(PERMISSION_SHARED_WITH_ME)
-                && file.getPermissions() != null && file.getPermissions().contains(PERMISSION_SHARED_WITH_ME));
-    }
-
-    /**
-     * Sorts list by Date
-     * @param sortAscending true: ascending, false: descending
-     */
-    private void sortByDate(boolean sortAscending){
-        final Integer val;
-        if (sortAscending){
-            val = 1;
-        } else {
-            val = -1;
-        }
-        
-        Collections.sort(mFiles, new Comparator<OCFile>() {
-            public int compare(OCFile o1, OCFile o2) {
-                if (o1.isFolder() && o2.isFolder()) {
-                    return val * Long.compare(o1.getModificationTimestamp(), o2.getModificationTimestamp());
-                }
-                else if (o1.isFolder()) {
-                    return -1;
-                } else if (o2.isFolder()) {
-                    return 1;
-                } else if (o1.getModificationTimestamp() == 0 || o2.getModificationTimestamp() == 0){
-                    return 0;
-                } else {
-                    return val * Long.compare(o1.getModificationTimestamp(), o2.getModificationTimestamp());
-                }
-            }
-        });
-    }
-
-    /**
-     * Sorts list by Size
-     * @param sortAscending true: ascending, false: descending
-     */
-    private void sortBySize(boolean sortAscending){
-        final Integer val;
-        if (sortAscending){
-            val = 1;
-        } else {
-            val = -1;
-        }
-        
-        Collections.sort(mFiles, new Comparator<OCFile>() {
-            public int compare(OCFile o1, OCFile o2) {
-                if (o1.isFolder() && o2.isFolder()) {
-                    return val * Long.compare(getFolderSize(new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, o1))), 
-                                              getFolderSize(new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, o2))));
-                }
-                else if (o1.isFolder()) {
-                    return -1;
-                } else if (o2.isFolder()) {
-                    return 1;
-                } else if (o1.getFileLength() == 0 || o2.getFileLength() == 0){
-                    return 0;
-                } else {
-                    return val * Long.compare(o1.getFileLength(), o2.getFileLength());
-                }
-            }
-        });
-    }
-
-    /**
-     * Sorts list by Name
-     * @param sortAscending true: ascending, false: descending
-     */
-    private void sortByName(boolean sortAscending){
-        final Integer val;
-        if (sortAscending){
-            val = 1;
-        } else {
-            val = -1;
-        }
-
-        Collections.sort(mFiles, new Comparator<OCFile>() {
-            public int compare(OCFile o1, OCFile o2) {
-                if (o1.isFolder() && o2.isFolder()) {
-                    return val * o1.getRemotePath().toLowerCase().compareTo(o2.getRemotePath().toLowerCase());
-                } else if (o1.isFolder()) {
-                    return -1;
-                } else if (o2.isFolder()) {
-                    return 1;
-                }
-                return val * new AlphanumComparator().compare(o1, o2);
-            }
-        });
-    }
-
-    public void setSortOrder(Integer order, boolean ascending) {
-        SharedPreferences.Editor editor = appPreferences.edit();
-        editor.putInt("sortOrder", order);
-        editor.putBoolean("sortAscending", ascending);
-        editor.commit();
-        
-        sortOrder = order;
-        sortAscending = ascending;
-        
-        sortDirectory();
-    }    
+	private final static String PERMISSION_SHARED_WITH_ME = "S";
+
+	private final Context mContext;
+	private OCFile mFile = null;
+	private Vector<OCFile> mFiles = null;
+	private final boolean mJustFolders;
+
+	private FileDataStorageManager mStorageManager;
+	private Account mAccount;
+	private final ComponentsGetter mTransferServiceGetter;
+	private Integer mSortOrder;
+	public static final Integer mSortName = 0;
+	public static final Integer mSortDate = 1;
+	public static final Integer mSortSize = 2;
+	private Boolean mSortAscending;
+	private final SharedPreferences mAppPreferences;
+
+	public FileListListAdapter(boolean justFolders, Context context, ComponentsGetter transferServiceGetter) {
+		mJustFolders = justFolders;
+		mContext = context;
+		mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
+		mTransferServiceGetter = transferServiceGetter;
+
+		mAppPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
+
+		// Read sorting order, default to sort by name ascending
+		mSortOrder = mAppPreferences.getInt("sortOrder", mSortName);
+		mSortAscending = mAppPreferences.getBoolean("sortAscending", true);
+
+	}
+
+	@Override
+	public boolean areAllItemsEnabled() {
+		return true;
+	}
+
+	@Override
+	public boolean isEnabled(int position) {
+		return true;
+	}
+
+	@Override
+	public int getCount() {
+		return mFiles != null ? mFiles.size() : 0;
+	}
+
+	@Override
+	public Object getItem(int position) {
+		if (mFiles == null || mFiles.size() <= position)
+			return null;
+		return mFiles.get(position);
+	}
+
+	@Override
+	public long getItemId(int position) {
+		if (mFiles == null || mFiles.size() <= position)
+			return 0;
+		return mFiles.get(position).getFileId();
+	}
+
+	@Override
+	public int getItemViewType(int position) {
+		return 0;
+	}
+
+	@Override
+	public View getView(int position, View convertView, ViewGroup parent) {
+		View view = convertView;
+		if (view == null) {
+			LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+			view = inflator.inflate(R.layout.list_item, null);
+		}
+
+		if (mFiles != null && mFiles.size() > position) {
+			OCFile file = mFiles.get(position);
+			TextView fileName = (TextView) view.findViewById(R.id.Filename);
+			String name = file.getFileName();
+
+			fileName.setText(name);
+			ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
+			ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
+			ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);
+			sharedWithMeIconV.setVisibility(View.GONE);
+
+			ImageView localStateView = (ImageView) view.findViewById(R.id.imageView2);
+			localStateView.bringToFront();
+			FileDownloaderBinder downloaderBinder = mTransferServiceGetter.getFileDownloaderBinder();
+			FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
+			if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) {
+				localStateView.setImageResource(R.drawable.downloading_file_indicator);
+				localStateView.setVisibility(View.VISIBLE);
+			} else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
+				localStateView.setImageResource(R.drawable.uploading_file_indicator);
+				localStateView.setVisibility(View.VISIBLE);
+			} else if (file.isDown()) {
+				localStateView.setImageResource(R.drawable.local_file_indicator);
+				localStateView.setVisibility(View.VISIBLE);
+			} else {
+				localStateView.setVisibility(View.INVISIBLE);
+			}
+
+			TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
+			TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
+			ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
+
+			if (!file.isFolder()) {
+				fileSizeV.setVisibility(View.VISIBLE);
+				fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
+				lastModV.setVisibility(View.VISIBLE);
+				lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
+				// this if-else is needed even thoe fav icon is visible by
+				// default
+				// because android reuses views in listview
+				if (!file.keepInSync()) {
+					view.findViewById(R.id.imageView3).setVisibility(View.GONE);
+				} else {
+					view.findViewById(R.id.imageView3).setVisibility(View.VISIBLE);
+				}
+
+				ListView parentList = (ListView) parent;
+				if (parentList.getChoiceMode() == ListView.CHOICE_MODE_NONE) {
+					checkBoxV.setVisibility(View.GONE);
+				} else {
+					if (parentList.isItemChecked(position)) {
+						checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
+					} else {
+						checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
+					}
+					checkBoxV.setVisibility(View.VISIBLE);
+				}
+
+				fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
+
+				if (checkIfFileIsSharedWithMe(file)) {
+					sharedWithMeIconV.setVisibility(View.VISIBLE);
+				}
+			} else {
+				// TODO Re-enable when server supports folder-size calculation
+				// if (FileStorageUtils.getDefaultSavePathFor(mAccount.name,
+				// file) != null) {
+				// fileSizeV.setVisibility(View.VISIBLE);
+				// fileSizeV
+				// .setText(getFolderSizeHuman(FileStorageUtils.getDefaultSavePathFor(mAccount.name,
+				// file)));
+				// } else {
+				fileSizeV.setVisibility(View.INVISIBLE);
+				// }
+
+				lastModV.setVisibility(View.VISIBLE);
+				lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
+				checkBoxV.setVisibility(View.GONE);
+				view.findViewById(R.id.imageView3).setVisibility(View.GONE);
+
+				if (checkIfFileIsSharedWithMe(file)) {
+					fileIcon.setImageResource(R.drawable.shared_with_me_folder);
+					sharedWithMeIconV.setVisibility(View.VISIBLE);
+				} else {
+					fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
+				}
+
+				// If folder is sharedByLink, icon folder must be changed to
+				// folder-public one
+				if (file.isShareByLink()) {
+					fileIcon.setImageResource(R.drawable.folder_public);
+				}
+			}
+
+			if (file.isShareByLink()) {
+				sharedIconV.setVisibility(View.VISIBLE);
+			} else {
+				sharedIconV.setVisibility(View.GONE);
+			}
+		}
+
+		return view;
+	}
+
+	/**
+	 * Local Folder size in human readable format
+	 * 
+	 * @param path
+	 *            String
+	 * @return Size in human readable format
+	 */
+	private String getFolderSizeHuman(String path) {
+
+		File dir = new File(path);
+
+		if (dir.exists()) {
+			long bytes = getFolderSize(dir);
+			return DisplayUtils.bytesToHumanReadable(bytes);
+		}
+
+		return "0 B";
+	}
+
+	/**
+	 * Local Folder size
+	 * 
+	 * @param dir
+	 *            File
+	 * @return Size in bytes
+	 */
+	private long getFolderSize(File dir) {
+		if (dir.exists()) {
+			long result = 0;
+			File[] fileList = dir.listFiles();
+			for (int i = 0; i < fileList.length; i++) {
+				if (fileList[i].isDirectory()) {
+					result += getFolderSize(fileList[i]);
+				} else {
+					result += fileList[i].length();
+				}
+			}
+			return result;
+		}
+		return 0;
+	}
+
+	@Override
+	public int getViewTypeCount() {
+		return 1;
+	}
+
+	@Override
+	public boolean hasStableIds() {
+		return true;
+	}
+
+	@Override
+	public boolean isEmpty() {
+		return (mFiles == null || mFiles.isEmpty());
+	}
+
+	/**
+	 * Change the adapted directory for a new one
+	 * 
+	 * @param directory
+	 *            New file to adapt. Can be NULL, meaning "no content to adapt".
+	 * @param updatedStorageManager
+	 *            Optional updated storage manager; used to replace
+	 *            mStorageManager if is different (and not NULL)
+	 */
+	public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager) {
+		mFile = directory;
+		if (updatedStorageManager != null && updatedStorageManager != mStorageManager) {
+			mStorageManager = updatedStorageManager;
+			mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
+		}
+		if (mStorageManager != null) {
+			mFiles = mStorageManager.getFolderContent(mFile);
+			if (mJustFolders) {
+				mFiles = getFolders(mFiles);
+			}
+		} else {
+			mFiles = null;
+		}
+
+		sortDirectory();
+	}
+
+	/**
+	 * Sorts all filenames, regarding last user decision
+	 */
+	private void sortDirectory() {
+		switch (mSortOrder) {
+		case 0:
+			sortByName(mSortAscending);
+			break;
+		case 1:
+			sortByDate(mSortAscending);
+			break;
+		case 2:
+			sortBySize(mSortAscending);
+			break;
+		}
+
+		notifyDataSetChanged();
+	}
+
+	/**
+	 * Filter for getting only the folders
+	 * 
+	 * @param files
+	 * @return Vector<OCFile>
+	 */
+	public Vector<OCFile> getFolders(Vector<OCFile> files) {
+		Vector<OCFile> ret = new Vector<OCFile>();
+		OCFile current = null;
+		for (int i = 0; i < files.size(); i++) {
+			current = files.get(i);
+			if (current.isFolder()) {
+				ret.add(current);
+			}
+		}
+		return ret;
+	}
+
+	/**
+	 * Check if parent folder does not include 'S' permission and if file/folder
+	 * is shared with me
+	 * 
+	 * @param file
+	 *            : OCFile
+	 * @return boolean: True if it is shared with me and false if it is not
+	 */
+	private boolean checkIfFileIsSharedWithMe(OCFile file) {
+		return (mFile.getPermissions() != null && !mFile.getPermissions().contains(PERMISSION_SHARED_WITH_ME)
+				&& file.getPermissions() != null && file.getPermissions().contains(PERMISSION_SHARED_WITH_ME));
+	}
+
+	/**
+	 * Sorts list by Date
+	 * 
+	 * @param sortAscending
+	 *            true: ascending, false: descending
+	 */
+	private void sortByDate(boolean sortAscending) {
+		final Integer val;
+		if (sortAscending) {
+			val = 1;
+		} else {
+			val = -1;
+		}
+
+		Collections.sort(mFiles, new Comparator<OCFile>() {
+			@Override
+			public int compare(OCFile o1, OCFile o2) {
+				if (o1.isFolder() && o2.isFolder()) {
+					return val * Long.compare(o1.getModificationTimestamp(), o2.getModificationTimestamp());
+				} else if (o1.isFolder()) {
+					return -1;
+				} else if (o2.isFolder()) {
+					return 1;
+				} else if (o1.getModificationTimestamp() == 0 || o2.getModificationTimestamp() == 0) {
+					return 0;
+				} else {
+					return val * Long.compare(o1.getModificationTimestamp(), o2.getModificationTimestamp());
+				}
+			}
+		});
+	}
+
+	/**
+	 * Sorts list by Size
+	 * 
+	 * @param sortAscending
+	 *            true: ascending, false: descending
+	 */
+	private void sortBySize(boolean sortAscending) {
+		final Integer val;
+		if (sortAscending) {
+			val = 1;
+		} else {
+			val = -1;
+		}
+
+		Collections.sort(mFiles, new Comparator<OCFile>() {
+			@Override
+			public int compare(OCFile o1, OCFile o2) {
+				if (o1.isFolder() && o2.isFolder()) {
+					return val
+							* Long.compare(
+									getFolderSize(new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, o1))),
+									getFolderSize(new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, o2))));
+				} else if (o1.isFolder()) {
+					return -1;
+				} else if (o2.isFolder()) {
+					return 1;
+				} else if (o1.getFileLength() == 0 || o2.getFileLength() == 0) {
+					return 0;
+				} else {
+					return val * Long.compare(o1.getFileLength(), o2.getFileLength());
+				}
+			}
+		});
+	}
+
+	/**
+	 * Sorts list by Name
+	 * 
+	 * @param sortAscending
+	 *            true: ascending, false: descending
+	 */
+	private void sortByName(boolean sortAscending) {
+		final Integer val;
+		if (sortAscending) {
+			val = 1;
+		} else {
+			val = -1;
+		}
+
+		Collections.sort(mFiles, new Comparator<OCFile>() {
+			@Override
+			public int compare(OCFile o1, OCFile o2) {
+				if (o1.isFolder() && o2.isFolder()) {
+					return val * o1.getRemotePath().toLowerCase().compareTo(o2.getRemotePath().toLowerCase());
+				} else if (o1.isFolder()) {
+					return -1;
+				} else if (o2.isFolder()) {
+					return 1;
+				}
+				return val * new AlphanumComparator().compare(o1, o2);
+			}
+		});
+	}
+
+	public void setSortOrder(Integer order, boolean ascending) {
+		SharedPreferences.Editor editor = mAppPreferences.edit();
+		editor.putInt("sortOrder", order);
+		editor.putBoolean("sortAscending", ascending);
+		editor.commit();
+
+		mSortOrder = order;
+		mSortAscending = ascending;
+
+		sortDirectory();
+	}
 }

+ 336 - 343
src/com/owncloud/android/ui/fragment/OCFileListFragment.java

@@ -54,347 +54,340 @@ import com.owncloud.android.utils.Log_OC;
  * @author David A. Velasco
  */
 public class OCFileListFragment extends ExtendedListFragment {
-    
-    private static final String TAG = OCFileListFragment.class.getSimpleName();
-
-    private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ?
-            OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
-            
-    public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
-    public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
-            
-    private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
-
-    private FileFragment.ContainerActivity mContainerActivity;
-   
-    private OCFile mFile = null;
-    private FileListListAdapter mAdapter;
-    
-    private OCFile mTargetFile;
-
-    
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    public void onAttach(Activity activity) {
-        super.onAttach(activity);
-        Log_OC.e(TAG, "onAttach");
-        try {
-            mContainerActivity = (FileFragment.ContainerActivity) activity;
-            
-        } catch (ClassCastException e) {
-            throw new ClassCastException(activity.toString() + " must implement " + 
-                    FileFragment.ContainerActivity.class.getSimpleName());
-        }
-        try {
-            setOnRefreshListener((SwipeRefreshLayout.OnRefreshListener) activity);
-            
-        } catch (ClassCastException e) {
-            throw new ClassCastException(activity.toString() + " must implement " + 
-                    SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
-        }
-    }
-
-    
-    @Override
-    public void onDetach() {
-        setOnRefreshListener(null);
-        mContainerActivity = null;
-        super.onDetach();
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    public void onActivityCreated(Bundle savedInstanceState) {
-        super.onActivityCreated(savedInstanceState);
-        Log_OC.e(TAG, "onActivityCreated() start");
-        
-        if (savedInstanceState != null) {
-            mFile = savedInstanceState.getParcelable(KEY_FILE);
-        }
-        
-        Bundle args = getArguments();
-        boolean justFolders = (args == null) ? false : args.getBoolean(ARG_JUST_FOLDERS, false); 
-        mAdapter = new FileListListAdapter(
-                justFolders,
-                getSherlockActivity(), 
-                mContainerActivity
-        );
-        setListAdapter(mAdapter);
-        
-        registerForContextMenu(getListView());
-        getListView().setOnCreateContextMenuListener(this);
-  }
-    
-    /**
-     * Saves the current listed folder.
-     */
-    @Override
-    public void onSaveInstanceState (Bundle outState) {
-        super.onSaveInstanceState(outState);
-        outState.putParcelable(KEY_FILE, mFile);
-    }
-    
-    /**
-     * Call this, when the user presses the up button.
-     * 
-     * Tries to move up the current folder one level. If the parent folder was removed from the 
-     * database, it continues browsing up until finding an existing folders.
-     * 
-     * return       Count of folder levels browsed up.
-     */
-    public int onBrowseUp() {
-        OCFile parentDir = null;
-        int moveCount = 0;
-        
-        if(mFile != null){
-            FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
-            
-            String parentPath = null;
-            if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
-                parentPath = new File(mFile.getRemotePath()).getParent();
-                parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : 
-                	parentPath + OCFile.PATH_SEPARATOR;
-                parentDir = storageManager.getFileByPath(parentPath);
-                moveCount++;
-            } else {
-                parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
-            }
-            while (parentDir == null) {
-                parentPath = new File(parentPath).getParent();
-                parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : 
-                	parentPath + OCFile.PATH_SEPARATOR;
-                parentDir = storageManager.getFileByPath(parentPath);
-                moveCount++;
-            }   // exit is granted because storageManager.getFileByPath("/") never returns null
-            mFile = parentDir;
-            
-            listDirectory(mFile);
-
-            onRefresh();
-            
-            // restore index and top position
-            restoreIndexAndTopPosition();
-            
-        }   // else - should never happen now
-   
-        return moveCount;
-    }
-    
-    @Override
-    public void onItemClick(AdapterView<?> l, View v, int position, long id) {
-        OCFile file = (OCFile) mAdapter.getItem(position);
-        if (file != null) {
-            if (file.isFolder()) { 
-                // update state and view of this fragment
-                listDirectory(file);
-                // then, notify parent activity to let it update its state and view
-                mContainerActivity.onBrowsedDownTo(file);
-                // save index and top position
-                saveIndexAndTopPosition(position);
-                
-            } else { /// Click on a file
-                if (PreviewImageFragment.canBePreviewed(file)) {
-                    // preview image - it handles the download, if needed
-                    ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
-                    
-                } else if (file.isDown()) {
-                    if (PreviewMediaFragment.canBePreviewed(file)) {
-                        // media preview
-                        ((FileDisplayActivity)mContainerActivity).startMediaPreview(file, 0, true);
-                    } else {
-                        mContainerActivity.getFileOperationsHelper().openFile(file);
-                    }
-                    
-                } else {
-                    // automatic download, preview on finish
-                    ((FileDisplayActivity)mContainerActivity).startDownloadForPreview(file);
-                }
-                    
-            }
-            
-        } else {
-            Log_OC.d(TAG, "Null object in ListAdapter!!");
-        }
-        
-    }
-    
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    public void onCreateContextMenu (
-            ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
-        super.onCreateContextMenu(menu, v, menuInfo);
-        Bundle args = getArguments();
-        boolean allowContextualActions = 
-                (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true); 
-        if (allowContextualActions) {
-            MenuInflater inflater = getSherlockActivity().getMenuInflater();
-            inflater.inflate(R.menu.file_actions_menu, menu);
-            AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
-            OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
-            
-            if (mContainerActivity.getStorageManager() != null) {
-                FileMenuFilter mf = new FileMenuFilter(
-                    targetFile,
-                    mContainerActivity.getStorageManager().getAccount(),
-                    mContainerActivity,
-                    getSherlockActivity()
-                );
-                mf.filter(menu);
-            }
-            
-            /// additional restrictions for this fragment 
-            // TODO allow in the future 'open with' for previewable files
-            MenuItem item = menu.findItem(R.id.action_open_file_with);
-            if (item != null) {
-                item.setVisible(false);
-                item.setEnabled(false);
-            }
-            /// TODO break this direct dependency on FileDisplayActivity... if possible
-            FileFragment frag = ((FileDisplayActivity)getSherlockActivity()).getSecondFragment();
-            if (frag != null && frag instanceof FileDetailFragment && 
-                    frag.getFile().getFileId() == targetFile.getFileId()) {
-                item = menu.findItem(R.id.action_see_details);
-                if (item != null) {
-                    item.setVisible(false);
-                    item.setEnabled(false);
-                }
-            }
-        }
-    }
-    
-    
-    /**
-     * {@inhericDoc}
-     */
-    @Override
-    public boolean onContextItemSelected (MenuItem item) {
-        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();        
-        mTargetFile = (OCFile) mAdapter.getItem(info.position);
-        switch (item.getItemId()) {                
-            case R.id.action_share_file: {
-                mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
-                return true;
-            }
-            case R.id.action_unshare_file: {
-                mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
-                return true;
-            }
-            case R.id.action_rename_file: {
-                RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
-                dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
-                return true;
-            }
-            case R.id.action_remove_file: {
-                RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
-                dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
-                return true;
-            }
-            case R.id.action_download_file: 
-            case R.id.action_sync_file: {
-                mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
-                return true;
-            }
-            case R.id.action_cancel_download:
-            case R.id.action_cancel_upload: {
-                ((FileDisplayActivity)mContainerActivity).cancelTransference(mTargetFile);
-                return true;
-            }
-            case R.id.action_see_details: {
-                mContainerActivity.showDetails(mTargetFile);
-                return true;
-            }
-            case R.id.action_send_file: {
-                // Obtain the file
-                if (!mTargetFile.isDown()) {  // Download the file
-                    Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
-                    ((FileDisplayActivity)mContainerActivity).startDownloadForSending(mTargetFile);
-                    
-                } else {
-                    mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
-                }
-                return true;
-            }
-            case R.id.action_move: {
-                Intent action = new Intent(getActivity(), MoveActivity.class);
-
-                // Pass mTargetFile that contains info of selected file/folder
-                action.putExtra(MoveActivity.EXTRA_TARGET_FILE, mTargetFile);
-                getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
-                return true;
-            }
-            default:
-                return super.onContextItemSelected(item); 
-        }
-    }
-
-
-    /**
-     * Use this to query the {@link OCFile} that is currently
-     * being displayed by this fragment
-     * @return The currently viewed OCFile
-     */
-    public OCFile getCurrentFile(){
-        return mFile;
-    }
-    
-    /**
-     * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
-     */
-    public void listDirectory(){
-        listDirectory(null);
-    }
-    
-    /**
-     * Lists the given directory on the view. When the input parameter is null,
-     * it will either refresh the last known directory. list the root
-     * if there never was a directory.
-     * 
-     * @param directory File to be listed
-     */
-    public void listDirectory(OCFile directory) {
-        FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
-        if (storageManager != null) {
-
-            // Check input parameters for null
-            if(directory == null){
-                if(mFile != null){
-                    directory = mFile;
-                } else {
-                    directory = storageManager.getFileByPath("/");
-                    if (directory == null) return; // no files, wait for sync
-                }
-            }
-        
-        
-            // If that's not a directory -> List its parent
-            if(!directory.isFolder()){
-                Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
-                directory = storageManager.getFileById(directory.getParentId());
-            }
-
-            mAdapter.swapDirectory(directory, storageManager);
-            if (mFile == null || !mFile.equals(directory)) {
-                mList.setSelectionFromTop(0, 0);
-            }
-            mFile = directory;
-        }
-    }
-    
-    public void sortByName(boolean descending){
-        mAdapter.setSortOrder(0, descending);
-    } 
-    
-    public void sortByDate(boolean descending){
-        mAdapter.setSortOrder(1, descending);
-    }
-
-    public void sortBySize(boolean descending){
-        mAdapter.setSortOrder(2, descending);
-    }    
+
+	private static final String TAG = OCFileListFragment.class.getSimpleName();
+
+	private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ? OCFileListFragment.class
+			.getPackage().getName() : "com.owncloud.android.ui.fragment";
+
+	public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
+	public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
+
+	private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
+
+	private FileFragment.ContainerActivity mContainerActivity;
+
+	private OCFile mFile = null;
+	private FileListListAdapter mAdapter;
+
+	private OCFile mTargetFile;
+
+	/**
+	 * {@inheritDoc}
+	 */
+	@Override
+	public void onAttach(Activity activity) {
+		super.onAttach(activity);
+		Log_OC.e(TAG, "onAttach");
+		try {
+			mContainerActivity = (FileFragment.ContainerActivity) activity;
+
+		} catch (ClassCastException e) {
+			throw new ClassCastException(activity.toString() + " must implement "
+					+ FileFragment.ContainerActivity.class.getSimpleName());
+		}
+		try {
+			setOnRefreshListener((SwipeRefreshLayout.OnRefreshListener) activity);
+
+		} catch (ClassCastException e) {
+			throw new ClassCastException(activity.toString() + " must implement "
+					+ SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
+		}
+	}
+
+	@Override
+	public void onDetach() {
+		setOnRefreshListener(null);
+		mContainerActivity = null;
+		super.onDetach();
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+	@Override
+	public void onActivityCreated(Bundle savedInstanceState) {
+		super.onActivityCreated(savedInstanceState);
+		Log_OC.e(TAG, "onActivityCreated() start");
+
+		if (savedInstanceState != null) {
+			mFile = savedInstanceState.getParcelable(KEY_FILE);
+		}
+
+		Bundle args = getArguments();
+		boolean justFolders = (args == null) ? false : args.getBoolean(ARG_JUST_FOLDERS, false);
+		mAdapter = new FileListListAdapter(justFolders, getSherlockActivity(), mContainerActivity);
+		setListAdapter(mAdapter);
+
+		registerForContextMenu(getListView());
+		getListView().setOnCreateContextMenuListener(this);
+	}
+
+	/**
+	 * Saves the current listed folder.
+	 */
+	@Override
+	public void onSaveInstanceState(Bundle outState) {
+		super.onSaveInstanceState(outState);
+		outState.putParcelable(KEY_FILE, mFile);
+	}
+
+	/**
+	 * Call this, when the user presses the up button.
+	 * 
+	 * Tries to move up the current folder one level. If the parent folder was
+	 * removed from the database, it continues browsing up until finding an
+	 * existing folders.
+	 * 
+	 * return Count of folder levels browsed up.
+	 */
+	public int onBrowseUp() {
+		OCFile parentDir = null;
+		int moveCount = 0;
+
+		if (mFile != null) {
+			FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
+
+			String parentPath = null;
+			if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
+				parentPath = new File(mFile.getRemotePath()).getParent();
+				parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath
+						+ OCFile.PATH_SEPARATOR;
+				parentDir = storageManager.getFileByPath(parentPath);
+				moveCount++;
+			} else {
+				parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
+			}
+			while (parentDir == null) {
+				parentPath = new File(parentPath).getParent();
+				parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath
+						+ OCFile.PATH_SEPARATOR;
+				parentDir = storageManager.getFileByPath(parentPath);
+				moveCount++;
+			} // exit is granted because storageManager.getFileByPath("/") never
+				// returns null
+			mFile = parentDir;
+
+			listDirectory(mFile);
+
+			onRefresh();
+
+			// restore index and top position
+			restoreIndexAndTopPosition();
+
+		} // else - should never happen now
+
+		return moveCount;
+	}
+
+	@Override
+	public void onItemClick(AdapterView<?> l, View v, int position, long id) {
+		OCFile file = (OCFile) mAdapter.getItem(position);
+		if (file != null) {
+			if (file.isFolder()) {
+				// update state and view of this fragment
+				listDirectory(file);
+				// then, notify parent activity to let it update its state and
+				// view
+				mContainerActivity.onBrowsedDownTo(file);
+				// save index and top position
+				saveIndexAndTopPosition(position);
+
+			} else { // / Click on a file
+				if (PreviewImageFragment.canBePreviewed(file)) {
+					// preview image - it handles the download, if needed
+					((FileDisplayActivity) mContainerActivity).startImagePreview(file);
+
+				} else if (file.isDown()) {
+					if (PreviewMediaFragment.canBePreviewed(file)) {
+						// media preview
+						((FileDisplayActivity) mContainerActivity).startMediaPreview(file, 0, true);
+					} else {
+						mContainerActivity.getFileOperationsHelper().openFile(file);
+					}
+
+				} else {
+					// automatic download, preview on finish
+					((FileDisplayActivity) mContainerActivity).startDownloadForPreview(file);
+				}
+
+			}
+
+		} else {
+			Log_OC.d(TAG, "Null object in ListAdapter!!");
+		}
+
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+	@Override
+	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
+		super.onCreateContextMenu(menu, v, menuInfo);
+		Bundle args = getArguments();
+		boolean allowContextualActions = (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
+		if (allowContextualActions) {
+			MenuInflater inflater = getSherlockActivity().getMenuInflater();
+			inflater.inflate(R.menu.file_actions_menu, menu);
+			AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
+			OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
+
+			if (mContainerActivity.getStorageManager() != null) {
+				FileMenuFilter mf = new FileMenuFilter(targetFile, mContainerActivity.getStorageManager()
+						.getAccount(), mContainerActivity, getSherlockActivity());
+				mf.filter(menu);
+			}
+
+			// / additional restrictions for this fragment
+			// TODO allow in the future 'open with' for previewable files
+			MenuItem item = menu.findItem(R.id.action_open_file_with);
+			if (item != null) {
+				item.setVisible(false);
+				item.setEnabled(false);
+			}
+			// / TODO break this direct dependency on FileDisplayActivity... if
+			// possible
+			FileFragment frag = ((FileDisplayActivity) getSherlockActivity()).getSecondFragment();
+			if (frag != null && frag instanceof FileDetailFragment
+					&& frag.getFile().getFileId() == targetFile.getFileId()) {
+				item = menu.findItem(R.id.action_see_details);
+				if (item != null) {
+					item.setVisible(false);
+					item.setEnabled(false);
+				}
+			}
+		}
+	}
+
+	/**
+	 * {@inhericDoc}
+	 */
+	@Override
+	public boolean onContextItemSelected(MenuItem item) {
+		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
+		mTargetFile = (OCFile) mAdapter.getItem(info.position);
+		switch (item.getItemId()) {
+		case R.id.action_share_file: {
+			mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
+			return true;
+		}
+		case R.id.action_unshare_file: {
+			mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
+			return true;
+		}
+		case R.id.action_rename_file: {
+			RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
+			dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
+			return true;
+		}
+		case R.id.action_remove_file: {
+			RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
+			dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
+			return true;
+		}
+		case R.id.action_download_file:
+		case R.id.action_sync_file: {
+			mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
+			return true;
+		}
+		case R.id.action_cancel_download:
+		case R.id.action_cancel_upload: {
+			((FileDisplayActivity) mContainerActivity).cancelTransference(mTargetFile);
+			return true;
+		}
+		case R.id.action_see_details: {
+			mContainerActivity.showDetails(mTargetFile);
+			return true;
+		}
+		case R.id.action_send_file: {
+			// Obtain the file
+			if (!mTargetFile.isDown()) { // Download the file
+				Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
+				((FileDisplayActivity) mContainerActivity).startDownloadForSending(mTargetFile);
+
+			} else {
+				mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
+			}
+			return true;
+		}
+		case R.id.action_move: {
+			Intent action = new Intent(getActivity(), MoveActivity.class);
+
+			// Pass mTargetFile that contains info of selected file/folder
+			action.putExtra(MoveActivity.EXTRA_TARGET_FILE, mTargetFile);
+			getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
+			return true;
+		}
+		default:
+			return super.onContextItemSelected(item);
+		}
+	}
+
+	/**
+	 * Use this to query the {@link OCFile} that is currently being displayed by
+	 * this fragment
+	 * 
+	 * @return The currently viewed OCFile
+	 */
+	public OCFile getCurrentFile() {
+		return mFile;
+	}
+
+	/**
+	 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null
+	 * parameter
+	 */
+	public void listDirectory() {
+		listDirectory(null);
+	}
+
+	/**
+	 * Lists the given directory on the view. When the input parameter is null,
+	 * it will either refresh the last known directory. list the root if there
+	 * never was a directory.
+	 * 
+	 * @param directory
+	 *            File to be listed
+	 */
+	public void listDirectory(OCFile directory) {
+		FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
+		if (storageManager != null) {
+
+			// Check input parameters for null
+			if (directory == null) {
+				if (mFile != null) {
+					directory = mFile;
+				} else {
+					directory = storageManager.getFileByPath("/");
+					if (directory == null)
+						return; // no files, wait for sync
+				}
+			}
+
+			// If that's not a directory -> List its parent
+			if (!directory.isFolder()) {
+				Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
+				directory = storageManager.getFileById(directory.getParentId());
+			}
+
+			mAdapter.swapDirectory(directory, storageManager);
+			if (mFile == null || !mFile.equals(directory)) {
+				mList.setSelectionFromTop(0, 0);
+			}
+			mFile = directory;
+		}
+	}
+
+	public void sortByName(boolean descending) {
+		mAdapter.setSortOrder(FileListListAdapter.mSortName, descending);
+	}
+
+	public void sortByDate(boolean descending) {
+		mAdapter.setSortOrder(FileListListAdapter.mSortDate, descending);
+	}
+
+	public void sortBySize(boolean descending) {
+		mAdapter.setSortOrder(FileListListAdapter.mSortSize, descending);
+	}
 }

+ 3 - 1
src/com/owncloud/android/datamodel/AlphanumComparator.java → src/third_parties/daveKoeller/AlphanumComparator.java

@@ -22,9 +22,11 @@
  *
  */
 
-package com.owncloud.android.datamodel;
+package third_parties.daveKoeller;
 import java.util.Comparator;
 
+import com.owncloud.android.datamodel.OCFile;
+
 /**
  * This is an updated version with enhancements made by Daniel Migowski,
  * Andre Bogus, and David Koelle