Browse Source

Force spaces in eclipse via project specifc settings
Reformat all code: Use spaces over tabs

Lennart Rosam 13 years ago
parent
commit
435b31ba4f
56 changed files with 5801 additions and 5264 deletions
  1. 281 0
      .settings/org.eclipse.jdt.core.prefs
  2. 3 0
      .settings/org.eclipse.jdt.ui.prefs
  3. 63 55
      src/eu/alefzero/owncloud/AccountUtils.java
  4. 48 46
      src/eu/alefzero/owncloud/DisplayUtils.java
  5. 99 87
      src/eu/alefzero/owncloud/FileDownloader.java
  6. 31 30
      src/eu/alefzero/owncloud/OwnCloudSession.java
  7. 467 393
      src/eu/alefzero/owncloud/Uploader.java
  8. 225 222
      src/eu/alefzero/owncloud/authenticator/AccountAuthenticator.java
  9. 13 13
      src/eu/alefzero/owncloud/authenticator/AccountAuthenticatorService.java
  10. 46 45
      src/eu/alefzero/owncloud/authenticator/AuthenticationRunnable.java
  11. 114 113
      src/eu/alefzero/owncloud/authenticator/ConnectionCheckerRunnable.java
  12. 85 92
      src/eu/alefzero/owncloud/authenticator/EasySSLSocketFactory.java
  13. 24 29
      src/eu/alefzero/owncloud/authenticator/EasyX509TrustManager.java
  14. 2 2
      src/eu/alefzero/owncloud/authenticator/OnAuthenticationResultListener.java
  15. 7 16
      src/eu/alefzero/owncloud/authenticator/OnConnectCheckListener.java
  16. 11 11
      src/eu/alefzero/owncloud/datamodel/DataStorageManager.java
  17. 243 227
      src/eu/alefzero/owncloud/datamodel/FileDataStorageManager.java
  18. 296 293
      src/eu/alefzero/owncloud/datamodel/OCFile.java
  19. 63 59
      src/eu/alefzero/owncloud/db/DbHandler.java
  20. 33 32
      src/eu/alefzero/owncloud/db/ProviderMeta.java
  21. 8 8
      src/eu/alefzero/owncloud/extensions/ExtensionsAvailableActivity.java
  22. 31 29
      src/eu/alefzero/owncloud/extensions/ExtensionsAvailableDialog.java
  23. 101 84
      src/eu/alefzero/owncloud/extensions/ExtensionsListActivity.java
  24. 127 113
      src/eu/alefzero/owncloud/files/services/FileUploader.java
  25. 4 4
      src/eu/alefzero/owncloud/files/services/OnUploadCompletedListener.java
  26. 56 51
      src/eu/alefzero/owncloud/location/LocationServiceLauncherReciever.java
  27. 73 67
      src/eu/alefzero/owncloud/location/LocationUpdateService.java
  28. 165 157
      src/eu/alefzero/owncloud/providers/FileContentProvider.java
  29. 119 115
      src/eu/alefzero/owncloud/syncadapter/AbstractOwnCloudSyncAdapter.java
  30. 72 64
      src/eu/alefzero/owncloud/syncadapter/ContactSyncAdapter.java
  31. 17 16
      src/eu/alefzero/owncloud/syncadapter/ContactSyncService.java
  32. 87 87
      src/eu/alefzero/owncloud/syncadapter/FileSyncAdapter.java
  33. 26 25
      src/eu/alefzero/owncloud/syncadapter/FileSyncService.java
  34. 36 34
      src/eu/alefzero/owncloud/ui/ActionItem.java
  35. 112 106
      src/eu/alefzero/owncloud/ui/CustomPopup.java
  36. 37 38
      src/eu/alefzero/owncloud/ui/FragmentListView.java
  37. 263 233
      src/eu/alefzero/owncloud/ui/QuickAction.java
  38. 133 127
      src/eu/alefzero/owncloud/ui/activity/AccountSelectActivity.java
  39. 317 302
      src/eu/alefzero/owncloud/ui/activity/AuthenticatorActivity.java
  40. 19 19
      src/eu/alefzero/owncloud/ui/activity/FileDetailActivity.java
  41. 357 351
      src/eu/alefzero/owncloud/ui/activity/FileDisplayActivity.java
  42. 114 111
      src/eu/alefzero/owncloud/ui/activity/LandingActivity.java
  43. 190 188
      src/eu/alefzero/owncloud/ui/activity/Preferences.java
  44. 85 116
      src/eu/alefzero/owncloud/ui/activity/PreferencesNewSession.java
  45. 122 114
      src/eu/alefzero/owncloud/ui/adapter/FileListActionListAdapter.java
  46. 114 109
      src/eu/alefzero/owncloud/ui/adapter/FileListListAdapter.java
  47. 64 64
      src/eu/alefzero/owncloud/ui/adapter/LandingScreenAdapter.java
  48. 175 175
      src/eu/alefzero/owncloud/ui/fragment/FileDetailFragment.java
  49. 157 154
      src/eu/alefzero/owncloud/ui/fragment/FileListFragment.java
  50. 19 19
      src/eu/alefzero/owncloud/ui/fragment/LandingPageFragment.java
  51. 59 56
      src/eu/alefzero/owncloud/utils/OwnCloudVersion.java
  52. 107 97
      src/eu/alefzero/owncloud/widgets/ActionEditText.java
  53. 34 33
      src/eu/alefzero/webdav/FileRequestEntity.java
  54. 124 118
      src/eu/alefzero/webdav/WebdavClient.java
  55. 93 87
      src/eu/alefzero/webdav/WebdavEntry.java
  56. 30 28
      src/eu/alefzero/webdav/WebdavUtils.java

+ 281 - 0
.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,281 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_assignment=0
+org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
+org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
+org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
+org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
+org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0
+org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80
+org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16
+org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_after_package=1
+org.eclipse.jdt.core.formatter.blank_lines_before_field=0
+org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
+org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
+org.eclipse.jdt.core.formatter.blank_lines_before_method=1
+org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
+org.eclipse.jdt.core.formatter.blank_lines_before_package=0
+org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1
+org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1
+org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
+org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
+org.eclipse.jdt.core.formatter.comment.format_block_comments=true
+org.eclipse.jdt.core.formatter.comment.format_header=false
+org.eclipse.jdt.core.formatter.comment.format_html=true
+org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true
+org.eclipse.jdt.core.formatter.comment.format_line_comments=true
+org.eclipse.jdt.core.formatter.comment.format_source_code=true
+org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true
+org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
+org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
+org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert
+org.eclipse.jdt.core.formatter.comment.line_length=80
+org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true
+org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true
+org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false
+org.eclipse.jdt.core.formatter.compact_else_if=true
+org.eclipse.jdt.core.formatter.continuation_indentation=2
+org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
+org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off
+org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on
+org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false
+org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
+org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_empty_lines=false
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false
+org.eclipse.jdt.core.formatter.indentation.size=4
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert
+org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
+org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.join_lines_in_comments=true
+org.eclipse.jdt.core.formatter.join_wrapped_lines=true
+org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.lineSplit=80
+org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false
+org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
+org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
+org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
+org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
+org.eclipse.jdt.core.formatter.tabulation.char=space
+org.eclipse.jdt.core.formatter.tabulation.size=4
+org.eclipse.jdt.core.formatter.use_on_off_tags=false
+org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true
+org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
+org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true
+org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true

+ 3 - 0
.settings/org.eclipse.jdt.ui.prefs

@@ -0,0 +1,3 @@
+eclipse.preferences.version=1
+formatter_profile=_eclipse [spaces-only]
+formatter_settings_version=12

+ 63 - 55
src/eu/alefzero/owncloud/AccountUtils.java

@@ -28,61 +28,69 @@ import android.content.SharedPreferences;
 import android.preference.PreferenceManager;
 
 public class AccountUtils {
-  public static final String WEBDAV_PATH_1_2 = "/webdav/owncloud.php";
-  public static final String WEBDAV_PATH_2_0 = "/files/webdav.php";
-  public static final String WEBDAV_PATH_4_0 = "/remote/webdav.php";
-  public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php";
-  public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php";
-  public static final String STATUS_PATH = "/status.php";
+    public static final String WEBDAV_PATH_1_2 = "/webdav/owncloud.php";
+    public static final String WEBDAV_PATH_2_0 = "/files/webdav.php";
+    public static final String WEBDAV_PATH_4_0 = "/remote/webdav.php";
+    public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php";
+    public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php";
+    public static final String STATUS_PATH = "/status.php";
 
-  /**
-   * Can be used to get the currently selected ownCloud account in the preferences
-   * 
-   * @param context The current appContext
-   * @return The current account or first available, if none is available, then null.
-   */
-  public static Account getCurrentOwnCloudAccount(Context context) {
-	  Account[] ocAccounts = AccountManager.get(context).getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
-	  Account defaultAccount = null;
-	  
-	  SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(context);
-	  String accountName = appPreferences.getString("select_oc_account", null);
-	  
-	  if(accountName != null){
-		  for(Account account : ocAccounts){
-			  if(account.name.equals(accountName)){
-				  defaultAccount = account;
-				  break;
-			  }
-		  }
-	  } else if (ocAccounts.length != 0) {
-	    // we at least need to take first account as fallback
-	    defaultAccount = ocAccounts[0];
-	  }
-	  
-	return defaultAccount;
-  }
-  
-  public static void setCurrentOwnCloudAccount(Context context, String name) {
-    SharedPreferences.Editor appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
-    appPrefs.putString("select_oc_account", name);
-    appPrefs.commit();
-  }
-  
-  /**
-   * 
-   * @param version version of owncloud
-   * @return webdav path for given OC version, null if OC version unknown
-   */
-  public static String getWebdavPath(OwnCloudVersion version) {
-    if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)
-      return WEBDAV_PATH_4_0;
-    if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0 ||
-        version.compareTo(OwnCloudVersion.owncloud_v2) >= 0)
-      return WEBDAV_PATH_2_0;
-    if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0)
-      return WEBDAV_PATH_1_2;
-    return null;
-  }
+    /**
+     * Can be used to get the currently selected ownCloud account in the
+     * preferences
+     * 
+     * @param context
+     *            The current appContext
+     * @return The current account or first available, if none is available,
+     *         then null.
+     */
+    public static Account getCurrentOwnCloudAccount(Context context) {
+        Account[] ocAccounts = AccountManager.get(context).getAccountsByType(
+                AccountAuthenticator.ACCOUNT_TYPE);
+        Account defaultAccount = null;
+
+        SharedPreferences appPreferences = PreferenceManager
+                .getDefaultSharedPreferences(context);
+        String accountName = appPreferences
+                .getString("select_oc_account", null);
+
+        if (accountName != null) {
+            for (Account account : ocAccounts) {
+                if (account.name.equals(accountName)) {
+                    defaultAccount = account;
+                    break;
+                }
+            }
+        } else if (ocAccounts.length != 0) {
+            // we at least need to take first account as fallback
+            defaultAccount = ocAccounts[0];
+        }
+
+        return defaultAccount;
+    }
+
+    public static void setCurrentOwnCloudAccount(Context context, String name) {
+        SharedPreferences.Editor appPrefs = PreferenceManager
+                .getDefaultSharedPreferences(context).edit();
+        appPrefs.putString("select_oc_account", name);
+        appPrefs.commit();
+    }
+
+    /**
+     * 
+     * @param version
+     *            version of owncloud
+     * @return webdav path for given OC version, null if OC version unknown
+     */
+    public static String getWebdavPath(OwnCloudVersion version) {
+        if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)
+            return WEBDAV_PATH_4_0;
+        if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0
+                || version.compareTo(OwnCloudVersion.owncloud_v2) >= 0)
+            return WEBDAV_PATH_2_0;
+        if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0)
+            return WEBDAV_PATH_1_2;
+        return null;
+    }
 
 }

+ 48 - 46
src/eu/alefzero/owncloud/DisplayUtils.java

@@ -22,57 +22,59 @@ import java.util.HashMap;
 
 /**
  * A helper class for some string operations.
+ * 
  * @author Bartek Przybylski
- *
+ * 
  */
 public class DisplayUtils {
-  public static String bitsToHumanReadable(long bitsLen) {
-    double result = bitsLen;
-    int attachedsuff = 0;
-    while (result > 1024 && attachedsuff < suffixes.length) {
-      result /= 1024.;
-      attachedsuff++;
+    public static String bitsToHumanReadable(long bitsLen) {
+        double result = bitsLen;
+        int attachedsuff = 0;
+        while (result > 1024 && attachedsuff < suffixes.length) {
+            result /= 1024.;
+            attachedsuff++;
+        }
+        result = ((int) (result * 100)) / 100.;
+        return result + suffixes[attachedsuff];
+    }
+
+    public static String HtmlDecode(String s) {
+        String ret = "";
+        for (int i = 0; i < s.length(); ++i) {
+            if (s.charAt(i) == '%') {
+                ret += (char) Integer.parseInt(s.substring(i + 1, i + 3), 16);
+                i += 2;
+            } else {
+                ret += s.charAt(i);
+            }
+        }
+        return ret;
     }
-    result = ((int)(result * 100))/100.;
-    return result+suffixes[attachedsuff];
-  }
-  
-  public static String HtmlDecode(String s) {
-    String ret = "";
-    for (int i = 0; i < s.length(); ++i) {
-      if (s.charAt(i) == '%') {
-        ret += (char)Integer.parseInt(s.substring(i+1, i+3), 16);
-        i+=2;
-      } else {
-        ret += s.charAt(i);
-      }
+
+    public static String convertMIMEtoPrettyPrint(String mimetype) {
+        if (mimeType2HUmanReadable.containsKey(mimetype)) {
+            return mimeType2HUmanReadable.get(mimetype);
+        }
+        return mimetype.split("/")[1].toUpperCase() + " file";
     }
-    return ret;
-  }
 
-  public static String convertMIMEtoPrettyPrint(String mimetype) {
-    if (mimeType2HUmanReadable.containsKey(mimetype)) {
-      return mimeType2HUmanReadable.get(mimetype);
+    private static final String[] suffixes = { "B", "KB", "MB", "GB", "TB",
+            "PB", "EB", "ZB", "YB" };
+
+    private static HashMap<String, String> mimeType2HUmanReadable;
+    static {
+        mimeType2HUmanReadable = new HashMap<String, String>();
+        // images
+        mimeType2HUmanReadable.put("image/jpeg", "JPEG image");
+        mimeType2HUmanReadable.put("image/jpg", "JPEG image");
+        mimeType2HUmanReadable.put("image/png", "PNG image");
+        mimeType2HUmanReadable.put("image/bmp", "Bitmap image");
+        mimeType2HUmanReadable.put("image/gif", "GIF image");
+        mimeType2HUmanReadable.put("image/svg+xml", "JPEG image");
+        mimeType2HUmanReadable.put("image/tiff", "TIFF image");
+        // music
+        mimeType2HUmanReadable.put("audio/mpeg", "MP3 music file");
+        mimeType2HUmanReadable.put("application/ogg", "OGG music file");
+
     }
-    return mimetype.split("/")[1].toUpperCase() + " file";
-  }
-  
-  private static final String[] suffixes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
-  
-  private static HashMap<String, String> mimeType2HUmanReadable;
-  static {
-    mimeType2HUmanReadable = new HashMap<String, String>();
-    // images
-    mimeType2HUmanReadable.put("image/jpeg", "JPEG image");
-    mimeType2HUmanReadable.put("image/jpg", "JPEG image");
-    mimeType2HUmanReadable.put("image/png", "PNG image");
-    mimeType2HUmanReadable.put("image/bmp", "Bitmap image");
-    mimeType2HUmanReadable.put("image/gif", "GIF image");
-    mimeType2HUmanReadable.put("image/svg+xml", "JPEG image");
-    mimeType2HUmanReadable.put("image/tiff", "TIFF image");
-    // music
-    mimeType2HUmanReadable.put("audio/mpeg", "MP3 music file");
-    mimeType2HUmanReadable.put("application/ogg", "OGG music file");
-    
-  }
 }

+ 99 - 87
src/eu/alefzero/owncloud/FileDownloader.java

@@ -25,96 +25,108 @@ import eu.alefzero.owncloud.ui.activity.FileDisplayActivity;
 import eu.alefzero.webdav.WebdavClient;
 
 public class FileDownloader extends Service {
-  public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
-  public static final String EXTRA_ACCOUNT = "ACCOUNT";
-  public static final String EXTRA_FILE_PATH = "FILE_PATH";
-  private static final String TAG = "FileDownloader";
-  
-  private NotificationManager nm;
-  private Looper mServiceLooper;
-  private ServiceHandler mServiceHandler;
-  private Account mAccount;
-  private String mFilePath;
-  
-  private final class ServiceHandler extends Handler {
-    public ServiceHandler(Looper looper) {
-      super(looper);
+    public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
+    public static final String EXTRA_ACCOUNT = "ACCOUNT";
+    public static final String EXTRA_FILE_PATH = "FILE_PATH";
+    private static final String TAG = "FileDownloader";
+
+    private NotificationManager nm;
+    private Looper mServiceLooper;
+    private ServiceHandler mServiceHandler;
+    private Account mAccount;
+    private String mFilePath;
+
+    private final class ServiceHandler extends Handler {
+        public ServiceHandler(Looper looper) {
+            super(looper);
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            downloadFile();
+            stopSelf(msg.arg1);
+        }
     }
+
     @Override
-    public void handleMessage(Message msg) {
-      downloadFile();
-      stopSelf(msg.arg1);
+    public void onCreate() {
+        super.onCreate();
+        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+        HandlerThread thread = new HandlerThread("FileDownladerThread",
+                Process.THREAD_PRIORITY_BACKGROUND);
+        thread.start();
+        mServiceLooper = thread.getLooper();
+        mServiceHandler = new ServiceHandler(mServiceLooper);
     }
-  }
-  
-  @Override
-  public void onCreate() {
-    super.onCreate();
-    nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
-    HandlerThread thread = new HandlerThread("FileDownladerThread", Process.THREAD_PRIORITY_BACKGROUND);
-    thread.start();
-    mServiceLooper = thread.getLooper();
-    mServiceHandler = new ServiceHandler(mServiceLooper); 
-  }
-  
-  @Override
-  public IBinder onBind(Intent arg0) {
-    return null;
-  }
-
-  @Override
-  public int onStartCommand(Intent intent, int flags, int startId) {
-    if (!intent.hasExtra(EXTRA_ACCOUNT) && !intent.hasExtra(EXTRA_FILE_PATH)) {
-      Log.e(TAG, "Not enough information provided in intent");
-      return START_STICKY;
+
+    @Override
+    public IBinder onBind(Intent arg0) {
+        return null;
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        if (!intent.hasExtra(EXTRA_ACCOUNT)
+                && !intent.hasExtra(EXTRA_FILE_PATH)) {
+            Log.e(TAG, "Not enough information provided in intent");
+            return START_STICKY;
+        }
+        mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);
+        mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);
+        Message msg = mServiceHandler.obtainMessage();
+        msg.arg1 = startId;
+        mServiceHandler.sendMessage(msg);
+
+        return START_NOT_STICKY;
     }
-    mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);
-    mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);
-    Message msg = mServiceHandler.obtainMessage();
-    msg.arg1 = startId;
-    mServiceHandler.sendMessage(msg);
-
-    return START_NOT_STICKY;
-  }
-  
-  void downloadFile() {
-    AccountManager am = (AccountManager)getSystemService(ACCOUNT_SERVICE);
-    Uri oc_url = Uri.parse(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_URL));
-
-    WebdavClient wdc = new WebdavClient(oc_url);
-    
-    String username = mAccount.name.split("@")[0];
-    String password = "";
-    try {
-      password = am.blockingGetAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE, true);
-    } catch (Exception e) {
-      e.printStackTrace();
+
+    void downloadFile() {
+        AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
+        Uri oc_url = Uri.parse(am.getUserData(mAccount,
+                AccountAuthenticator.KEY_OC_URL));
+
+        WebdavClient wdc = new WebdavClient(oc_url);
+
+        String username = mAccount.name.split("@")[0];
+        String password = "";
+        try {
+            password = am.blockingGetAuthToken(mAccount,
+                    AccountAuthenticator.AUTH_TOKEN_TYPE, true);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        wdc.setCredentials(username, password);
+        wdc.allowUnsignedCertificates();
+
+        Notification n = new Notification(R.drawable.icon, "Downloading file",
+                System.currentTimeMillis());
+        PendingIntent pi = PendingIntent.getActivity(this, 1, new Intent(this,
+                FileDisplayActivity.class), 0);
+        n.setLatestEventInfo(this, "Downloading file", "Downloading file "
+                + mFilePath, pi);
+        nm.notify(1, n);
+
+        File sdCard = Environment.getExternalStorageDirectory();
+        File dir = new File(sdCard.getAbsolutePath() + "/owncloud");
+        dir.mkdirs();
+        File file = new File(dir, mFilePath.replace('/', '.'));
+
+        Log.e(TAG, file.getAbsolutePath() + " " + oc_url.toString());
+        wdc.downloadFile(mFilePath, file);
+        ContentValues cv = new ContentValues();
+        cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath());
+        getContentResolver().update(
+                ProviderTableMeta.CONTENT_URI,
+                cv,
+                ProviderTableMeta.FILE_NAME + "=? AND "
+                        + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
+                new String[] {
+                        mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
+                        mAccount.name });
+        nm.cancel(1);
+        Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
+        sendBroadcast(end);
     }
-    
-    wdc.setCredentials(username, password);
-    wdc.allowUnsignedCertificates();
-
-    Notification n = new Notification(R.drawable.icon, "Downloading file", System.currentTimeMillis());
-    PendingIntent pi = PendingIntent.getActivity(this, 1, new Intent(this, FileDisplayActivity.class), 0);
-    n.setLatestEventInfo(this, "Downloading file", "Downloading file " + mFilePath, pi);
-    nm.notify(1, n);
-
-    File sdCard = Environment.getExternalStorageDirectory();
-    File dir = new File (sdCard.getAbsolutePath() + "/owncloud");
-    dir.mkdirs();
-    File file = new File(dir, mFilePath.replace('/', '.'));
-    
-    Log.e(TAG, file.getAbsolutePath() + " " + oc_url.toString());
-    wdc.downloadFile(mFilePath, file);
-    ContentValues cv = new ContentValues();
-    cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath());
-    getContentResolver().update(ProviderTableMeta.CONTENT_URI,
-        cv,
-        ProviderTableMeta.FILE_NAME +"=? AND "+ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",
-        new String[]{mFilePath.substring(mFilePath.lastIndexOf('/')+1), mAccount.name});
-    nm.cancel(1);
-    Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
-    sendBroadcast(end);
-  }
-  
+
 }

+ 31 - 30
src/eu/alefzero/owncloud/OwnCloudSession.java

@@ -19,37 +19,38 @@ package eu.alefzero.owncloud;
 
 /**
  * Represents a session to an ownCloud instance
+ * 
  * @author Bartek Przybylski
- *
+ * 
  */
 public class OwnCloudSession {
-  private String mSessionName;
-  private String mSessionUrl;
-  private int mEntryId;
-  
-  public OwnCloudSession(String name, String url, int entryId) {
-    mSessionName = name;
-    mSessionUrl = url;
-    mEntryId = entryId;
-  }
-  
-  public void setName(String name) {
-    mSessionName = name;
-  }
-  
-  public String getName() {
-    return mSessionName;
-  }
-  
-  public void setUrl(String url) {
-    mSessionUrl = url;
-  }
-  
-  public String getUrl() {
-    return mSessionUrl;
-  }
-  
-  public int getEntryId() {
-    return mEntryId;
-  }
+    private String mSessionName;
+    private String mSessionUrl;
+    private int mEntryId;
+
+    public OwnCloudSession(String name, String url, int entryId) {
+        mSessionName = name;
+        mSessionUrl = url;
+        mEntryId = entryId;
+    }
+
+    public void setName(String name) {
+        mSessionName = name;
+    }
+
+    public String getName() {
+        return mSessionName;
+    }
+
+    public void setUrl(String url) {
+        mSessionUrl = url;
+    }
+
+    public String getUrl() {
+        return mSessionUrl;
+    }
+
+    public int getEntryId() {
+        return mEntryId;
+    }
 }

+ 467 - 393
src/eu/alefzero/owncloud/Uploader.java

@@ -62,424 +62,498 @@ import eu.alefzero.webdav.WebdavUtils;
 
 /**
  * This can be used to upload things to an ownCloud instance.
+ * 
  * @author Bartek Przybylski
- *
+ * 
  */
-public class Uploader extends ListActivity implements OnItemClickListener, android.view.View.OnClickListener {
-  private static final String TAG = "ownCloudUploader";
-
-  private Account mAccount;
-  private AccountManager mAccountManager;
-  private String mUsername, mPassword;
-  private Cursor mCursor;
-  private Stack<String> mParents;
-  private Thread mUploadThread;
-  private Handler mHandler;
-  private ArrayList<Parcelable> mStreamsToUpload;
-
-  private final static int DIALOG_NO_ACCOUNT = 0;
-  private final static int DIALOG_WAITING = 1;
-  private final static int DIALOG_NO_STREAM = 2;
-  private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
-  private final static int DIALOG_GET_DIRNAME = 4;
-
-  private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
-
-  @Override
-  protected void onCreate(Bundle savedInstanceState) {
-    super.onCreate(savedInstanceState);
-    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
-    mParents = new Stack<String>();
-    mHandler = new Handler();
-    if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
-      prepareStreamsToUpload();
-      mAccountManager = (AccountManager)getSystemService(Context.ACCOUNT_SERVICE);
-      Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
-      if (accounts.length == 0) {
-        Log.i(TAG, "No ownCloud account is available");
-        showDialog(DIALOG_NO_ACCOUNT);
-      } else if (accounts.length > 1) {
-        Log.i(TAG, "More then one ownCloud is available");
-        showDialog(DIALOG_MULTIPLE_ACCOUNT);
-      } else {
-        mAccount = accounts[0];
-        setContentView(R.layout.uploader_layout);
-        populateDirectoryList();
-      }
-    } else {
-      showDialog(DIALOG_NO_STREAM);
-    }
-  }
-
-  @Override
-  protected Dialog onCreateDialog(final int id) {
-    final AlertDialog.Builder builder = new Builder(this);
-    switch (id) {
-      case DIALOG_WAITING:
-        ProgressDialog pDialog = new ProgressDialog(this);
-        pDialog.setIndeterminate(false);
-        pDialog.setCancelable(false);
-        pDialog.setMessage(getResources().getString(R.string.uploader_info_uploading));
-        return pDialog;
-      case DIALOG_NO_ACCOUNT:
-        builder.setIcon(android.R.drawable.ic_dialog_alert);
-        builder.setTitle(R.string.uploader_wrn_no_account_title);
-        builder.setMessage(R.string.uploader_wrn_no_account_text);
-        builder.setCancelable(false);
-        builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
-          public void onClick(DialogInterface dialog, int which) {
-            if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
-              // using string value since in API7 this constatn is not defined
-              // in API7 < this constatant is defined in Settings.ADD_ACCOUNT_SETTINGS
-              // and Settings.EXTRA_AUTHORITIES
-              Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
-              intent.putExtra("authorities", new String[] {AccountAuthenticator.AUTH_TOKEN_TYPE});
-              startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
+public class Uploader extends ListActivity implements OnItemClickListener,
+        android.view.View.OnClickListener {
+    private static final String TAG = "ownCloudUploader";
+
+    private Account mAccount;
+    private AccountManager mAccountManager;
+    private String mUsername, mPassword;
+    private Cursor mCursor;
+    private Stack<String> mParents;
+    private Thread mUploadThread;
+    private Handler mHandler;
+    private ArrayList<Parcelable> mStreamsToUpload;
+
+    private final static int DIALOG_NO_ACCOUNT = 0;
+    private final static int DIALOG_WAITING = 1;
+    private final static int DIALOG_NO_STREAM = 2;
+    private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
+    private final static int DIALOG_GET_DIRNAME = 4;
+
+    private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
+        mParents = new Stack<String>();
+        mHandler = new Handler();
+        if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
+            prepareStreamsToUpload();
+            mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
+            Account[] accounts = mAccountManager
+                    .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+            if (accounts.length == 0) {
+                Log.i(TAG, "No ownCloud account is available");
+                showDialog(DIALOG_NO_ACCOUNT);
+            } else if (accounts.length > 1) {
+                Log.i(TAG, "More then one ownCloud is available");
+                showDialog(DIALOG_MULTIPLE_ACCOUNT);
             } else {
-              // since in API7 there is no direct call for account setup, so we need to
-              // show our own AccountSetupAcricity, get desired results and setup
-              // everything for ourself
-              Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);
-              startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
+                mAccount = accounts[0];
+                setContentView(R.layout.uploader_layout);
+                populateDirectoryList();
             }
-          }
-        });
-        builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
-          public void onClick(DialogInterface dialog, int which) {
-            finish();
-          }
-        });
-        return builder.create();
-      case DIALOG_GET_DIRNAME:
-        final EditText dirName = new EditText(getBaseContext());
-        builder.setView(dirName);
-        builder.setTitle(R.string.uploader_info_dirname);
-        String pathToUpload;
-        if (mParents.empty()) {
-          pathToUpload = "/";
         } else {
-          mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()), 
-                                 null,
-                                 null,
-                                 null,
-                                 null);
-          mCursor.moveToFirst();
-          pathToUpload = mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_PATH)) +
-                         mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_NAME)).replace(" ", "%20");
+            showDialog(DIALOG_NO_STREAM);
         }
-        a a = new a(pathToUpload, dirName);
-        builder.setPositiveButton(R.string.common_ok, a);
-        builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
-          public void onClick(DialogInterface dialog, int which) {
-            dialog.cancel();
-          }
-        });
-        return builder.create();
-      case DIALOG_MULTIPLE_ACCOUNT:
-        CharSequence ac[] = new CharSequence[mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE).length];
-        for (int i = 0;  i < ac.length; ++i) {
-          ac[i] = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[i].name;
+    }
+
+    @Override
+    protected Dialog onCreateDialog(final int id) {
+        final AlertDialog.Builder builder = new Builder(this);
+        switch (id) {
+        case DIALOG_WAITING:
+            ProgressDialog pDialog = new ProgressDialog(this);
+            pDialog.setIndeterminate(false);
+            pDialog.setCancelable(false);
+            pDialog.setMessage(getResources().getString(
+                    R.string.uploader_info_uploading));
+            return pDialog;
+        case DIALOG_NO_ACCOUNT:
+            builder.setIcon(android.R.drawable.ic_dialog_alert);
+            builder.setTitle(R.string.uploader_wrn_no_account_title);
+            builder.setMessage(R.string.uploader_wrn_no_account_text);
+            builder.setCancelable(false);
+            builder.setPositiveButton(
+                    R.string.uploader_wrn_no_account_setup_btn_text,
+                    new OnClickListener() {
+                        public void onClick(DialogInterface dialog, int which) {
+                            if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
+                                // using string value since in API7 this
+                                // constatn is not defined
+                                // in API7 < this constatant is defined in
+                                // Settings.ADD_ACCOUNT_SETTINGS
+                                // and Settings.EXTRA_AUTHORITIES
+                                Intent intent = new Intent(
+                                        "android.settings.ADD_ACCOUNT_SETTINGS");
+                                intent.putExtra(
+                                        "authorities",
+                                        new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+                                startActivityForResult(intent,
+                                        REQUEST_CODE_SETUP_ACCOUNT);
+                            } else {
+                                // since in API7 there is no direct call for
+                                // account setup, so we need to
+                                // show our own AccountSetupAcricity, get
+                                // desired results and setup
+                                // everything for ourself
+                                Intent intent = new Intent(getBaseContext(),
+                                        AccountAuthenticator.class);
+                                startActivityForResult(intent,
+                                        REQUEST_CODE_SETUP_ACCOUNT);
+                            }
+                        }
+                    });
+            builder.setNegativeButton(
+                    R.string.uploader_wrn_no_account_quit_btn_text,
+                    new OnClickListener() {
+                        public void onClick(DialogInterface dialog, int which) {
+                            finish();
+                        }
+                    });
+            return builder.create();
+        case DIALOG_GET_DIRNAME:
+            final EditText dirName = new EditText(getBaseContext());
+            builder.setView(dirName);
+            builder.setTitle(R.string.uploader_info_dirname);
+            String pathToUpload;
+            if (mParents.empty()) {
+                pathToUpload = "/";
+            } else {
+                mCursor = managedQuery(Uri.withAppendedPath(
+                        ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()),
+                        null, null, null, null);
+                mCursor.moveToFirst();
+                pathToUpload = mCursor.getString(mCursor
+                        .getColumnIndex(ProviderTableMeta.FILE_PATH))
+                        + mCursor
+                                .getString(
+                                        mCursor.getColumnIndex(ProviderTableMeta.FILE_NAME))
+                                .replace(" ", "%20");
+            }
+            a a = new a(pathToUpload, dirName);
+            builder.setPositiveButton(R.string.common_ok, a);
+            builder.setNegativeButton(R.string.common_cancel,
+                    new OnClickListener() {
+                        public void onClick(DialogInterface dialog, int which) {
+                            dialog.cancel();
+                        }
+                    });
+            return builder.create();
+        case DIALOG_MULTIPLE_ACCOUNT:
+            CharSequence ac[] = new CharSequence[mAccountManager
+                    .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE).length];
+            for (int i = 0; i < ac.length; ++i) {
+                ac[i] = mAccountManager
+                        .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[i].name;
+            }
+            builder.setTitle(R.string.common_choose_account);
+            builder.setItems(ac, new OnClickListener() {
+                public void onClick(DialogInterface dialog, int which) {
+                    mAccount = mAccountManager
+                            .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[which];
+                    populateDirectoryList();
+                }
+            });
+            builder.setCancelable(true);
+            builder.setOnCancelListener(new OnCancelListener() {
+                public void onCancel(DialogInterface dialog) {
+                    dialog.cancel();
+                    finish();
+                }
+            });
+            return builder.create();
+        default:
+            throw new IllegalArgumentException("Unknown dialog id: " + id);
         }
-        builder.setTitle(R.string.common_choose_account);
-        builder.setItems(ac, new OnClickListener() {
-          public void onClick(DialogInterface dialog, int which) {
-            mAccount = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[which];
-            populateDirectoryList();
-          }
-        });
-        builder.setCancelable(true);
-        builder.setOnCancelListener(new OnCancelListener() {
-          public void onCancel(DialogInterface dialog) {
-            dialog.cancel();
-            finish();
-          }
-        });
-        return builder.create();
-      default:
-        throw new IllegalArgumentException("Unknown dialog id: " + id);
     }
-  }
-  
-  class a implements OnClickListener {
-    String mPath;
-    EditText mDirname;
-    public a(String path, EditText dirname) {
-      mPath = path; mDirname = dirname;
+
+    class a implements OnClickListener {
+        String mPath;
+        EditText mDirname;
+
+        public a(String path, EditText dirname) {
+            mPath = path;
+            mDirname = dirname;
+        }
+
+        public void onClick(DialogInterface dialog, int which) {
+            showDialog(DIALOG_WAITING);
+            mUploadThread = new Thread(new BackgroundUploader(mPath
+                    + mDirname.getText().toString(), mStreamsToUpload,
+                    mHandler, true));
+            mUploadThread.start();
+        }
     }
-    public void onClick(DialogInterface dialog, int which) {
-      showDialog(DIALOG_WAITING);
-      mUploadThread = new Thread(new BackgroundUploader(mPath+mDirname.getText().toString(), mStreamsToUpload, mHandler, true));
-      mUploadThread.start();
+
+    @Override
+    public void onBackPressed() {
+
+        if (mParents.size() == 0) {
+            super.onBackPressed();
+            return;
+        } else if (mParents.size() == 1) {
+            mParents.pop();
+            mCursor = managedQuery(ProviderTableMeta.CONTENT_URI, null,
+                    ProviderTableMeta.FILE_CONTENT_TYPE + "=?",
+                    new String[] { "DIR" }, null);
+        } else {
+            mParents.pop();
+            mCursor = managedQuery(Uri.withAppendedPath(
+                    ProviderTableMeta.CONTENT_URI_DIR, mParents.peek()), null,
+                    ProviderTableMeta.FILE_CONTENT_TYPE + "=?",
+                    new String[] { "DIR" }, null);
+        }
+
+        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
+                R.layout.uploader_list_item_layout, mCursor,
+                new String[] { ProviderTableMeta.FILE_NAME },
+                new int[] { R.id.textView1 });
+        setListAdapter(sca);
     }
-  }
-  
-  @Override
-  public void onBackPressed() {
-    
-    if (mParents.size()==0) {
-      super.onBackPressed();
-      return;
-    } else if (mParents.size() == 1) {
-      mParents.pop();
-      mCursor = managedQuery(ProviderTableMeta.CONTENT_URI,
-          null,
-          ProviderTableMeta.FILE_CONTENT_TYPE+"=?",
-          new String[]{"DIR"},
-          null);
-    } else {
-      mParents.pop();
-      mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, mParents.peek()),
-          null,
-          ProviderTableMeta.FILE_CONTENT_TYPE+"=?",
-          new String[]{"DIR"},
-          null);
+
+    public void onItemClick(AdapterView<?> parent, View view, int position,
+            long id) {
+        if (!mCursor.moveToPosition(position)) {
+            throw new IndexOutOfBoundsException("Incorrect item selected");
+        }
+        String _id = mCursor.getString(mCursor
+                .getColumnIndex(ProviderTableMeta._ID));
+        mParents.push(_id);
+
+        mCursor.close();
+        mCursor = managedQuery(
+                Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, _id),
+                null, ProviderTableMeta.FILE_CONTENT_TYPE + "=?",
+                new String[] { "DIR" }, null);
+        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
+                R.layout.uploader_list_item_layout, mCursor,
+                new String[] { ProviderTableMeta.FILE_NAME },
+                new int[] { R.id.textView1 });
+        setListAdapter(sca);
+        getListView().invalidate();
     }
-    
-    SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.uploader_list_item_layout,
-                                   mCursor,
-                                   new String[]{ProviderTableMeta.FILE_NAME},
-                                   new int[]{R.id.textView1});
-    setListAdapter(sca);
-  }
-  
-  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
-    if (!mCursor.moveToPosition(position)) {
-      throw new IndexOutOfBoundsException("Incorrect item selected");
+
+    public void onClick(View v) {
+        switch (v.getId()) {
+        case R.id.uploader_choose_folder:
+            String pathToUpload = null;
+            if (mParents.empty()) {
+                pathToUpload = "/";
+            } else {
+                mCursor = managedQuery(Uri.withAppendedPath(
+                        ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()),
+                        null, null, null, null);
+                mCursor.moveToFirst();
+                pathToUpload = mCursor.getString(
+                        mCursor.getColumnIndex(ProviderTableMeta.FILE_PATH))
+                        .replace(" ", "%20");
+            }
+            Log.d(TAG, "Uploading file to dir " + pathToUpload);
+
+            showDialog(DIALOG_WAITING);
+            mUploadThread = new Thread(new BackgroundUploader(pathToUpload,
+                    mStreamsToUpload, mHandler));
+            mUploadThread.start();
+
+            break;
+        case android.R.id.button1: // dynamic action for create aditional dir
+            showDialog(DIALOG_GET_DIRNAME);
+            break;
+        default:
+            throw new IllegalArgumentException("Wrong element clicked");
+        }
     }
-    String _id = mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta._ID));
-    mParents.push(_id);
-    
-    mCursor.close();
-    mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, _id),
-                           null,
-                           ProviderTableMeta.FILE_CONTENT_TYPE+"=?",
-                           new String[]{"DIR"},
-                           null);
-    SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.uploader_list_item_layout,
-                                                      mCursor,
-                                                      new String[]{ProviderTableMeta.FILE_NAME},
-                                                      new int[]{R.id.textView1});
-    setListAdapter(sca);
-    getListView().invalidate();
-  }
-
-  public void onClick(View v) {
-    switch (v.getId()) {
-      case R.id.uploader_choose_folder:
-        String pathToUpload = null;
-        if (mParents.empty()) {
-          pathToUpload = "/";
+
+    public void onUploadComplete(boolean uploadSucc, String message) {
+        dismissDialog(DIALOG_WAITING);
+        Log.i(TAG, "UploadSucc: " + uploadSucc + " message: " + message);
+        if (uploadSucc) {
+            Toast.makeText(this,
+                    getResources().getString(R.string.uploader_upload_succeed),
+                    Toast.LENGTH_SHORT).show();
         } else {
-          mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()), 
-                                 null,
-                                 null,
-                                 null,
-                                 null);
-          mCursor.moveToFirst();
-          pathToUpload = mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_PATH)).replace(" ", "%20");
+            Toast.makeText(
+                    this,
+                    getResources().getString(R.string.uploader_upload_failed)
+                            + message, Toast.LENGTH_LONG).show();
         }
-        Log.d(TAG, "Uploading file to dir " + pathToUpload);
-        
-        showDialog(DIALOG_WAITING);
-        mUploadThread = new Thread(new BackgroundUploader(pathToUpload, mStreamsToUpload, mHandler));
-        mUploadThread.start();
-        
-        break;
-      case android.R.id.button1: // dynamic action for create aditional dir
-        showDialog(DIALOG_GET_DIRNAME);
-        break;
-      default:
-        throw new IllegalArgumentException("Wrong element clicked");
-    }
-  }
-
-  public void onUploadComplete(boolean uploadSucc, String message) {
-    dismissDialog(DIALOG_WAITING);
-    Log.i(TAG, "UploadSucc: " + uploadSucc + " message: " + message);
-    if (uploadSucc) {
-      Toast.makeText(this, getResources().getString(R.string.uploader_upload_succeed), Toast.LENGTH_SHORT).show();
-    } else {
-      Toast.makeText(this, getResources().getString(R.string.uploader_upload_failed) + message, Toast.LENGTH_LONG).show();
-    }
-    finish();
-  }
-  
-  @Override
-  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
-    super.onActivityResult(requestCode, resultCode, data);
-    Log.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
-    if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {
-      dismissDialog(DIALOG_NO_ACCOUNT);
-      if (resultCode == RESULT_CANCELED) {
         finish();
-      }
-      Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.AUTH_TOKEN_TYPE);
-      if (accounts.length == 0) {
-        showDialog(DIALOG_NO_ACCOUNT);
-      } else {
-        // there is no need for checking for is there more then one account at this point
-        // since account setup can set only one account at time
-        mAccount = accounts[0];
-        populateDirectoryList();
-      }
-    }
-  }
-  
-  private void populateDirectoryList() {
-    mUsername = mAccount.name.substring(0, mAccount.name.indexOf('@'));
-    mPassword = mAccountManager.getPassword(mAccount);
-    setContentView(R.layout.uploader_layout);
-    
-    mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI,
-                           null,
-                           ProviderTableMeta.FILE_NAME+"=? AND " +ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",
-                           new String[]{"/", mAccount.name},
-                           null);
-    
-    if (mCursor.moveToFirst()) {
-      mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI,
-                             null,
-                             ProviderTableMeta.FILE_CONTENT_TYPE+"=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +ProviderTableMeta.FILE_PARENT+"=?",
-                             new String[]{"DIR", mAccount.name, mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta._ID))},
-                             null);    
-  
-      ListView lv = getListView();
-      lv.setOnItemClickListener(this);
-      SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
-                                                        R.layout.uploader_list_item_layout,
-                                                        mCursor,
-                                                        new String[]{ProviderTableMeta.FILE_NAME},
-                                                        new int[]{R.id.textView1});
-      setListAdapter(sca);
-      Button btn = (Button) findViewById(R.id.uploader_choose_folder);
-      btn.setOnClickListener(this);
-      // insert create new directory for multiple items uploading
-      if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
-        Button createDirBtn = new Button(this);
-        createDirBtn.setId(android.R.id.button1);
-        createDirBtn.setText(R.string.uploader_btn_create_dir_text);
-        createDirBtn.setOnClickListener(this);
-        ((LinearLayout)findViewById(R.id.linearLayout1)).addView(createDirBtn, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
-      }
     }
-  }
-  
-  private void prepareStreamsToUpload() {
-    if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
-      mStreamsToUpload = new ArrayList<Parcelable>();
-      mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
-    } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
-      mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
-    } else {
-      // unknow action inserted
-      throw new IllegalArgumentException("Unknown action given: " + getIntent().getAction());
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        super.onActivityResult(requestCode, resultCode, data);
+        Log.i(TAG, "result received. req: " + requestCode + " res: "
+                + resultCode);
+        if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {
+            dismissDialog(DIALOG_NO_ACCOUNT);
+            if (resultCode == RESULT_CANCELED) {
+                finish();
+            }
+            Account[] accounts = mAccountManager
+                    .getAccountsByType(AccountAuthenticator.AUTH_TOKEN_TYPE);
+            if (accounts.length == 0) {
+                showDialog(DIALOG_NO_ACCOUNT);
+            } else {
+                // there is no need for checking for is there more then one
+                // account at this point
+                // since account setup can set only one account at time
+                mAccount = accounts[0];
+                populateDirectoryList();
+            }
+        }
     }
-  }
-  
-  public void PartialupdateUpload(String fileLocalPath, String filename, String filepath, String contentType, String contentLength) {
-    ContentValues cv = new ContentValues();
-    cv.put(ProviderTableMeta.FILE_NAME, filename);
-    cv.put(ProviderTableMeta.FILE_PATH, filepath);
-    cv.put(ProviderTableMeta.FILE_STORAGE_PATH, fileLocalPath);
-    cv.put(ProviderTableMeta.FILE_MODIFIED, WebdavUtils.DISPLAY_DATE_FORMAT.format(new java.util.Date()));
-    cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, contentType);
-    cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, contentLength);
-    cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
-    Log.d(TAG, filename+" ++ "+filepath+" ++ " + contentLength + " ++ " + contentType + " ++ " + fileLocalPath);
-    if (!mParents.empty()) {
-      Cursor c = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()),
-                              null,
-                              null,
-                              null,
-                              null);
-      c.moveToFirst();
-      cv.put(ProviderTableMeta.FILE_PARENT, c.getString(c.getColumnIndex(ProviderTableMeta._ID)));
-      c.close();
+
+    private void populateDirectoryList() {
+        mUsername = mAccount.name.substring(0, mAccount.name.indexOf('@'));
+        mPassword = mAccountManager.getPassword(mAccount);
+        setContentView(R.layout.uploader_layout);
+
+        mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI,
+                null, ProviderTableMeta.FILE_NAME + "=? AND "
+                        + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
+                new String[] { "/", mAccount.name }, null);
+
+        if (mCursor.moveToFirst()) {
+            mCursor = managedQuery(
+                    ProviderMeta.ProviderTableMeta.CONTENT_URI,
+                    null,
+                    ProviderTableMeta.FILE_CONTENT_TYPE + "=? AND "
+                            + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND "
+                            + ProviderTableMeta.FILE_PARENT + "=?",
+                    new String[] {
+                            "DIR",
+                            mAccount.name,
+                            mCursor.getString(mCursor
+                                    .getColumnIndex(ProviderTableMeta._ID)) },
+                    null);
+
+            ListView lv = getListView();
+            lv.setOnItemClickListener(this);
+            SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
+                    R.layout.uploader_list_item_layout, mCursor,
+                    new String[] { ProviderTableMeta.FILE_NAME },
+                    new int[] { R.id.textView1 });
+            setListAdapter(sca);
+            Button btn = (Button) findViewById(R.id.uploader_choose_folder);
+            btn.setOnClickListener(this);
+            // insert create new directory for multiple items uploading
+            if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
+                Button createDirBtn = new Button(this);
+                createDirBtn.setId(android.R.id.button1);
+                createDirBtn.setText(R.string.uploader_btn_create_dir_text);
+                createDirBtn.setOnClickListener(this);
+                ((LinearLayout) findViewById(R.id.linearLayout1)).addView(
+                        createDirBtn, LayoutParams.FILL_PARENT,
+                        LayoutParams.WRAP_CONTENT);
+            }
+        }
     }
-    getContentResolver().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);
-  }
-  
-  class BackgroundUploader implements Runnable {
-    private ArrayList<Parcelable> mUploadStreams;
-    private Handler mHandler;
-    private String mUploadPath;
-    private boolean mCreateDir;
-    
-    public BackgroundUploader(String pathToUpload, ArrayList<Parcelable> streamsToUpload,
-        Handler handler) {
-      mUploadStreams = streamsToUpload;
-      mHandler = handler;
-      mUploadPath = pathToUpload.replace(" ", "%20");
-      mCreateDir = false;
+
+    private void prepareStreamsToUpload() {
+        if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
+            mStreamsToUpload = new ArrayList<Parcelable>();
+            mStreamsToUpload.add(getIntent().getParcelableExtra(
+                    Intent.EXTRA_STREAM));
+        } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
+            mStreamsToUpload = getIntent().getParcelableArrayListExtra(
+                    Intent.EXTRA_STREAM);
+        } else {
+            // unknow action inserted
+            throw new IllegalArgumentException("Unknown action given: "
+                    + getIntent().getAction());
+        }
     }
 
-    public BackgroundUploader(String pathToUpload, ArrayList<Parcelable> streamsToUpload,
-                              Handler handler, boolean createDir) {
-      mUploadStreams = streamsToUpload;
-      mHandler = handler;
-      mUploadPath = pathToUpload.replace(" ", "%20");
-      mCreateDir = createDir;
+    public void PartialupdateUpload(String fileLocalPath, String filename,
+            String filepath, String contentType, String contentLength) {
+        ContentValues cv = new ContentValues();
+        cv.put(ProviderTableMeta.FILE_NAME, filename);
+        cv.put(ProviderTableMeta.FILE_PATH, filepath);
+        cv.put(ProviderTableMeta.FILE_STORAGE_PATH, fileLocalPath);
+        cv.put(ProviderTableMeta.FILE_MODIFIED,
+                WebdavUtils.DISPLAY_DATE_FORMAT.format(new java.util.Date()));
+        cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, contentType);
+        cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, contentLength);
+        cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
+        Log.d(TAG, filename + " ++ " + filepath + " ++ " + contentLength
+                + " ++ " + contentType + " ++ " + fileLocalPath);
+        if (!mParents.empty()) {
+            Cursor c = managedQuery(Uri.withAppendedPath(
+                    ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()), null,
+                    null, null, null);
+            c.moveToFirst();
+            cv.put(ProviderTableMeta.FILE_PARENT,
+                    c.getString(c.getColumnIndex(ProviderTableMeta._ID)));
+            c.close();
+        }
+        getContentResolver().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);
     }
 
-    public void run() {
-      WebdavClient wdc = new WebdavClient(Uri.parse(mAccountManager.getUserData(mAccount,
-          AccountAuthenticator.KEY_OC_URL)));
-      wdc.setCredentials(mUsername, mPassword);
-      wdc.allowUnsignedCertificates();
-
-      // create last directory in path if nessesary
-      if (mCreateDir) {
-        wdc.createDirectory(mUploadPath);
-      }
-      
-      for (int i = 0; i < mUploadStreams.size(); ++i) {
-        Uri uri = (Uri) mUploadStreams.get(i);
-        if (uri.getScheme().equals("content")) {
-          final Cursor c = getContentResolver().query((Uri) mUploadStreams.get(i), null, null, null, null);
-          
-          if (!wdc.putFile(c.getString(c.getColumnIndex(Media.DATA)),
-                           mUploadPath+"/"+c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),
-                           c.getString(c.getColumnIndex(Media.MIME_TYPE)))) {
-            mHandler.post(new Runnable() {
-              public void run() {
-                Uploader.this.onUploadComplete(false, "Error while uploading file: " + c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));
-              }
-            });
-          } else {
-            mHandler.post(new Runnable() {
-              public void run() {
-                Uploader.this.PartialupdateUpload(c.getString(c.getColumnIndex(Media.DATA)),
-                    c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),
-                    mUploadPath+"/"+c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),
-                    c.getString(c.getColumnIndex(Media.MIME_TYPE)),
-                    c.getString(c.getColumnIndex(Media.SIZE)));
-              }
-            });
-          }
-        } else if (uri.getScheme().equals("file")) {
-         final File file = new File(Uri.decode(uri.toString()).replace(uri.getScheme()+"://", ""));
-         FileNameMap fileNameMap = URLConnection.getFileNameMap();
-         String contentType = fileNameMap.getContentTypeFor(uri.toString());
-         if (contentType == null) {
-           contentType = "text/plain";
-         }
-         if (!wdc.putFile(file.getAbsolutePath(), mUploadPath+"/"+file.getName(), contentType)) {
-           mHandler.post(new Runnable() {
-             public void run() {
-               Uploader.this.onUploadComplete(false, "Error while uploading file: " + file.getName());
-             }
-           });
-         }
+    class BackgroundUploader implements Runnable {
+        private ArrayList<Parcelable> mUploadStreams;
+        private Handler mHandler;
+        private String mUploadPath;
+        private boolean mCreateDir;
+
+        public BackgroundUploader(String pathToUpload,
+                ArrayList<Parcelable> streamsToUpload, Handler handler) {
+            mUploadStreams = streamsToUpload;
+            mHandler = handler;
+            mUploadPath = pathToUpload.replace(" ", "%20");
+            mCreateDir = false;
+        }
+
+        public BackgroundUploader(String pathToUpload,
+                ArrayList<Parcelable> streamsToUpload, Handler handler,
+                boolean createDir) {
+            mUploadStreams = streamsToUpload;
+            mHandler = handler;
+            mUploadPath = pathToUpload.replace(" ", "%20");
+            mCreateDir = createDir;
         }
-        
-      }
-      mHandler.post(new Runnable() {
+
         public void run() {
-          Uploader.this.onUploadComplete(true, null);
+            WebdavClient wdc = new WebdavClient(Uri.parse(mAccountManager
+                    .getUserData(mAccount, AccountAuthenticator.KEY_OC_URL)));
+            wdc.setCredentials(mUsername, mPassword);
+            wdc.allowUnsignedCertificates();
+
+            // create last directory in path if nessesary
+            if (mCreateDir) {
+                wdc.createDirectory(mUploadPath);
+            }
+
+            for (int i = 0; i < mUploadStreams.size(); ++i) {
+                Uri uri = (Uri) mUploadStreams.get(i);
+                if (uri.getScheme().equals("content")) {
+                    final Cursor c = getContentResolver()
+                            .query((Uri) mUploadStreams.get(i), null, null,
+                                    null, null);
+
+                    if (!wdc.putFile(
+                            c.getString(c.getColumnIndex(Media.DATA)),
+                            mUploadPath
+                                    + "/"
+                                    + c.getString(c
+                                            .getColumnIndex(Media.DISPLAY_NAME)),
+                            c.getString(c.getColumnIndex(Media.MIME_TYPE)))) {
+                        mHandler.post(new Runnable() {
+                            public void run() {
+                                Uploader.this
+                                        .onUploadComplete(
+                                                false,
+                                                "Error while uploading file: "
+                                                        + c.getString(c
+                                                                .getColumnIndex(Media.DISPLAY_NAME)));
+                            }
+                        });
+                    } else {
+                        mHandler.post(new Runnable() {
+                            public void run() {
+                                Uploader.this.PartialupdateUpload(
+                                        c.getString(c
+                                                .getColumnIndex(Media.DATA)),
+                                        c.getString(c
+                                                .getColumnIndex(Media.DISPLAY_NAME)),
+                                        mUploadPath
+                                                + "/"
+                                                + c.getString(c
+                                                        .getColumnIndex(Media.DISPLAY_NAME)),
+                                        c.getString(c
+                                                .getColumnIndex(Media.MIME_TYPE)),
+                                        c.getString(c
+                                                .getColumnIndex(Media.SIZE)));
+                            }
+                        });
+                    }
+                } else if (uri.getScheme().equals("file")) {
+                    final File file = new File(Uri.decode(uri.toString())
+                            .replace(uri.getScheme() + "://", ""));
+                    FileNameMap fileNameMap = URLConnection.getFileNameMap();
+                    String contentType = fileNameMap.getContentTypeFor(uri
+                            .toString());
+                    if (contentType == null) {
+                        contentType = "text/plain";
+                    }
+                    if (!wdc.putFile(file.getAbsolutePath(), mUploadPath + "/"
+                            + file.getName(), contentType)) {
+                        mHandler.post(new Runnable() {
+                            public void run() {
+                                Uploader.this.onUploadComplete(
+                                        false,
+                                        "Error while uploading file: "
+                                                + file.getName());
+                            }
+                        });
+                    }
+                }
+
+            }
+            mHandler.post(new Runnable() {
+                public void run() {
+                    Uploader.this.onUploadComplete(true, null);
+                }
+            });
         }
-      });
+
     }
 
-  }
-  
 }

+ 225 - 222
src/eu/alefzero/owncloud/authenticator/AccountAuthenticator.java

@@ -26,252 +26,255 @@ import android.os.Bundle;
 import android.util.Log;
 
 public class AccountAuthenticator extends AbstractAccountAuthenticator {
-  /**
-   * Is used by android system to assign accounts to authenticators. Should be
-   * used by application and all extensions.
-   */
-  public static final String ACCOUNT_TYPE = "owncloud";
-  public static final String AUTH_TOKEN_TYPE = "org.owncloud";
-
-  public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";
-  public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";
-  public static final String KEY_LOGIN_OPTIONS = "loginOptions";
-  public static final String KEY_ACCOUNT = "account";
-  /**
-   * Value under this key should handle path to webdav php script. Will be
-   * removed and usage should be replaced by combining
-   * {@link eu.alefzero.owncloud.authenticator.KEY_OC_BASE_URL} and
-   * {@link eu.alefzero.owncloud.utils.OwnCloudVersion}
-   * 
-   * @deprecated
-   */
-  public static final String KEY_OC_URL = "oc_url";
-  /**
-   * Version should be 3 numbers separated by dot so it can be parsed by
-   * {@link eu.alefzero.owncloud.utils.OwnCloudVersion}
-   */
-  public static final String KEY_OC_VERSION = "oc_version";
-  /**
-   * Base url should point to owncloud installation without trailing / ie:
-   * http://server/path or https://owncloud.server
-   */
-  public static final String KEY_OC_BASE_URL = "oc_base_url";
-
-  private static final String TAG = "AccountAuthenticator";
-  private Context mContext;
-
-  public AccountAuthenticator(Context context) {
-    super(context);
-    mContext = context;
-  }
-
-  /**
-   * {@inheritDoc}
-   */
-  @Override
-  public Bundle addAccount(AccountAuthenticatorResponse response,
-                           String accountType,
-                           String authTokenType,
-                           String[] requiredFeatures,
-                           Bundle options) throws NetworkErrorException {
-    Log.i(TAG, "Adding account with type " + accountType + " and auth token " + authTokenType);
-    try {
-      validateAccountType(accountType);
-    } catch (AuthenticatorException e) {
-      Log.e(TAG, "Failed to validate account type "+ accountType +": " + e.getMessage());
-      e.printStackTrace();
-      return e.getFailureBundle();
+    /**
+     * Is used by android system to assign accounts to authenticators. Should be
+     * used by application and all extensions.
+     */
+    public static final String ACCOUNT_TYPE = "owncloud";
+    public static final String AUTH_TOKEN_TYPE = "org.owncloud";
+
+    public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";
+    public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";
+    public static final String KEY_LOGIN_OPTIONS = "loginOptions";
+    public static final String KEY_ACCOUNT = "account";
+    /**
+     * Value under this key should handle path to webdav php script. Will be
+     * removed and usage should be replaced by combining
+     * {@link eu.alefzero.owncloud.authenticator.KEY_OC_BASE_URL} and
+     * {@link eu.alefzero.owncloud.utils.OwnCloudVersion}
+     * 
+     * @deprecated
+     */
+    public static final String KEY_OC_URL = "oc_url";
+    /**
+     * Version should be 3 numbers separated by dot so it can be parsed by
+     * {@link eu.alefzero.owncloud.utils.OwnCloudVersion}
+     */
+    public static final String KEY_OC_VERSION = "oc_version";
+    /**
+     * Base url should point to owncloud installation without trailing / ie:
+     * http://server/path or https://owncloud.server
+     */
+    public static final String KEY_OC_BASE_URL = "oc_base_url";
+
+    private static final String TAG = "AccountAuthenticator";
+    private Context mContext;
+
+    public AccountAuthenticator(Context context) {
+        super(context);
+        mContext = context;
     }
-    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
-    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
-    intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
-    intent.putExtra(KEY_REQUIRED_FEATURES, requiredFeatures);
-    intent.putExtra(KEY_LOGIN_OPTIONS, options);
-
-    setIntentFlags(intent);
-    final Bundle bundle = new Bundle();
-    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
-    return bundle;
-  }
-
-  /**
-   * {@inheritDoc}
-   */
-  @Override
-  public Bundle confirmCredentials(AccountAuthenticatorResponse response,
-      Account account, Bundle options) throws NetworkErrorException {
-    try {
-      validateAccountType(account.type);
-    } catch (AuthenticatorException e) {
-      Log.e(TAG, "Failed to validate account type "+ account.type +": " + e.getMessage());
-      e.printStackTrace();
-      return e.getFailureBundle();
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public Bundle addAccount(AccountAuthenticatorResponse response,
+            String accountType, String authTokenType,
+            String[] requiredFeatures, Bundle options)
+            throws NetworkErrorException {
+        Log.i(TAG, "Adding account with type " + accountType
+                + " and auth token " + authTokenType);
+        try {
+            validateAccountType(accountType);
+        } catch (AuthenticatorException e) {
+            Log.e(TAG, "Failed to validate account type " + accountType + ": "
+                    + e.getMessage());
+            e.printStackTrace();
+            return e.getFailureBundle();
+        }
+        final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
+        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
+                response);
+        intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
+        intent.putExtra(KEY_REQUIRED_FEATURES, requiredFeatures);
+        intent.putExtra(KEY_LOGIN_OPTIONS, options);
+
+        setIntentFlags(intent);
+        final Bundle bundle = new Bundle();
+        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
+        return bundle;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public Bundle confirmCredentials(AccountAuthenticatorResponse response,
+            Account account, Bundle options) throws NetworkErrorException {
+        try {
+            validateAccountType(account.type);
+        } catch (AuthenticatorException e) {
+            Log.e(TAG, "Failed to validate account type " + account.type + ": "
+                    + e.getMessage());
+            e.printStackTrace();
+            return e.getFailureBundle();
+        }
+        Intent intent = new Intent(mContext, AuthenticatorActivity.class);
+        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
+                response);
+        intent.putExtra(KEY_ACCOUNT, account);
+        intent.putExtra(KEY_LOGIN_OPTIONS, options);
+
+        setIntentFlags(intent);
+
+        Bundle resultBundle = new Bundle();
+        resultBundle.putParcelable(AccountManager.KEY_INTENT, intent);
+        return resultBundle;
+    }
+
+    @Override
+    public Bundle editProperties(AccountAuthenticatorResponse response,
+            String accountType) {
+        return null;
+    }
+
+    @Override
+    public Bundle getAuthToken(AccountAuthenticatorResponse response,
+            Account account, String authTokenType, Bundle options)
+            throws NetworkErrorException {
+        try {
+            validateAccountType(account.type);
+            validateAuthTokenType(authTokenType);
+        } catch (AuthenticatorException e) {
+            Log.e(TAG, "Failed to validate account type " + account.type + ": "
+                    + e.getMessage());
+            e.printStackTrace();
+            return e.getFailureBundle();
+        }
+        final AccountManager am = AccountManager.get(mContext);
+        final String password = am.getPassword(account);
+        if (password != null) {
+            final Bundle result = new Bundle();
+            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
+            result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
+            result.putString(AccountManager.KEY_AUTHTOKEN, password);
+            return result;
+        }
+
+        final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
+        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
+                response);
+        intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
+        intent.putExtra(KEY_LOGIN_OPTIONS, options);
+        intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
+
+        final Bundle bundle = new Bundle();
+        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
+        return bundle;
     }
-    Intent intent = new Intent(mContext, AuthenticatorActivity.class);
-    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
-    intent.putExtra(KEY_ACCOUNT, account);
-    intent.putExtra(KEY_LOGIN_OPTIONS, options);
-
-    setIntentFlags(intent);
-
-    Bundle resultBundle = new Bundle();
-    resultBundle.putParcelable(AccountManager.KEY_INTENT, intent);
-    return resultBundle;
-  }
-
-  @Override
-  public Bundle editProperties(AccountAuthenticatorResponse response,
-                               String accountType) {
-    return null;
-  }
-
-  @Override
-  public Bundle getAuthToken(AccountAuthenticatorResponse response,
-                             Account account,
-                             String authTokenType,
-                             Bundle options) throws NetworkErrorException {
-    try {
-      validateAccountType(account.type);
-      validateAuthTokenType(authTokenType);
-    } catch (AuthenticatorException e) {
-      Log.e(TAG, "Failed to validate account type "+ account.type +": " + e.getMessage());
-      e.printStackTrace();
-      return e.getFailureBundle();
+
+    @Override
+    public String getAuthTokenLabel(String authTokenType) {
+        return null;
     }
-    final AccountManager am = AccountManager.get(mContext);
-    final String password = am.getPassword(account);
-    if (password != null) {
-      final Bundle result = new Bundle();
-      result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
-      result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
-      result.putString(AccountManager.KEY_AUTHTOKEN, password);
-      return result;
+
+    @Override
+    public Bundle hasFeatures(AccountAuthenticatorResponse response,
+            Account account, String[] features) throws NetworkErrorException {
+        final Bundle result = new Bundle();
+        result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
+        return result;
     }
 
-    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
-    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
-    intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
-    intent.putExtra(KEY_LOGIN_OPTIONS, options);
-    intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
-
-    final Bundle bundle = new Bundle();
-    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
-    return bundle;
-  }
-
-  @Override
-  public String getAuthTokenLabel(String authTokenType) {
-    return null;
-  }
-
-  @Override
-  public Bundle hasFeatures(AccountAuthenticatorResponse response,
-                            Account account,
-                            String[] features) throws NetworkErrorException {
-    final Bundle result = new Bundle();
-    result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
-    return result;
-  }
-
-  @Override
-  public Bundle updateCredentials(AccountAuthenticatorResponse response,
-                                  Account account,
-                                  String authTokenType,
-                                  Bundle options) throws NetworkErrorException {
-    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
-    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
-    intent.putExtra(KEY_ACCOUNT, account);
-    intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
-    intent.putExtra(KEY_LOGIN_OPTIONS, options);
-    setIntentFlags(intent);
-
-    final Bundle bundle = new Bundle();
-    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
-    return bundle;
-  }
-
-  @Override
-  public Bundle getAccountRemovalAllowed(AccountAuthenticatorResponse response,
-      Account account) throws NetworkErrorException {
-    return super.getAccountRemovalAllowed(response, account);
-  }
-
-  private void setIntentFlags(Intent intent) {
-    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-    intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
-    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
-    intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
-    intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
-  }
-
-  private void validateAccountType(String type)
-      throws UnsupportedAccountTypeException {
-    if (!type.equals(ACCOUNT_TYPE)) {
-      throw new UnsupportedAccountTypeException();
+    @Override
+    public Bundle updateCredentials(AccountAuthenticatorResponse response,
+            Account account, String authTokenType, Bundle options)
+            throws NetworkErrorException {
+        final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
+        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
+                response);
+        intent.putExtra(KEY_ACCOUNT, account);
+        intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
+        intent.putExtra(KEY_LOGIN_OPTIONS, options);
+        setIntentFlags(intent);
+
+        final Bundle bundle = new Bundle();
+        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
+        return bundle;
     }
-  }
 
-  private void validateAuthTokenType(String authTokenType)
-      throws UnsupportedAuthTokenTypeException {
-    if (!authTokenType.equals(AUTH_TOKEN_TYPE)) {
-      throw new UnsupportedAuthTokenTypeException();
+    @Override
+    public Bundle getAccountRemovalAllowed(
+            AccountAuthenticatorResponse response, Account account)
+            throws NetworkErrorException {
+        return super.getAccountRemovalAllowed(response, account);
     }
-  }
 
-  public static class AuthenticatorException extends Exception {
-    private static final long serialVersionUID = 1L;
-    private Bundle mFailureBundle;
+    private void setIntentFlags(Intent intent) {
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
+        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
+        intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
+    }
 
-    public AuthenticatorException(int code, String errorMsg) {
-      mFailureBundle = new Bundle();
-      mFailureBundle.putInt(AccountManager.KEY_ERROR_CODE, code);
-      mFailureBundle.putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg);
+    private void validateAccountType(String type)
+            throws UnsupportedAccountTypeException {
+        if (!type.equals(ACCOUNT_TYPE)) {
+            throw new UnsupportedAccountTypeException();
+        }
     }
 
-    public Bundle getFailureBundle() {
-      return mFailureBundle;
+    private void validateAuthTokenType(String authTokenType)
+            throws UnsupportedAuthTokenTypeException {
+        if (!authTokenType.equals(AUTH_TOKEN_TYPE)) {
+            throw new UnsupportedAuthTokenTypeException();
+        }
     }
-  }
 
-  public static class UnsupportedAccountTypeException
-      extends
-        AuthenticatorException {
-    private static final long serialVersionUID = 1L;
+    public static class AuthenticatorException extends Exception {
+        private static final long serialVersionUID = 1L;
+        private Bundle mFailureBundle;
+
+        public AuthenticatorException(int code, String errorMsg) {
+            mFailureBundle = new Bundle();
+            mFailureBundle.putInt(AccountManager.KEY_ERROR_CODE, code);
+            mFailureBundle
+                    .putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg);
+        }
 
-    public UnsupportedAccountTypeException() {
-      super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
-          "Unsupported account type");
+        public Bundle getFailureBundle() {
+            return mFailureBundle;
+        }
     }
-  }
 
-  public static class UnsupportedAuthTokenTypeException
-      extends
-        AuthenticatorException {
-    private static final long serialVersionUID = 1L;
+    public static class UnsupportedAccountTypeException extends
+            AuthenticatorException {
+        private static final long serialVersionUID = 1L;
 
-    public UnsupportedAuthTokenTypeException() {
-      super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
-          "Unsupported auth token type");
+        public UnsupportedAccountTypeException() {
+            super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
+                    "Unsupported account type");
+        }
     }
-  }
 
-  public static class UnsupportedFeaturesException
-      extends
-        AuthenticatorException {
-    public static final long serialVersionUID = 1L;
+    public static class UnsupportedAuthTokenTypeException extends
+            AuthenticatorException {
+        private static final long serialVersionUID = 1L;
 
-    public UnsupportedFeaturesException() {
-      super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
-          "Unsupported features");
+        public UnsupportedAuthTokenTypeException() {
+            super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
+                    "Unsupported auth token type");
+        }
     }
-  }
 
-  public static class AccessDeniedException extends AuthenticatorException {
-    public AccessDeniedException(int code, String errorMsg) {
-      super(AccountManager.ERROR_CODE_INVALID_RESPONSE, "Access Denied");
+    public static class UnsupportedFeaturesException extends
+            AuthenticatorException {
+        public static final long serialVersionUID = 1L;
+
+        public UnsupportedFeaturesException() {
+            super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
+                    "Unsupported features");
+        }
     }
 
-    private static final long serialVersionUID = 1L;
+    public static class AccessDeniedException extends AuthenticatorException {
+        public AccessDeniedException(int code, String errorMsg) {
+            super(AccountManager.ERROR_CODE_INVALID_RESPONSE, "Access Denied");
+        }
+
+        private static final long serialVersionUID = 1L;
 
-  }
+    }
 }

+ 13 - 13
src/eu/alefzero/owncloud/authenticator/AccountAuthenticatorService.java

@@ -24,18 +24,18 @@ import android.os.IBinder;
 
 public class AccountAuthenticatorService extends Service {
 
-  private AccountAuthenticator mAuthenticator;
-  static final public String ACCOUNT_TYPE = "owncloud"; 
-  
-  @Override
-  public void onCreate() {
-    super.onCreate();
-    mAuthenticator = new AccountAuthenticator(this);
-  }
-  
-  @Override
-  public IBinder onBind(Intent intent) {
-    return mAuthenticator.getIBinder();
-  }
+    private AccountAuthenticator mAuthenticator;
+    static final public String ACCOUNT_TYPE = "owncloud";
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        mAuthenticator = new AccountAuthenticator(this);
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return mAuthenticator.getIBinder();
+    }
 
 }

+ 46 - 45
src/eu/alefzero/owncloud/authenticator/AuthenticationRunnable.java

@@ -29,54 +29,55 @@ import android.os.Handler;
 
 public class AuthenticationRunnable implements Runnable {
 
-  private OnAuthenticationResultListener mListener;
-  private Handler mHandler;
-  private URL mUrl;
-  private String mUsername;
-  private String mPassword;
+    private OnAuthenticationResultListener mListener;
+    private Handler mHandler;
+    private URL mUrl;
+    private String mUsername;
+    private String mPassword;
 
-  public AuthenticationRunnable(URL url, String username, String password) {
-    mListener = null;
-    mUrl = url;
-    mUsername = username;
-    mPassword = password;
-  }
-  
-  public void setOnAuthenticationResultListener(OnAuthenticationResultListener listener, Handler handler) {
-    mListener = listener;
-    mHandler = handler;
-  }
-  
-  @Override
-  public void run() {
-    Uri uri;
-    uri = Uri.parse(mUrl.toString());
-    WebdavClient client = new WebdavClient(uri);
-    client.setCredentials(mUsername, mPassword);
-    int login_result = client.tryToLogin(); 
-    switch (login_result) {
-      case HttpStatus.SC_OK:
-        postResult(true, uri.toString());
-        break;
-      case HttpStatus.SC_UNAUTHORIZED:
-        postResult(false, "Invalid login or/and password");
-        break;
-      case HttpStatus.SC_NOT_FOUND:
-        postResult(false, "Wrong path given");
-        break;
-      default:
-        postResult(false, "Internal server error, code: " + login_result);
+    public AuthenticationRunnable(URL url, String username, String password) {
+        mListener = null;
+        mUrl = url;
+        mUsername = username;
+        mPassword = password;
     }
-  }
 
-  private void postResult(final boolean success, final String message) {
-    if (mHandler != null && mListener != null) {
-      mHandler.post(new Runnable() {
-        @Override
-        public void run() {
-          mListener.onAuthenticationResult(success, message);
+    public void setOnAuthenticationResultListener(
+            OnAuthenticationResultListener listener, Handler handler) {
+        mListener = listener;
+        mHandler = handler;
+    }
+
+    @Override
+    public void run() {
+        Uri uri;
+        uri = Uri.parse(mUrl.toString());
+        WebdavClient client = new WebdavClient(uri);
+        client.setCredentials(mUsername, mPassword);
+        int login_result = client.tryToLogin();
+        switch (login_result) {
+        case HttpStatus.SC_OK:
+            postResult(true, uri.toString());
+            break;
+        case HttpStatus.SC_UNAUTHORIZED:
+            postResult(false, "Invalid login or/and password");
+            break;
+        case HttpStatus.SC_NOT_FOUND:
+            postResult(false, "Wrong path given");
+            break;
+        default:
+            postResult(false, "Internal server error, code: " + login_result);
+        }
+    }
+
+    private void postResult(final boolean success, final String message) {
+        if (mHandler != null && mListener != null) {
+            mHandler.post(new Runnable() {
+                @Override
+                public void run() {
+                    mListener.onAuthenticationResult(success, message);
+                }
+            });
         }
-      });
     }
-  }
 }

+ 114 - 113
src/eu/alefzero/owncloud/authenticator/ConnectionCheckerRunnable.java

@@ -39,124 +39,125 @@ import android.os.Handler;
 import android.util.Log;
 
 public class ConnectionCheckerRunnable implements Runnable {
-  private static final String TAG = "ConnectionCheckerRunnable";
-  private OnConnectCheckListener mListener;
-  private String mUrl;
-  private Handler mHandler;
-  private ResultType mLatestResult;
-  private Context mContext;
-  private OwnCloudVersion mOCVersion;
-  
-  public void setListener(OnConnectCheckListener listener, Handler handler) {
-    mListener = listener;
-    mHandler = handler;
-  }
-
-  public ConnectionCheckerRunnable(String url, Context context) {
-    mListener = null;
-    mHandler = null;
-    mUrl = url;
-    mContext = context;
-    mOCVersion = null;
-  }
-  
-  @Override
-  public void run() {
-    
-    if (!isOnline()) {
-      postResult(ResultType.NO_NETWORK_CONNECTION);
-      return;
+    private static final String TAG = "ConnectionCheckerRunnable";
+    private OnConnectCheckListener mListener;
+    private String mUrl;
+    private Handler mHandler;
+    private ResultType mLatestResult;
+    private Context mContext;
+    private OwnCloudVersion mOCVersion;
+
+    public void setListener(OnConnectCheckListener listener, Handler handler) {
+        mListener = listener;
+        mHandler = handler;
+    }
+
+    public ConnectionCheckerRunnable(String url, Context context) {
+        mListener = null;
+        mHandler = null;
+        mUrl = url;
+        mContext = context;
+        mOCVersion = null;
+    }
+
+    @Override
+    public void run() {
+
+        if (!isOnline()) {
+            postResult(ResultType.NO_NETWORK_CONNECTION);
+            return;
+        }
+        if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) {
+            mLatestResult = ResultType.OK;
+            tryConnection(Uri.parse(mUrl + AccountUtils.STATUS_PATH));
+            postResult(mLatestResult);
+        } else {
+            Uri uri = Uri.parse("https://" + mUrl + AccountUtils.STATUS_PATH);
+            if (tryConnection(uri)) {
+                postResult(ResultType.OK);
+                return;
+            }
+            Log.d(TAG,
+                    "establishing secure connection failed, trying non secure connection");
+            uri = Uri.parse("http://" + mUrl + AccountUtils.STATUS_PATH);
+
+            if (tryConnection(uri)) {
+                postResult(ResultType.OK_NO_SSL);
+                return;
+            }
+            postResult(mLatestResult);
+        }
     }
-    if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) {
-      mLatestResult = ResultType.OK;
-      tryConnection(Uri.parse(mUrl + AccountUtils.STATUS_PATH));
-      postResult(mLatestResult);
-    } else {
-      Uri uri = Uri.parse("https://" + mUrl + AccountUtils.STATUS_PATH);
-      if (tryConnection(uri)) {
-        postResult(ResultType.OK);
-        return;
-      }
-      Log.d(TAG, "establishing secure connection failed, trying non secure connection");
-      uri = Uri.parse("http://" + mUrl + AccountUtils.STATUS_PATH);
-
-      if (tryConnection(uri)) {
-        postResult(ResultType.OK_NO_SSL);
-        return;
-      }
-      postResult(mLatestResult);
+
+    public OwnCloudVersion getDiscoveredVersion() {
+        return mOCVersion;
     }
-  }
-
-  public OwnCloudVersion getDiscoveredVersion() {
-    return mOCVersion;
-  }
-  
-  private boolean tryConnection(Uri uri) {
-    WebdavClient wc = new WebdavClient(uri);
-    wc.allowUnsignedCertificates();
-    GetMethod get = new GetMethod(uri.toString());
-    boolean retval = false;
-    try {
-      int status = wc.executeMethod(get);
-      switch (status) {
-        case HttpStatus.SC_OK: {
-          String response = get.getResponseBodyAsString();
-          JSONObject json = new JSONObject(response);
-          if (!json.getBoolean("installed")) {
-            mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
-            break;
-          }
-          mOCVersion = new OwnCloudVersion(json.getString("version"));
-          if (!mOCVersion.isVersionValid())
-            break;
-          retval = true;
-          break;
+
+    private boolean tryConnection(Uri uri) {
+        WebdavClient wc = new WebdavClient(uri);
+        wc.allowUnsignedCertificates();
+        GetMethod get = new GetMethod(uri.toString());
+        boolean retval = false;
+        try {
+            int status = wc.executeMethod(get);
+            switch (status) {
+            case HttpStatus.SC_OK: {
+                String response = get.getResponseBodyAsString();
+                JSONObject json = new JSONObject(response);
+                if (!json.getBoolean("installed")) {
+                    mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
+                    break;
+                }
+                mOCVersion = new OwnCloudVersion(json.getString("version"));
+                if (!mOCVersion.isVersionValid())
+                    break;
+                retval = true;
+                break;
+            }
+            case HttpStatus.SC_NOT_FOUND:
+                mLatestResult = ResultType.FILE_NOT_FOUND;
+                break;
+            case HttpStatus.SC_INTERNAL_SERVER_ERROR:
+                mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
+                break;
+            default:
+                mLatestResult = ResultType.UNKNOWN_ERROR;
+                Log.e(TAG, "Not handled status received from server: " + status);
+            }
+
+        } catch (Exception e) {
+            if (e instanceof UnknownHostException
+                    || e instanceof ConnectException) {
+                mLatestResult = ResultType.HOST_NOT_AVAILABLE;
+            } else if (e instanceof JSONException) {
+                mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
+            } else if (e instanceof SSLHandshakeException) {
+                mLatestResult = ResultType.SSL_INIT_ERROR;
+            } else {
+                mLatestResult = ResultType.UNKNOWN_ERROR;
+            }
+            e.printStackTrace();
         }
-        case HttpStatus.SC_NOT_FOUND:
-          mLatestResult = ResultType.FILE_NOT_FOUND;
-          break;
-        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
-          mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
-          break;
-        default:
-          mLatestResult = ResultType.UNKNOWN_ERROR;
-          Log.e(TAG,"Not handled status received from server: " + status);
-      }
-      
-    } catch (Exception e) {
-      if (e instanceof UnknownHostException || e instanceof ConnectException) {
-        mLatestResult = ResultType.HOST_NOT_AVAILABLE;
-      } else if (e instanceof JSONException) {
-        mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
-      } else if (e instanceof SSLHandshakeException) {
-        mLatestResult = ResultType.SSL_INIT_ERROR;
-      } else {
-        mLatestResult = ResultType.UNKNOWN_ERROR;
-      }
-      e.printStackTrace();
+
+        return retval;
+    }
+
+    private boolean isOnline() {
+        ConnectivityManager cm = (ConnectivityManager) mContext
+                .getSystemService(Context.CONNECTIVITY_SERVICE);
+        return cm != null && cm.getActiveNetworkInfo() != null
+                && cm.getActiveNetworkInfo().isConnectedOrConnecting();
     }
 
-    return retval;
-  }
-  
-  private boolean isOnline() {
-    ConnectivityManager cm =
-        (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-    return cm != null
-           && cm.getActiveNetworkInfo() != null
-           && cm.getActiveNetworkInfo().isConnectedOrConnecting();
-  }
-  
-  private void postResult(final ResultType result) {
-    if (mHandler != null && mListener != null) {
-      mHandler.post(new Runnable() {
-        @Override
-        public void run() {
-          mListener.onConnectionCheckResult(result);
+    private void postResult(final ResultType result) {
+        if (mHandler != null && mListener != null) {
+            mHandler.post(new Runnable() {
+                @Override
+                public void run() {
+                    mListener.onConnectionCheckResult(result);
+                }
+            });
         }
-      });
     }
-  }
-  
+
 }

+ 85 - 92
src/eu/alefzero/owncloud/authenticator/EasySSLSocketFactory.java

@@ -51,49 +51,55 @@ import android.util.Log;
 
 /**
  * <p>
- * EasySSLProtocolSocketFactory can be used to creats SSL {@link Socket}s 
- * that accept self-signed certificates. 
+ * EasySSLProtocolSocketFactory can be used to creats SSL {@link Socket}s that
+ * accept self-signed certificates.
  * </p>
  * <p>
- * This socket factory SHOULD NOT be used for productive systems 
- * due to security reasons, unless it is a concious decision and 
- * you are perfectly aware of security implications of accepting 
- * self-signed certificates
+ * This socket factory SHOULD NOT be used for productive systems due to security
+ * reasons, unless it is a concious decision and you are perfectly aware of
+ * security implications of accepting self-signed certificates
  * </p>
- *
+ * 
  * <p>
  * Example of using custom protocol socket factory for a specific host:
- *     <pre>
- *     Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
- *
- *     URI uri = new URI("https://localhost/", true);
- *     // use relative url only
- *     GetMethod httpget = new GetMethod(uri.getPathQuery());
- *     HostConfiguration hc = new HostConfiguration();
- *     hc.setHost(uri.getHost(), uri.getPort(), easyhttps);
- *     HttpClient client = new HttpClient();
- *     client.executeMethod(hc, httpget);
- *     </pre>
+ * 
+ * <pre>
+ * Protocol easyhttps = new Protocol(&quot;https&quot;, new EasySSLProtocolSocketFactory(),
+ *         443);
+ * 
+ * URI uri = new URI(&quot;https://localhost/&quot;, true);
+ * // use relative url only
+ * GetMethod httpget = new GetMethod(uri.getPathQuery());
+ * HostConfiguration hc = new HostConfiguration();
+ * hc.setHost(uri.getHost(), uri.getPort(), easyhttps);
+ * HttpClient client = new HttpClient();
+ * client.executeMethod(hc, httpget);
+ * </pre>
+ * 
  * </p>
  * <p>
- * Example of using custom protocol socket factory per default instead of the standard one:
- *     <pre>
- *     Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
- *     Protocol.registerProtocol("https", easyhttps);
- *
- *     HttpClient client = new HttpClient();
- *     GetMethod httpget = new GetMethod("https://localhost/");
- *     client.executeMethod(httpget);
- *     </pre>
+ * Example of using custom protocol socket factory per default instead of the
+ * standard one:
+ * 
+ * <pre>
+ * Protocol easyhttps = new Protocol(&quot;https&quot;, new EasySSLProtocolSocketFactory(),
+ *         443);
+ * Protocol.registerProtocol(&quot;https&quot;, easyhttps);
+ * 
+ * HttpClient client = new HttpClient();
+ * GetMethod httpget = new GetMethod(&quot;https://localhost/&quot;);
+ * client.executeMethod(httpget);
+ * </pre>
+ * 
  * </p>
  * 
  * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
  * 
- * <p>
- * DISCLAIMER: HttpClient developers DO NOT actively support this component.
- * The component is provided as a reference material, which may be inappropriate
- * for use without additional customization.
- * </p>
+ *         <p>
+ *         DISCLAIMER: HttpClient developers DO NOT actively support this
+ *         component. The component is provided as a reference material, which
+ *         may be inappropriate for use without additional customization.
+ *         </p>
  */
 
 public class EasySSLSocketFactory implements ProtocolSocketFactory {
@@ -111,13 +117,11 @@ public class EasySSLSocketFactory implements ProtocolSocketFactory {
     private static SSLContext createEasySSLContext() {
         try {
             SSLContext context = SSLContext.getInstance("TLS");
-            context.init(
-              null, 
-              new TrustManager[] {new EasyX509TrustManager(null)}, 
-              null);
+            context.init(null, new TrustManager[] { new EasyX509TrustManager(
+                    null) }, null);
             return context;
         } catch (Exception er) {
-            Log.e(TAG, er.getMessage()+"");
+            Log.e(TAG, er.getMessage() + "");
             throw new HttpClientError(er.toString());
         }
     }
@@ -132,59 +136,58 @@ public class EasySSLSocketFactory implements ProtocolSocketFactory {
     /**
      * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
      */
-    public Socket createSocket(
-        String host,
-        int port,
-        InetAddress clientHost,
-        int clientPort)
-        throws IOException, UnknownHostException {
-
-        return getSSLContext().getSocketFactory().createSocket(
-            host,
-            port,
-            clientHost,
-            clientPort
-        );
+    public Socket createSocket(String host, int port, InetAddress clientHost,
+            int clientPort) throws IOException, UnknownHostException {
+
+        return getSSLContext().getSocketFactory().createSocket(host, port,
+                clientHost, clientPort);
     }
 
     /**
-     * Attempts to get a new socket connection to the given host within the given time limit.
+     * Attempts to get a new socket connection to the given host within the
+     * given time limit.
      * <p>
-     * To circumvent the limitations of older JREs that do not support connect timeout a 
-     * controller thread is executed. The controller thread attempts to create a new socket 
-     * within the given limit of time. If socket constructor does not return until the 
-     * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
+     * To circumvent the limitations of older JREs that do not support connect
+     * timeout a controller thread is executed. The controller thread attempts
+     * to create a new socket within the given limit of time. If socket
+     * constructor does not return until the timeout expires, the controller
+     * terminates and throws an {@link ConnectTimeoutException}
      * </p>
-     *  
-     * @param host the host name/IP
-     * @param port the port on the host
-     * @param clientHost the local host name/IP to bind the socket to
-     * @param clientPort the port on the local machine
-     * @param params {@link HttpConnectionParams Http connection parameters}
+     * 
+     * @param host
+     *            the host name/IP
+     * @param port
+     *            the port on the host
+     * @param clientHost
+     *            the local host name/IP to bind the socket to
+     * @param clientPort
+     *            the port on the local machine
+     * @param params
+     *            {@link HttpConnectionParams Http connection parameters}
      * 
      * @return Socket a new socket
      * 
-     * @throws IOException if an I/O error occurs while creating the socket
-     * @throws UnknownHostException if the IP address of the host cannot be
-     * determined
+     * @throws IOException
+     *             if an I/O error occurs while creating the socket
+     * @throws UnknownHostException
+     *             if the IP address of the host cannot be determined
      */
-    public Socket createSocket(
-        final String host,
-        final int port,
-        final InetAddress localAddress,
-        final int localPort,
-        final HttpConnectionParams params
-    ) throws IOException, UnknownHostException, ConnectTimeoutException {
+    public Socket createSocket(final String host, final int port,
+            final InetAddress localAddress, final int localPort,
+            final HttpConnectionParams params) throws IOException,
+            UnknownHostException, ConnectTimeoutException {
         if (params == null) {
             throw new IllegalArgumentException("Parameters may not be null");
         }
         int timeout = params.getConnectionTimeout();
         SocketFactory socketfactory = getSSLContext().getSocketFactory();
         if (timeout == 0) {
-            return socketfactory.createSocket(host, port, localAddress, localPort);
+            return socketfactory.createSocket(host, port, localAddress,
+                    localPort);
         } else {
             Socket socket = socketfactory.createSocket();
-            SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
+            SocketAddress localaddr = new InetSocketAddress(localAddress,
+                    localPort);
             SocketAddress remoteaddr = new InetSocketAddress(host, port);
             socket.bind(localaddr);
             socket.connect(remoteaddr, timeout);
@@ -195,33 +198,23 @@ public class EasySSLSocketFactory implements ProtocolSocketFactory {
     /**
      * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
      */
-    public Socket createSocket(String host, int port)
-        throws IOException, UnknownHostException {
-        return getSSLContext().getSocketFactory().createSocket(
-            host,
-            port
-        );
+    public Socket createSocket(String host, int port) throws IOException,
+            UnknownHostException {
+        return getSSLContext().getSocketFactory().createSocket(host, port);
     }
 
     /**
      * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
      */
-    public Socket createSocket(
-        Socket socket,
-        String host,
-        int port,
-        boolean autoClose)
-        throws IOException, UnknownHostException {
-        return getSSLContext().getSocketFactory().createSocket(
-            socket,
-            host,
-            port,
-            autoClose
-        );
+    public Socket createSocket(Socket socket, String host, int port,
+            boolean autoClose) throws IOException, UnknownHostException {
+        return getSSLContext().getSocketFactory().createSocket(socket, host,
+                port, autoClose);
     }
 
     public boolean equals(Object obj) {
-        return ((obj != null) && obj.getClass().equals(EasySSLSocketFactory.class));
+        return ((obj != null) && obj.getClass().equals(
+                EasySSLSocketFactory.class));
     }
 
     public int hashCode() {

+ 24 - 29
src/eu/alefzero/owncloud/authenticator/EasyX509TrustManager.java

@@ -31,62 +31,57 @@ import javax.net.ssl.X509TrustManager;
 
 /**
  * @author olamy
- * @version $Id: EasyX509TrustManager.java 765355 2009-04-15 20:59:07Z evenisse $
+ * @version $Id: EasyX509TrustManager.java 765355 2009-04-15 20:59:07Z evenisse
+ *          $
  * @since 1.2.3
  */
-public class EasyX509TrustManager
-    implements X509TrustManager
-{
+public class EasyX509TrustManager implements X509TrustManager {
 
     private X509TrustManager standardTrustManager = null;
 
     /**
      * Constructor for EasyX509TrustManager.
      */
-    public EasyX509TrustManager( KeyStore keystore )
-        throws NoSuchAlgorithmException, KeyStoreException
-    {
+    public EasyX509TrustManager(KeyStore keystore)
+            throws NoSuchAlgorithmException, KeyStoreException {
         super();
-        TrustManagerFactory factory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() );
-        factory.init( keystore );
+        TrustManagerFactory factory = TrustManagerFactory
+                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
+        factory.init(keystore);
         TrustManager[] trustmanagers = factory.getTrustManagers();
-        if ( trustmanagers.length == 0 )
-        {
-            throw new NoSuchAlgorithmException( "no trust manager found" );
+        if (trustmanagers.length == 0) {
+            throw new NoSuchAlgorithmException("no trust manager found");
         }
         this.standardTrustManager = (X509TrustManager) trustmanagers[0];
     }
 
     /**
-     * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
+     * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],
+     *      String authType)
      */
-    public void checkClientTrusted( X509Certificate[] certificates, String authType )
-        throws CertificateException
-    {
-        standardTrustManager.checkClientTrusted( certificates, authType );
+    public void checkClientTrusted(X509Certificate[] certificates,
+            String authType) throws CertificateException {
+        standardTrustManager.checkClientTrusted(certificates, authType);
     }
 
     /**
-     * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
+     * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
+     *      String authType)
      */
-    public void checkServerTrusted( X509Certificate[] certificates, String authType )
-        throws CertificateException
-    {
-        if ( ( certificates != null ) && ( certificates.length == 1 ) )
-        {
+    public void checkServerTrusted(X509Certificate[] certificates,
+            String authType) throws CertificateException {
+        if ((certificates != null) && (certificates.length == 1)) {
             certificates[0].checkValidity();
-        }
-        else
-        {
-            //standardTrustManager.checkServerTrusted( certificates, authType );
+        } else {
+            // standardTrustManager.checkServerTrusted( certificates, authType
+            // );
         }
     }
 
     /**
      * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
      */
-    public X509Certificate[] getAcceptedIssuers()
-    {
+    public X509Certificate[] getAcceptedIssuers() {
         return this.standardTrustManager.getAcceptedIssuers();
     }
 

+ 2 - 2
src/eu/alefzero/owncloud/authenticator/OnAuthenticationResultListener.java

@@ -1,7 +1,7 @@
 package eu.alefzero.owncloud.authenticator;
 
 public interface OnAuthenticationResultListener {
-  
-  public void onAuthenticationResult(boolean success, String message);
+
+    public void onAuthenticationResult(boolean success, String message);
 
 }

+ 7 - 16
src/eu/alefzero/owncloud/authenticator/OnConnectCheckListener.java

@@ -1,20 +1,11 @@
 package eu.alefzero.owncloud.authenticator;
 
 public interface OnConnectCheckListener {
-  
-  enum ResultType {
-    OK,
-    OK_NO_SSL,
-    SSL_INIT_ERROR,
-    HOST_NOT_AVAILABLE,
-    TIMEOUT,
-    NO_NETWORK_CONNECTION,
-    INORRECT_ADDRESS,
-    INSTANCE_NOT_CONFIGURED,
-    FILE_NOT_FOUND,
-    UNKNOWN_ERROR
-  }
-  
-  public void onConnectionCheckResult(ResultType type);
-  
+
+    enum ResultType {
+        OK, OK_NO_SSL, SSL_INIT_ERROR, HOST_NOT_AVAILABLE, TIMEOUT, NO_NETWORK_CONNECTION, INORRECT_ADDRESS, INSTANCE_NOT_CONFIGURED, FILE_NOT_FOUND, UNKNOWN_ERROR
+    }
+
+    public void onConnectionCheckResult(ResultType type);
+
 }

+ 11 - 11
src/eu/alefzero/owncloud/datamodel/DataStorageManager.java

@@ -22,15 +22,15 @@ import java.util.Vector;
 
 public interface DataStorageManager {
 
-  public OCFile getFileByPath(String path);
-  
-  public OCFile getFileById(long id);
-
-  public boolean fileExists(String path);
-  
-  public boolean fileExists(long id);
-  
-  public boolean saveFile(OCFile file);
-  
-  public Vector<OCFile> getDirectoryContent(OCFile f);
+    public OCFile getFileByPath(String path);
+
+    public OCFile getFileById(long id);
+
+    public boolean fileExists(String path);
+
+    public boolean fileExists(long id);
+
+    public boolean saveFile(OCFile file);
+
+    public Vector<OCFile> getDirectoryContent(OCFile f);
 }

+ 243 - 227
src/eu/alefzero/owncloud/datamodel/FileDataStorageManager.java

@@ -32,243 +32,259 @@ import android.util.Log;
 
 public class FileDataStorageManager implements DataStorageManager {
 
-  private ContentResolver mContentResolver;
-  private ContentProviderClient mContentProvider;
-  private Account mAccount;
-  
-  private static String TAG = "FileDataStorageManager";
-  
-  public FileDataStorageManager(Account account, ContentResolver cr) {
-    mContentProvider = null;
-    mContentResolver = cr;
-    mAccount = account;
-  }
-  
-  public FileDataStorageManager(Account account, ContentProviderClient cp) {
-    mContentProvider = cp;
-    mContentResolver = null;
-    mAccount = account;
-  }
-  
-  @Override
-  public OCFile getFileByPath(String path) {
-    Cursor c = getCursorForValue(ProviderTableMeta.FILE_PATH, path);
-    OCFile file = null;
-    if (c.moveToFirst()) {
-      file = createFileInstance(c);
-      c.close();
+    private ContentResolver mContentResolver;
+    private ContentProviderClient mContentProvider;
+    private Account mAccount;
+
+    private static String TAG = "FileDataStorageManager";
+
+    public FileDataStorageManager(Account account, ContentResolver cr) {
+        mContentProvider = null;
+        mContentResolver = cr;
+        mAccount = account;
     }
-    return file;
-  }
-
-  @Override
-  public OCFile getFileById(long id) {
-    Cursor c = getCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
-    OCFile file = null;
-    if (c.moveToFirst()) {
-      file = createFileInstance(c);
-      c.close();
+
+    public FileDataStorageManager(Account account, ContentProviderClient cp) {
+        mContentProvider = cp;
+        mContentResolver = null;
+        mAccount = account;
     }
-    return file;
-  }
-
-  @Override
-  public boolean fileExists(long id) {
-    return fileExists(ProviderTableMeta._ID, String.valueOf(id));
-  }
-
-  @Override
-  public boolean fileExists(String path) {
-    return fileExists(ProviderTableMeta.FILE_PATH, path);
-  }
-
-  @Override
-  public boolean saveFile(OCFile file) {
-    boolean overriden = false;
-    ContentValues cv = new ContentValues();
-    cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
-    cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
-    cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
-    cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
-    cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
-    if (file.getParentId() != 0)
-      cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
-    cv.put(ProviderTableMeta.FILE_PATH, file.getPath());
-    cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
-    cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
-
-    if (fileExists(file.getPath())) {
-      OCFile tmpfile = getFileByPath(file.getPath());
-      file.setStoragePath(tmpfile.getStoragePath());
-      cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
-      file.setFileId(tmpfile.getFileId());
-      
-      overriden = true;
-      if (getContentResolver() != null) {
-        getContentResolver().update(ProviderTableMeta.CONTENT_URI,
-                                    cv,
-                                    ProviderTableMeta._ID + "=?",
-                                    new String[] {String.valueOf(file.getFileId())});
-      } else {
-        try {
-          getContentProvider().update(ProviderTableMeta.CONTENT_URI,
-                                      cv,
-                                      ProviderTableMeta._ID + "=?",
-                                      new String[] {String.valueOf(file.getFileId())});
-        } catch (RemoteException e) {
-          Log.e(TAG, "Fail to insert insert file to database " + e.getMessage());
+
+    @Override
+    public OCFile getFileByPath(String path) {
+        Cursor c = getCursorForValue(ProviderTableMeta.FILE_PATH, path);
+        OCFile file = null;
+        if (c.moveToFirst()) {
+            file = createFileInstance(c);
+            c.close();
         }
-      }
-    } else {
-      Uri result_uri = null;
-      if (getContentResolver() != null) {
-        result_uri = getContentResolver().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);
-      } else {
-        try {
-          result_uri = getContentProvider().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);
-        } catch (RemoteException e) {
-          Log.e(TAG, "Fail to insert insert file to database " + e.getMessage());
+        return file;
+    }
+
+    @Override
+    public OCFile getFileById(long id) {
+        Cursor c = getCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
+        OCFile file = null;
+        if (c.moveToFirst()) {
+            file = createFileInstance(c);
+            c.close();
         }
-      }
-      if (result_uri != null) {
-        long new_id = Long.parseLong(result_uri.getPathSegments().get(1));
-        file.setFileId(new_id);
-      }
+        return file;
+    }
+
+    @Override
+    public boolean fileExists(long id) {
+        return fileExists(ProviderTableMeta._ID, String.valueOf(id));
+    }
+
+    @Override
+    public boolean fileExists(String path) {
+        return fileExists(ProviderTableMeta.FILE_PATH, path);
     }
 
-    if (file.isDirectory() && file.needsUpdatingWhileSaving())
-      for (OCFile f : getDirectoryContent(file))
-        saveFile(f);
-    
-    return overriden;
-  }
-
-  public void setAccount(Account account) {
-    mAccount = account;
-  }
-  
-  public Account getAccount() {
-    return mAccount;
-  }
-  
-  public void setContentResolver(ContentResolver cr) {
-    mContentResolver = cr;
-  }
-  
-  public ContentResolver getContentResolver() {
-    return mContentResolver;
-  }
-  
-  public void setContentProvider(ContentProviderClient cp) {
-    mContentProvider = cp;
-  }
-  
-  public ContentProviderClient getContentProvider() {
-    return mContentProvider;
-  }
-
-  public Vector<OCFile> getDirectoryContent(OCFile f) {
-    if (f != null && f.isDirectory() && f.getFileId() != -1) {
-      Vector<OCFile> ret = new Vector<OCFile>();
-
-      Uri req_uri = Uri.withAppendedPath(
-          ProviderTableMeta.CONTENT_URI_DIR, String.valueOf(f.getFileId()));
-      Cursor c = null;
-      
-      if (getContentProvider() != null) {
-        try {
-          c = getContentProvider().query(req_uri,
-                                         null,
-                                         ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
-                                         new String[]{mAccount.name},
-                                         null);
-        } catch (RemoteException e) {
-          Log.e(TAG, e.getMessage());
-          return ret;
+    @Override
+    public boolean saveFile(OCFile file) {
+        boolean overriden = false;
+        ContentValues cv = new ContentValues();
+        cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
+        cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
+        cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
+        cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
+        cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
+        if (file.getParentId() != 0)
+            cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
+        cv.put(ProviderTableMeta.FILE_PATH, file.getPath());
+        cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
+        cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
+
+        if (fileExists(file.getPath())) {
+            OCFile tmpfile = getFileByPath(file.getPath());
+            file.setStoragePath(tmpfile.getStoragePath());
+            cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
+            file.setFileId(tmpfile.getFileId());
+
+            overriden = true;
+            if (getContentResolver() != null) {
+                getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv,
+                        ProviderTableMeta._ID + "=?",
+                        new String[] { String.valueOf(file.getFileId()) });
+            } else {
+                try {
+                    getContentProvider().update(ProviderTableMeta.CONTENT_URI,
+                            cv, ProviderTableMeta._ID + "=?",
+                            new String[] { String.valueOf(file.getFileId()) });
+                } catch (RemoteException e) {
+                    Log.e(TAG,
+                            "Fail to insert insert file to database "
+                                    + e.getMessage());
+                }
+            }
+        } else {
+            Uri result_uri = null;
+            if (getContentResolver() != null) {
+                result_uri = getContentResolver().insert(
+                        ProviderTableMeta.CONTENT_URI_FILE, cv);
+            } else {
+                try {
+                    result_uri = getContentProvider().insert(
+                            ProviderTableMeta.CONTENT_URI_FILE, cv);
+                } catch (RemoteException e) {
+                    Log.e(TAG,
+                            "Fail to insert insert file to database "
+                                    + e.getMessage());
+                }
+            }
+            if (result_uri != null) {
+                long new_id = Long.parseLong(result_uri.getPathSegments()
+                        .get(1));
+                file.setFileId(new_id);
+            }
         }
-      } else {
-        c = getContentResolver().query(req_uri,
-                                       null,
-                                       ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
-                                       new String[]{mAccount.name},
-                                       null);
-      }
-
-      if (c.moveToFirst()) {
-        do {
-          OCFile child = createFileInstance(c);
-          ret.add(child);
-        } while (c.moveToNext());
-      }
-      
-      c.close();
-      return ret;
+
+        if (file.isDirectory() && file.needsUpdatingWhileSaving())
+            for (OCFile f : getDirectoryContent(file))
+                saveFile(f);
+
+        return overriden;
+    }
+
+    public void setAccount(Account account) {
+        mAccount = account;
     }
-    return null;
-  }
-
-  
-  private boolean fileExists(String cmp_key, String value) {
-    Cursor c;
-    if (getContentResolver() != null) {
-      c = getContentResolver().query(ProviderTableMeta.CONTENT_URI,
-                                    null,
-                                    cmp_key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
-                                    new String[] {value, mAccount.name},
-                                    null);
-    } else {
-      try {
-        c = getContentProvider().query(ProviderTableMeta.CONTENT_URI,
-                                      null,
-                                      cmp_key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
-                                      new String[] {value, mAccount.name},
-                                      null);
-      } catch (RemoteException e) {
-        Log.e(TAG, "Couldn't determine file existance, assuming non existance: " + e.getMessage());
-        return false;
-      }
+
+    public Account getAccount() {
+        return mAccount;
     }
-    boolean retval = c.moveToFirst();
-    c.close();
-    return retval;
-  }
-  
-  private Cursor getCursorForValue(String key, String value) {
-    Cursor c = null;
-    if (getContentResolver() != null) {
-      c = getContentResolver().query(ProviderTableMeta.CONTENT_URI,
-                                     null,
-                                     key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
-                                     new String[] {value, mAccount.name},
-                                     null);
-    } else {
-      try {
-        c = getContentProvider().query(ProviderTableMeta.CONTENT_URI,
-                                       null,
-                                       key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
-                                       new String[]{value, mAccount.name},
-                                       null);
-      } catch (RemoteException e) {
-        Log.e(TAG, "Could not get file details: " + e.getMessage());
-        c = null;
-      }
+
+    public void setContentResolver(ContentResolver cr) {
+        mContentResolver = cr;
+    }
+
+    public ContentResolver getContentResolver() {
+        return mContentResolver;
     }
-    return c;
-  }
-
-  private OCFile createFileInstance(Cursor c) {
-    OCFile file = null;
-    if (c != null) {
-      file = new OCFile(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH)));
-      file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
-      file.setParentId(c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_PARENT)));
-      file.setStoragePath(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
-      file.setMimetype(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
-      file.setFileLength(c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
-      file.setCreationTimestamp(c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_CREATION)));
-      file.setModificationTimestamp(c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
+
+    public void setContentProvider(ContentProviderClient cp) {
+        mContentProvider = cp;
+    }
+
+    public ContentProviderClient getContentProvider() {
+        return mContentProvider;
+    }
+
+    public Vector<OCFile> getDirectoryContent(OCFile f) {
+        if (f != null && f.isDirectory() && f.getFileId() != -1) {
+            Vector<OCFile> ret = new Vector<OCFile>();
+
+            Uri req_uri = Uri.withAppendedPath(
+                    ProviderTableMeta.CONTENT_URI_DIR,
+                    String.valueOf(f.getFileId()));
+            Cursor c = null;
+
+            if (getContentProvider() != null) {
+                try {
+                    c = getContentProvider().query(req_uri, null,
+                            ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
+                            new String[] { mAccount.name }, null);
+                } catch (RemoteException e) {
+                    Log.e(TAG, e.getMessage());
+                    return ret;
+                }
+            } else {
+                c = getContentResolver().query(req_uri, null,
+                        ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
+                        new String[] { mAccount.name }, null);
+            }
+
+            if (c.moveToFirst()) {
+                do {
+                    OCFile child = createFileInstance(c);
+                    ret.add(child);
+                } while (c.moveToNext());
+            }
+
+            c.close();
+            return ret;
+        }
+        return null;
+    }
+
+    private boolean fileExists(String cmp_key, String value) {
+        Cursor c;
+        if (getContentResolver() != null) {
+            c = getContentResolver()
+                    .query(ProviderTableMeta.CONTENT_URI,
+                            null,
+                            cmp_key + "=? AND "
+                                    + ProviderTableMeta.FILE_ACCOUNT_OWNER
+                                    + "=?",
+                            new String[] { value, mAccount.name }, null);
+        } else {
+            try {
+                c = getContentProvider().query(
+                        ProviderTableMeta.CONTENT_URI,
+                        null,
+                        cmp_key + "=? AND "
+                                + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
+                        new String[] { value, mAccount.name }, null);
+            } catch (RemoteException e) {
+                Log.e(TAG,
+                        "Couldn't determine file existance, assuming non existance: "
+                                + e.getMessage());
+                return false;
+            }
+        }
+        boolean retval = c.moveToFirst();
+        c.close();
+        return retval;
+    }
+
+    private Cursor getCursorForValue(String key, String value) {
+        Cursor c = null;
+        if (getContentResolver() != null) {
+            c = getContentResolver()
+                    .query(ProviderTableMeta.CONTENT_URI,
+                            null,
+                            key + "=? AND "
+                                    + ProviderTableMeta.FILE_ACCOUNT_OWNER
+                                    + "=?",
+                            new String[] { value, mAccount.name }, null);
+        } else {
+            try {
+                c = getContentProvider().query(
+                        ProviderTableMeta.CONTENT_URI,
+                        null,
+                        key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
+                                + "=?", new String[] { value, mAccount.name },
+                        null);
+            } catch (RemoteException e) {
+                Log.e(TAG, "Could not get file details: " + e.getMessage());
+                c = null;
+            }
+        }
+        return c;
+    }
+
+    private OCFile createFileInstance(Cursor c) {
+        OCFile file = null;
+        if (c != null) {
+            file = new OCFile(c.getString(c
+                    .getColumnIndex(ProviderTableMeta.FILE_PATH)));
+            file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
+            file.setParentId(c.getLong(c
+                    .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
+            file.setStoragePath(c.getString(c
+                    .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
+            file.setMimetype(c.getString(c
+                    .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
+            file.setFileLength(c.getLong(c
+                    .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
+            file.setCreationTimestamp(c.getLong(c
+                    .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
+            file.setModificationTimestamp(c.getLong(c
+                    .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
+        }
+        return file;
     }
-    return file;
-  }
 
 }

+ 296 - 293
src/eu/alefzero/owncloud/datamodel/OCFile.java

@@ -25,297 +25,300 @@ import android.os.Parcelable;
 
 public class OCFile implements Parcelable {
 
-	public static final Parcelable.Creator<OCFile> CREATOR = new Parcelable.Creator<OCFile>() {
-		@Override
-		public OCFile createFromParcel(Parcel source) {
-			return new OCFile(source);
-		}
-
-		@Override
-		public OCFile[] newArray(int size) {
-			return new OCFile[size];
-		}
-	};
-	
-	private long mId;
-	private long mParentId;
-	private long mLength;
-	private long mCreationTimestamp;
-	private long mModifiedTimestamp;
-	private String mRemotePath;
-	private String mLocalPath;
-	private String mMimeType;
-	private boolean mNeedsUpdating;
-
-	/**
-	 * Create new {@link OCFile} with given path
-	 * 
-	 * @param path
-	 *            The remote path of the file
-	 */
-	public OCFile(String path) {
-		resetData();
-		mNeedsUpdating = false;
-		mRemotePath = path;
-	}
-	
-	/**
-	 * Reconstruct from parcel
-	 * @param source The source parcel
-	 */
-	private OCFile(Parcel source){
-		mId = source.readLong();
-		mParentId = source.readLong();
-		mLength = source.readLong();
-		mCreationTimestamp = source.readLong();
-		mModifiedTimestamp = source.readLong();
-		mRemotePath = source.readString();
-		mLocalPath = source.readString();
-		mMimeType = source.readString();
-		mNeedsUpdating = source.readInt() == 0;
-	}
-
-	/**
-	 * Gets the ID of the file
-	 * 
-	 * @return the file ID
-	 */
-	public long getFileId() {
-		return mId;
-	}
-
-	/**
-	 * Returns the path of the file
-	 * 
-	 * @return The path
-	 */
-	public String getPath() {
-		return mRemotePath;
-	}
-
-	/**
-	 * Can be used to check, whether or not this file exists in the database
-	 * already
-	 * 
-	 * @return true, if the file exists in the database
-	 */
-	public boolean fileExists() {
-		return mId != -1;
-	}
-
-	/**
-	 * Use this to find out if this file is a Directory
-	 * 
-	 * @return true if it is a directory
-	 */
-	public boolean isDirectory() {
-		return mMimeType != null && mMimeType.equals("DIR");
-	}
-
-	/**
-	 * Use this to check if this file is available locally
-	 * 
-	 * @return true if it is
-	 */
-	public boolean isDownloaded() {
-		return mLocalPath != null || mLocalPath.equals("");
-	}
-
-	/**
-	 * The path, where the file is stored locally
-	 * 
-	 * @return The local path to the file
-	 */
-	public String getStoragePath() {
-		return mLocalPath;
-	}
-
-	/**
-	 * Can be used to set the path where the file is stored
-	 * 
-	 * @param storage_path
-	 *            to set
-	 */
-	public void setStoragePath(String storage_path) {
-		mLocalPath = storage_path;
-	}
-
-	/**
-	 * Get a UNIX timestamp of the file creation time
-	 * 
-	 * @return A UNIX timestamp of the time that file was created
-	 */
-	public long getCreationTimestamp() {
-		return mCreationTimestamp;
-	}
-
-	/**
-	 * Set a UNIX timestamp of the time the file was created
-	 * 
-	 * @param creation_timestamp
-	 *            to set
-	 */
-	public void setCreationTimestamp(long creation_timestamp) {
-		mCreationTimestamp = creation_timestamp;
-	}
-
-	/**
-	 * Get a UNIX timestamp of the file modification time
-	 * 
-	 * @return A UNIX timestamp of the modification time
-	 */
-	public long getModificationTimestamp() {
-		return mModifiedTimestamp;
-	}
-
-	/**
-	 * Set a UNIX timestamp of the time the time the file was modified.
-	 * 
-	 * @param modification_timestamp
-	 *            to set
-	 */
-	public void setModificationTimestamp(long modification_timestamp) {
-		mModifiedTimestamp = modification_timestamp;
-	}
-
-	/**
-	 * Returns the filename and "/" for the root directory
-	 * 
-	 * @return The name of the file
-	 */
-	public String getFileName() {
-		if (mRemotePath != null) {
-			File f = new File(mRemotePath);
-			return f.getName().equals("") ? "/" : f.getName();
-		}
-		return null;
-	}
-
-	/**
-	 * Can be used to get the Mimetype
-	 * 
-	 * @return the Mimetype as a String
-	 */
-	public String getMimetype() {
-		return mMimeType;
-	}
-
-	/**
-	 * Adds a file to this directory. If this file is not a directory, an
-	 * exception gets thrown.
-	 * 
-	 * @param file
-	 *            to add
-	 * @throws IllegalStateException
-	 *             if you try to add a something and this is not a directory
-	 */
-	public void addFile(OCFile file) throws IllegalStateException {
-		if (isDirectory()) {
-			file.mParentId = mId;
-			mNeedsUpdating = true;
-			return;
-		}
-		throw new IllegalStateException(
-				"This is not a directory where you can add stuff to!");
-	}
-
-	/**
-	 * Used internally. Reset all file properties
-	 */
-	private void resetData() {
-		mId = -1;
-		mRemotePath = null;
-		mParentId = 0;
-		mLocalPath = null;
-		mMimeType = null;
-		mLength = 0;
-		mCreationTimestamp = 0;
-		mModifiedTimestamp = 0;
-	}
-
-	/**
-	 * Sets the ID of the file
-	 * 
-	 * @param file_id
-	 *            to set
-	 */
-	public void setFileId(long file_id) {
-		mId = file_id;
-	}
-
-	/**
-	 * Sets the Mime-Type of the
-	 * 
-	 * @param mimetype
-	 *            to set
-	 */
-	public void setMimetype(String mimetype) {
-		mMimeType = mimetype;
-	}
-
-	/**
-	 * Sets the ID of the parent folder
-	 * 
-	 * @param parent_id
-	 *            to set
-	 */
-	public void setParentId(long parent_id) {
-		mParentId = parent_id;
-	}
-
-	/**
-	 * Sets the file size in bytes
-	 * 
-	 * @param file_len
-	 *            to set
-	 */
-	public void setFileLength(long file_len) {
-		mLength = file_len;
-	}
-
-	/**
-	 * Returns the size of the file in bytes
-	 * 
-	 * @return The filesize in bytes
-	 */
-	public long getFileLength() {
-		return mLength;
-	}
-
-	/**
-	 * Returns the ID of the parent Folder
-	 * 
-	 * @return The ID
-	 */
-	public long getParentId() {
-		return mParentId;
-	}
-
-	/**
-	 * Check, if this file needs updating
-	 * 
-	 * @return
-	 */
-	public boolean needsUpdatingWhileSaving() {
-		return mNeedsUpdating;
-	}
-
-	@Override
-	public int describeContents() {
-		return this.hashCode();
-	}
-
-	@Override
-	public void writeToParcel(Parcel dest, int flags) {
-		dest.writeLong(mId);
-		dest.writeLong(mParentId);
-		dest.writeLong(mLength);
-		dest.writeLong(mCreationTimestamp);
-		dest.writeLong(mModifiedTimestamp);
-		dest.writeString(mRemotePath);
-		dest.writeString(mLocalPath);
-		dest.writeString(mMimeType);
-		dest.writeInt(mNeedsUpdating ? 0 : 1 ); // No writeBoolean method exists - yay :D
-	}
-	
+    public static final Parcelable.Creator<OCFile> CREATOR = new Parcelable.Creator<OCFile>() {
+        @Override
+        public OCFile createFromParcel(Parcel source) {
+            return new OCFile(source);
+        }
+
+        @Override
+        public OCFile[] newArray(int size) {
+            return new OCFile[size];
+        }
+    };
+
+    private long mId;
+    private long mParentId;
+    private long mLength;
+    private long mCreationTimestamp;
+    private long mModifiedTimestamp;
+    private String mRemotePath;
+    private String mLocalPath;
+    private String mMimeType;
+    private boolean mNeedsUpdating;
+
+    /**
+     * Create new {@link OCFile} with given path
+     * 
+     * @param path
+     *            The remote path of the file
+     */
+    public OCFile(String path) {
+        resetData();
+        mNeedsUpdating = false;
+        mRemotePath = path;
+    }
+
+    /**
+     * Reconstruct from parcel
+     * 
+     * @param source
+     *            The source parcel
+     */
+    private OCFile(Parcel source) {
+        mId = source.readLong();
+        mParentId = source.readLong();
+        mLength = source.readLong();
+        mCreationTimestamp = source.readLong();
+        mModifiedTimestamp = source.readLong();
+        mRemotePath = source.readString();
+        mLocalPath = source.readString();
+        mMimeType = source.readString();
+        mNeedsUpdating = source.readInt() == 0;
+    }
+
+    /**
+     * Gets the ID of the file
+     * 
+     * @return the file ID
+     */
+    public long getFileId() {
+        return mId;
+    }
+
+    /**
+     * Returns the path of the file
+     * 
+     * @return The path
+     */
+    public String getPath() {
+        return mRemotePath;
+    }
+
+    /**
+     * Can be used to check, whether or not this file exists in the database
+     * already
+     * 
+     * @return true, if the file exists in the database
+     */
+    public boolean fileExists() {
+        return mId != -1;
+    }
+
+    /**
+     * Use this to find out if this file is a Directory
+     * 
+     * @return true if it is a directory
+     */
+    public boolean isDirectory() {
+        return mMimeType != null && mMimeType.equals("DIR");
+    }
+
+    /**
+     * Use this to check if this file is available locally
+     * 
+     * @return true if it is
+     */
+    public boolean isDownloaded() {
+        return mLocalPath != null || mLocalPath.equals("");
+    }
+
+    /**
+     * The path, where the file is stored locally
+     * 
+     * @return The local path to the file
+     */
+    public String getStoragePath() {
+        return mLocalPath;
+    }
+
+    /**
+     * Can be used to set the path where the file is stored
+     * 
+     * @param storage_path
+     *            to set
+     */
+    public void setStoragePath(String storage_path) {
+        mLocalPath = storage_path;
+    }
+
+    /**
+     * Get a UNIX timestamp of the file creation time
+     * 
+     * @return A UNIX timestamp of the time that file was created
+     */
+    public long getCreationTimestamp() {
+        return mCreationTimestamp;
+    }
+
+    /**
+     * Set a UNIX timestamp of the time the file was created
+     * 
+     * @param creation_timestamp
+     *            to set
+     */
+    public void setCreationTimestamp(long creation_timestamp) {
+        mCreationTimestamp = creation_timestamp;
+    }
+
+    /**
+     * Get a UNIX timestamp of the file modification time
+     * 
+     * @return A UNIX timestamp of the modification time
+     */
+    public long getModificationTimestamp() {
+        return mModifiedTimestamp;
+    }
+
+    /**
+     * Set a UNIX timestamp of the time the time the file was modified.
+     * 
+     * @param modification_timestamp
+     *            to set
+     */
+    public void setModificationTimestamp(long modification_timestamp) {
+        mModifiedTimestamp = modification_timestamp;
+    }
+
+    /**
+     * Returns the filename and "/" for the root directory
+     * 
+     * @return The name of the file
+     */
+    public String getFileName() {
+        if (mRemotePath != null) {
+            File f = new File(mRemotePath);
+            return f.getName().equals("") ? "/" : f.getName();
+        }
+        return null;
+    }
+
+    /**
+     * Can be used to get the Mimetype
+     * 
+     * @return the Mimetype as a String
+     */
+    public String getMimetype() {
+        return mMimeType;
+    }
+
+    /**
+     * Adds a file to this directory. If this file is not a directory, an
+     * exception gets thrown.
+     * 
+     * @param file
+     *            to add
+     * @throws IllegalStateException
+     *             if you try to add a something and this is not a directory
+     */
+    public void addFile(OCFile file) throws IllegalStateException {
+        if (isDirectory()) {
+            file.mParentId = mId;
+            mNeedsUpdating = true;
+            return;
+        }
+        throw new IllegalStateException(
+                "This is not a directory where you can add stuff to!");
+    }
+
+    /**
+     * Used internally. Reset all file properties
+     */
+    private void resetData() {
+        mId = -1;
+        mRemotePath = null;
+        mParentId = 0;
+        mLocalPath = null;
+        mMimeType = null;
+        mLength = 0;
+        mCreationTimestamp = 0;
+        mModifiedTimestamp = 0;
+    }
+
+    /**
+     * Sets the ID of the file
+     * 
+     * @param file_id
+     *            to set
+     */
+    public void setFileId(long file_id) {
+        mId = file_id;
+    }
+
+    /**
+     * Sets the Mime-Type of the
+     * 
+     * @param mimetype
+     *            to set
+     */
+    public void setMimetype(String mimetype) {
+        mMimeType = mimetype;
+    }
+
+    /**
+     * Sets the ID of the parent folder
+     * 
+     * @param parent_id
+     *            to set
+     */
+    public void setParentId(long parent_id) {
+        mParentId = parent_id;
+    }
+
+    /**
+     * Sets the file size in bytes
+     * 
+     * @param file_len
+     *            to set
+     */
+    public void setFileLength(long file_len) {
+        mLength = file_len;
+    }
+
+    /**
+     * Returns the size of the file in bytes
+     * 
+     * @return The filesize in bytes
+     */
+    public long getFileLength() {
+        return mLength;
+    }
+
+    /**
+     * Returns the ID of the parent Folder
+     * 
+     * @return The ID
+     */
+    public long getParentId() {
+        return mParentId;
+    }
+
+    /**
+     * Check, if this file needs updating
+     * 
+     * @return
+     */
+    public boolean needsUpdatingWhileSaving() {
+        return mNeedsUpdating;
+    }
+
+    @Override
+    public int describeContents() {
+        return this.hashCode();
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeLong(mId);
+        dest.writeLong(mParentId);
+        dest.writeLong(mLength);
+        dest.writeLong(mCreationTimestamp);
+        dest.writeLong(mModifiedTimestamp);
+        dest.writeString(mRemotePath);
+        dest.writeString(mLocalPath);
+        dest.writeString(mMimeType);
+        dest.writeInt(mNeedsUpdating ? 0 : 1); // No writeBoolean method exists
+                                               // - yay :D
+    }
+
 }

+ 63 - 59
src/eu/alefzero/owncloud/db/DbHandler.java

@@ -29,74 +29,78 @@ import android.database.sqlite.SQLiteOpenHelper;
 
 /**
  * Custom database helper for ownCloud
+ * 
  * @author Bartek Przybylski
- *
+ * 
  */
 public class DbHandler {
-  private SQLiteDatabase mDB;
-  private OpenerHepler mHelper;
-  private final String mDatabaseName = "ownCloud";
-  private final String TABLE_SESSIONS = "sessions";
-  private final int mDatabaseVersion = 1;
-  
-  public DbHandler(Context context) {
-    mHelper = new OpenerHepler(context);
-    mDB = mHelper.getWritableDatabase();
-  }
-  
-  public Vector<OwnCloudSession> getSessionList() {
-    Cursor c = mDB.query(TABLE_SESSIONS, null, null, null, null, null, null);
-    Vector<OwnCloudSession> v = new Vector<OwnCloudSession>();
-    if (!c.moveToFirst()) {
-      return v;
+    private SQLiteDatabase mDB;
+    private OpenerHepler mHelper;
+    private final String mDatabaseName = "ownCloud";
+    private final String TABLE_SESSIONS = "sessions";
+    private final int mDatabaseVersion = 1;
+
+    public DbHandler(Context context) {
+        mHelper = new OpenerHepler(context);
+        mDB = mHelper.getWritableDatabase();
     }
-    while (!c.isAfterLast()) {
-      v.add(new OwnCloudSession(c.getString(c.getColumnIndex("sessionName")),
-                                c.getString(c.getColumnIndex("sessionUrl")),
-                                c.getInt(c.getColumnIndex("_id"))));
-      c.moveToNext();
+
+    public Vector<OwnCloudSession> getSessionList() {
+        Cursor c = mDB
+                .query(TABLE_SESSIONS, null, null, null, null, null, null);
+        Vector<OwnCloudSession> v = new Vector<OwnCloudSession>();
+        if (!c.moveToFirst()) {
+            return v;
+        }
+        while (!c.isAfterLast()) {
+            v.add(new OwnCloudSession(c.getString(c
+                    .getColumnIndex("sessionName")), c.getString(c
+                    .getColumnIndex("sessionUrl")), c.getInt(c
+                    .getColumnIndex("_id"))));
+            c.moveToNext();
+        }
+        c.close();
+        return v;
+    }
+
+    public void addSession(String sessionName, String uri) {
+        ContentValues cv = new ContentValues();
+        cv.put("sessionName", sessionName);
+        cv.put("sessionUrl", uri);
+        mDB.insert(TABLE_SESSIONS, null, cv);
     }
-    c.close();
-    return v;
-  }
-  
-  public void addSession(String sessionName, String uri) {
-    ContentValues cv = new ContentValues();
-    cv.put("sessionName", sessionName);
-    cv.put("sessionUrl", uri);
-    mDB.insert(TABLE_SESSIONS, null, cv);
-  }
-  
-  public void removeSessionWithId(int sessionId) {
-    mDB.delete(TABLE_SESSIONS, "_id = ?", new String[] {String.valueOf(sessionId)});
-  }
 
-  public void changeSessionFields(int id, String hostname, String uri) {
-    ContentValues cv = new ContentValues();
-    cv.put("sessionName", hostname);
-    cv.put("sessionUrl", uri);
-    mDB.update(TABLE_SESSIONS, cv, "_id = ?", new String[] {String.valueOf(id)});
-  }
-  
-  public void close() {
-    mDB.close();
-  }
-  
-  private class OpenerHepler extends SQLiteOpenHelper {
-    public OpenerHepler(Context context) {
-      super(context, mDatabaseName, null, mDatabaseVersion);
+    public void removeSessionWithId(int sessionId) {
+        mDB.delete(TABLE_SESSIONS, "_id = ?",
+                new String[] { String.valueOf(sessionId) });
     }
 
-    @Override
-    public void onCreate(SQLiteDatabase db) {
-      db.execSQL("CREATE TABLE " + TABLE_SESSIONS + " (" +
-                 " _id INTEGER PRIMARY KEY, " +
-                 " sessionName TEXT, " +
-                 " sessionUrl  TEXT);");
+    public void changeSessionFields(int id, String hostname, String uri) {
+        ContentValues cv = new ContentValues();
+        cv.put("sessionName", hostname);
+        cv.put("sessionUrl", uri);
+        mDB.update(TABLE_SESSIONS, cv, "_id = ?",
+                new String[] { String.valueOf(id) });
     }
 
-    @Override
-    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+    public void close() {
+        mDB.close();
+    }
+
+    private class OpenerHepler extends SQLiteOpenHelper {
+        public OpenerHepler(Context context) {
+            super(context, mDatabaseName, null, mDatabaseVersion);
+        }
+
+        @Override
+        public void onCreate(SQLiteDatabase db) {
+            db.execSQL("CREATE TABLE " + TABLE_SESSIONS + " ("
+                    + " _id INTEGER PRIMARY KEY, " + " sessionName TEXT, "
+                    + " sessionUrl  TEXT);");
+        }
+
+        @Override
+        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+        }
     }
-  }
 }

+ 33 - 32
src/eu/alefzero/owncloud/db/ProviderMeta.java

@@ -22,43 +22,44 @@ import android.provider.BaseColumns;
 
 /**
  * Meta-Class that holds various static field information
+ * 
  * @author Bartek Przybylski
- *
+ * 
  */
 public class ProviderMeta {
 
-  public static final String AUTHORITY_FILES = "org.owncloud";
-  public static final String DB_FILE = "owncloud.db";
-  public static final String DB_NAME = "filelist";
-  public static final int DB_VERSION = 1;
-  
-  private ProviderMeta() { }
-  
-  static public class ProviderTableMeta implements BaseColumns {
+    public static final String AUTHORITY_FILES = "org.owncloud";
+    public static final String DB_FILE = "owncloud.db";
     public static final String DB_NAME = "filelist";
-    public static final Uri CONTENT_URI =  
-      Uri.parse("content://" + AUTHORITY_FILES + "/");
-    public static final Uri CONTENT_URI_FILE =
-      Uri.parse("content://" + AUTHORITY_FILES + "/file");
-    public static final Uri CONTENT_URI_DIR =
-      Uri.parse("content://" + AUTHORITY_FILES + "/dir");
+    public static final int DB_VERSION = 1;
+
+    private ProviderMeta() {
+    }
+
+    static public class ProviderTableMeta implements BaseColumns {
+        public static final String DB_NAME = "filelist";
+        public static final Uri CONTENT_URI = Uri.parse("content://"
+                + AUTHORITY_FILES + "/");
+        public static final Uri CONTENT_URI_FILE = Uri.parse("content://"
+                + AUTHORITY_FILES + "/file");
+        public static final Uri CONTENT_URI_DIR = Uri.parse("content://"
+                + AUTHORITY_FILES + "/dir");
+
+        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.owncloud.file";
+        public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.owncloud.file";
+
+        public static final String FILE_PARENT = "parent";
+        public static final String FILE_NAME = "filename";
+        public static final String FILE_CREATION = "created";
+        public static final String FILE_MODIFIED = "modified";
+        public static final String FILE_CONTENT_LENGTH = "content_length";
+        public static final String FILE_CONTENT_TYPE = "content_type";
+        public static final String FILE_STORAGE_PATH = "media_path";
+        public static final String FILE_PATH = "path";
+        public static final String FILE_ACCOUNT_OWNER = "file_owner";
 
-    public static final String CONTENT_TYPE =
-      "vnd.android.cursor.dir/vnd.owncloud.file";
-    public static final String CONTENT_TYPE_ITEM =
-      "vnd.android.cursor.item/vnd.owncloud.file";
-    
-    public static final String FILE_PARENT = "parent";
-    public static final String FILE_NAME = "filename";
-    public static final String FILE_CREATION = "created";
-    public static final String FILE_MODIFIED = "modified";
-    public static final String FILE_CONTENT_LENGTH = "content_length";
-    public static final String FILE_CONTENT_TYPE = "content_type";
-    public static final String FILE_STORAGE_PATH = "media_path";
-    public static final String FILE_PATH = "path";
-    public static final String FILE_ACCOUNT_OWNER = "file_owner";
-    
-    public static final String DEFAULT_SORT_ORDER = FILE_NAME + " collate nocase asc";
+        public static final String DEFAULT_SORT_ORDER = FILE_NAME
+                + " collate nocase asc";
 
-  }
+    }
 }

+ 8 - 8
src/eu/alefzero/owncloud/extensions/ExtensionsAvailableActivity.java

@@ -6,12 +6,12 @@ import android.support.v4.app.FragmentManager;
 import com.actionbarsherlock.app.SherlockFragmentActivity;
 
 public class ExtensionsAvailableActivity extends SherlockFragmentActivity {
-  
-  @Override
-  public void onCreate(Bundle savedInstanceState) {
-    super.onCreate(savedInstanceState);
-    FragmentManager fm = getSupportFragmentManager();
-    ExtensionsAvailableDialog ead = new ExtensionsAvailableDialog();
-    ead.show(fm, "extensions_available_dialog");
-  }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        FragmentManager fm = getSupportFragmentManager();
+        ExtensionsAvailableDialog ead = new ExtensionsAvailableDialog();
+        ead.show(fm, "extensions_available_dialog");
+    }
 }

+ 31 - 29
src/eu/alefzero/owncloud/extensions/ExtensionsAvailableDialog.java

@@ -11,38 +11,40 @@ import android.view.ViewGroup;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 
-public class ExtensionsAvailableDialog extends DialogFragment implements OnClickListener {
+public class ExtensionsAvailableDialog extends DialogFragment implements
+        OnClickListener {
 
-  public ExtensionsAvailableDialog() { }
+    public ExtensionsAvailableDialog() {
+    }
+
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+        View view = inflater.inflate(R.layout.extensions_available_dialog,
+                container);
+        Button btnYes = (Button) view.findViewById(R.id.buttonYes);
+        Button btnNo = (Button) view.findViewById(R.id.buttonNo);
+        btnYes.setOnClickListener(this);
+        btnNo.setOnClickListener(this);
+        getDialog().setTitle(R.string.extensions_avail_title);
+        return view;
+    }
 
-  @Override
-  public View onCreateView(LayoutInflater inflater, ViewGroup container,
-      Bundle savedInstanceState) {
-    View view = inflater.inflate(R.layout.extensions_available_dialog, container);
-    Button btnYes = (Button) view.findViewById(R.id.buttonYes);
-    Button btnNo = (Button) view.findViewById(R.id.buttonNo);
-    btnYes.setOnClickListener(this);
-    btnNo.setOnClickListener(this);
-    getDialog().setTitle(R.string.extensions_avail_title);
-    return view;
-  }
-  
-  @Override
-  public void onClick(View v) {
-    switch (v.getId()) {
-      case R.id.buttonYes:
-        {
-          Intent i = new Intent(getActivity(), ExtensionsListActivity.class);
-          startActivity(i);
-          getActivity().finish();
+    @Override
+    public void onClick(View v) {
+        switch (v.getId()) {
+        case R.id.buttonYes: {
+            Intent i = new Intent(getActivity(), ExtensionsListActivity.class);
+            startActivity(i);
+            getActivity().finish();
+        }
+            break;
+        case R.id.buttonNo:
+            getActivity().finish();
+            break;
+        default:
+            Log.e("EAD", "Button with unknown id clicked " + v.getId());
         }
-        break;
-      case R.id.buttonNo:
-        getActivity().finish();
-        break;
-      default:
-        Log.e("EAD", "Button with unknown id clicked " + v.getId());
     }
-  }
 
 }

+ 101 - 84
src/eu/alefzero/owncloud/extensions/ExtensionsListActivity.java

@@ -22,95 +22,112 @@ import android.widget.SimpleAdapter;
 
 public class ExtensionsListActivity extends ListActivity {
 
-  private static final String packages_url = "http://alefzero.eu/a/packages.php";
-  
-  private Thread mGetterThread;
-  private final Handler mHandler = new Handler();  
-  
-  @Override
-  protected void onCreate(Bundle savedInstanceState) {
-    super.onCreate(savedInstanceState);
-    mGetterThread = new Thread(new JsonGetter());
-    mGetterThread.start();
-  }
-  
-  public void done(JSONArray a) {
-    LinkedList<HashMap<String, String>> ll = new LinkedList<HashMap<String,String>>();  
-    for (int i = 0; i < a.length(); ++i) {
-      try {
-        ExtensionApplicationEntry ela = new ExtensionApplicationEntry(((JSONObject)a.get(i)));
-        HashMap<String, String> ss = new HashMap<String, String>();
-        ss.put("NAME", ela.getName());
-        ss.put("DESC", ela.getDescription());
-        ll.add(ss);
-      } catch (JSONException e) {
-        e.printStackTrace();
-      }
-    }
-    setListAdapter(new SimpleAdapter(this,
-         ll,
-         R.layout.simple_list_item_2,
-         new String[] {"NAME", "DESC"},
-         new int[] {android.R.id.text1, android.R.id.text2}));
-    
-  }
-  
-  private class JsonGetter implements Runnable {
+    private static final String packages_url = "http://alefzero.eu/a/packages.php";
+
+    private Thread mGetterThread;
+    private final Handler mHandler = new Handler();
 
     @Override
-    public void run() {
-      HttpClient hc = new HttpClient();
-      GetMethod gm = new GetMethod(packages_url);
-      final JSONArray ar;
-      try {
-        hc.executeMethod(gm);
-        Log.e("ASD", gm.getResponseBodyAsString()+"");
-        ar = new JSONObject(gm.getResponseBodyAsString()).getJSONArray("apps");
-      } catch (Exception e) {
-        e.printStackTrace();
-        return;
-      }
-      
-      mHandler.post(new Runnable() {
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mGetterThread = new Thread(new JsonGetter());
+        mGetterThread.start();
+    }
+
+    public void done(JSONArray a) {
+        LinkedList<HashMap<String, String>> ll = new LinkedList<HashMap<String, String>>();
+        for (int i = 0; i < a.length(); ++i) {
+            try {
+                ExtensionApplicationEntry ela = new ExtensionApplicationEntry(
+                        ((JSONObject) a.get(i)));
+                HashMap<String, String> ss = new HashMap<String, String>();
+                ss.put("NAME", ela.getName());
+                ss.put("DESC", ela.getDescription());
+                ll.add(ss);
+            } catch (JSONException e) {
+                e.printStackTrace();
+            }
+        }
+        setListAdapter(new SimpleAdapter(this, ll, R.layout.simple_list_item_2,
+                new String[] { "NAME", "DESC" }, new int[] {
+                        android.R.id.text1, android.R.id.text2 }));
+
+    }
+
+    private class JsonGetter implements Runnable {
+
         @Override
         public void run() {
-          done(ar);
+            HttpClient hc = new HttpClient();
+            GetMethod gm = new GetMethod(packages_url);
+            final JSONArray ar;
+            try {
+                hc.executeMethod(gm);
+                Log.e("ASD", gm.getResponseBodyAsString() + "");
+                ar = new JSONObject(gm.getResponseBodyAsString())
+                        .getJSONArray("apps");
+            } catch (Exception e) {
+                e.printStackTrace();
+                return;
+            }
+
+            mHandler.post(new Runnable() {
+                @Override
+                public void run() {
+                    done(ar);
+                }
+            });
+
         }
-      });
-      
+
     }
-    
-  }
-  
-  private class ExtensionApplicationEntry {
-    private static final String APP_NAME    = "name";
-    private static final String APP_VERSION = "version";
-    private static final String APP_DESC    = "description";
-    private static final String APP_ICON    = "icon";
-    private static final String APP_URL     = "download";
-    private static final String APP_PLAYID  = "play_id";
-    
-    private String mName, mDescription, mIcon, mDownload, mPlayId;
-    private OwnCloudVersion mVersion;
-    
-    public ExtensionApplicationEntry(JSONObject appentry) {
-      try {
-        mName = appentry.getString(APP_NAME);
-        mDescription = appentry.getString(APP_DESC);
-        mIcon = appentry.getString(APP_ICON);
-        mDownload = appentry.getString(APP_URL);
-        mPlayId = appentry.getString(APP_PLAYID);
-        mVersion = new OwnCloudVersion(appentry.getString(APP_VERSION));
-      } catch (JSONException e) {
-        e.printStackTrace();
-      }
+
+    private class ExtensionApplicationEntry {
+        private static final String APP_NAME = "name";
+        private static final String APP_VERSION = "version";
+        private static final String APP_DESC = "description";
+        private static final String APP_ICON = "icon";
+        private static final String APP_URL = "download";
+        private static final String APP_PLAYID = "play_id";
+
+        private String mName, mDescription, mIcon, mDownload, mPlayId;
+        private OwnCloudVersion mVersion;
+
+        public ExtensionApplicationEntry(JSONObject appentry) {
+            try {
+                mName = appentry.getString(APP_NAME);
+                mDescription = appentry.getString(APP_DESC);
+                mIcon = appentry.getString(APP_ICON);
+                mDownload = appentry.getString(APP_URL);
+                mPlayId = appentry.getString(APP_PLAYID);
+                mVersion = new OwnCloudVersion(appentry.getString(APP_VERSION));
+            } catch (JSONException e) {
+                e.printStackTrace();
+            }
+        }
+
+        public String getName() {
+            return mName;
+        }
+
+        public String getDescription() {
+            return mDescription;
+        }
+
+        public String getIcon() {
+            return mIcon;
+        }
+
+        public String getDownload() {
+            return mDownload;
+        }
+
+        public String getPlayId() {
+            return mPlayId;
+        }
+
+        public OwnCloudVersion getVersion() {
+            return mVersion;
+        }
     }
-    
-    public String getName() { return mName; }
-    public String getDescription() { return mDescription; }
-    public String getIcon() { return mIcon; }
-    public String getDownload() { return mDownload; }
-    public String getPlayId() { return mPlayId; }
-    public OwnCloudVersion getVersion() { return mVersion; }
-  }
 }

+ 127 - 113
src/eu/alefzero/owncloud/files/services/FileUploader.java

@@ -27,127 +27,141 @@ import android.widget.Toast;
 
 public class FileUploader extends Service {
 
-  public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
-  public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
-  public static final String KEY_ACCOUNT = "ACCOUNT";
-  public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
-  
-  public static final int UPLOAD_SINGLE_FILE = 0;
-  public static final int UPLOAD_MULTIPLE_FILES = 1;
-  
-  private static final String TAG = "FileUploader"; 
-  private NotificationManager mNotificationManager;
-  private Looper mServiceLooper;
-  private ServiceHandler mServiceHandler;
-  private AccountManager mAccountManager;
-  private Account mAccount;
-  private String[] mLocalPaths, mRemotePaths;
-  private boolean mResult;
-  private int mUploadType;
-  
-  @Override
-  public IBinder onBind(Intent arg0) {
-    return null;
-  }
-  
-  private final class ServiceHandler extends Handler {
-    public ServiceHandler(Looper looper) {
-      super(looper);
-    }
+    public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
+    public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
+    public static final String KEY_ACCOUNT = "ACCOUNT";
+    public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
+
+    public static final int UPLOAD_SINGLE_FILE = 0;
+    public static final int UPLOAD_MULTIPLE_FILES = 1;
+
+    private static final String TAG = "FileUploader";
+    private NotificationManager mNotificationManager;
+    private Looper mServiceLooper;
+    private ServiceHandler mServiceHandler;
+    private AccountManager mAccountManager;
+    private Account mAccount;
+    private String[] mLocalPaths, mRemotePaths;
+    private boolean mResult;
+    private int mUploadType;
+
     @Override
-    public void handleMessage(Message msg) {
-      uploadFile();
-      stopSelf(msg.arg1);
+    public IBinder onBind(Intent arg0) {
+        return null;
     }
-  }
-  
-  @Override
-  public void onCreate() {
-    super.onCreate();
-    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
-    HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
-    thread.start();
-    mServiceLooper = thread.getLooper();
-    mServiceHandler = new ServiceHandler(mServiceLooper); 
-    mAccountManager = AccountManager.get(this);
-  }
-  
-  @Override
-  public int onStartCommand(Intent intent, int flags, int startId) {
-    if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
-      Log.e(TAG, "Not enought data in intent provided");
-      return Service.START_NOT_STICKY;
-    }
-    mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
-    mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
-    if (mUploadType == -1) {
-      Log.e(TAG, "Incorrect upload type provided");
-      return Service.START_NOT_STICKY;
+
+    private final class ServiceHandler extends Handler {
+        public ServiceHandler(Looper looper) {
+            super(looper);
+        }
+
+        @Override
+        public void handleMessage(Message msg) {
+            uploadFile();
+            stopSelf(msg.arg1);
+        }
     }
-    if (mUploadType == UPLOAD_SINGLE_FILE) {
-      mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
-      mRemotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
-    } else { // mUploadType == UPLOAD_MULTIPLE_FILES
-      mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
-      mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+        HandlerThread thread = new HandlerThread("FileUploaderThread",
+                Process.THREAD_PRIORITY_BACKGROUND);
+        thread.start();
+        mServiceLooper = thread.getLooper();
+        mServiceHandler = new ServiceHandler(mServiceLooper);
+        mAccountManager = AccountManager.get(this);
     }
-    
-    for (int i = 0; i < mRemotePaths.length; ++i)
-      mRemotePaths[i] = mRemotePaths[i].replace(' ', '+');
-    
-    if (mLocalPaths.length != mRemotePaths.length) {
-      Log.e(TAG, "Remote paths and local paths are not equal!");
-      return Service.START_NOT_STICKY;
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
+            Log.e(TAG, "Not enought data in intent provided");
+            return Service.START_NOT_STICKY;
+        }
+        mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
+        mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
+        if (mUploadType == -1) {
+            Log.e(TAG, "Incorrect upload type provided");
+            return Service.START_NOT_STICKY;
+        }
+        if (mUploadType == UPLOAD_SINGLE_FILE) {
+            mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
+            mRemotePaths = new String[] { intent
+                    .getStringExtra(KEY_REMOTE_FILE) };
+        } else { // mUploadType == UPLOAD_MULTIPLE_FILES
+            mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
+            mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
+        }
+
+        for (int i = 0; i < mRemotePaths.length; ++i)
+            mRemotePaths[i] = mRemotePaths[i].replace(' ', '+');
+
+        if (mLocalPaths.length != mRemotePaths.length) {
+            Log.e(TAG, "Remote paths and local paths are not equal!");
+            return Service.START_NOT_STICKY;
+        }
+
+        Message msg = mServiceHandler.obtainMessage();
+        msg.arg1 = startId;
+        mServiceHandler.sendMessage(msg);
+
+        return Service.START_NOT_STICKY;
     }
-      
-    Message msg = mServiceHandler.obtainMessage();
-    msg.arg1 = startId;
-    mServiceHandler.sendMessage(msg);
-    
-    return Service.START_NOT_STICKY;
-  }
-
-  public void run() {
-    if (mResult) {
-      Toast.makeText(this, "Upload successfull", Toast.LENGTH_SHORT).show();
-    } else {
-      Toast.makeText(this, "No i kupa", Toast.LENGTH_SHORT).show();
+
+    public void run() {
+        if (mResult) {
+            Toast.makeText(this, "Upload successfull", Toast.LENGTH_SHORT)
+                    .show();
+        } else {
+            Toast.makeText(this, "No i kupa", Toast.LENGTH_SHORT).show();
+        }
     }
-  }
 
     public void uploadFile() {
-      String baseUrl = mAccountManager.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL),
-             ocVerStr = mAccountManager.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
-      OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
-      String webdav_path = AccountUtils.getWebdavPath(ocVer);
-      Uri ocUri = Uri.parse(baseUrl + webdav_path);
-      String username = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
-      String password = mAccountManager.getPassword(mAccount);
-      Notification notification = new Notification(eu.alefzero.owncloud.R.drawable.icon,
-                                                   "Uploading...", System.currentTimeMillis());
-      notification.flags |= Notification.FLAG_ONGOING_EVENT;
-      notification.contentView = new RemoteViews(getApplicationContext().getPackageName(),
-                                                 R.layout.progressbar_layout);
-      notification.contentView.setProgressBar(R.id.status_progress, mLocalPaths.length-1, 0, false);
-      notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
-      
-      mNotificationManager.notify(42, notification);
-
-      WebdavClient wc = new WebdavClient(ocUri);
-      wc.setCredentials(username, password);
-      
-      for (int i = 0; i < mLocalPaths.length; ++i) {
-        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(mLocalPaths[i].substring(mLocalPaths[i].lastIndexOf('.')+1));
-        mResult = false;
-        if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
-          mResult |= true;
-        }
-        notification.contentView.setProgressBar(R.id.status_progress, mLocalPaths.length-1, i+1, false);
-        
+        String baseUrl = mAccountManager.getUserData(mAccount,
+                AccountAuthenticator.KEY_OC_BASE_URL), ocVerStr = mAccountManager
+                .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
+        OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
+        String webdav_path = AccountUtils.getWebdavPath(ocVer);
+        Uri ocUri = Uri.parse(baseUrl + webdav_path);
+        String username = mAccount.name.substring(0,
+                mAccount.name.lastIndexOf('@'));
+        String password = mAccountManager.getPassword(mAccount);
+        Notification notification = new Notification(
+                eu.alefzero.owncloud.R.drawable.icon, "Uploading...",
+                System.currentTimeMillis());
+        notification.flags |= Notification.FLAG_ONGOING_EVENT;
+        notification.contentView = new RemoteViews(getApplicationContext()
+                .getPackageName(), R.layout.progressbar_layout);
+        notification.contentView.setProgressBar(R.id.status_progress,
+                mLocalPaths.length - 1, 0, false);
+        notification.contentView.setImageViewResource(R.id.status_icon,
+                R.drawable.icon);
+
         mNotificationManager.notify(42, notification);
-      }
-      //notification.contentView.setProgressBar(R.id.status_progress, mLocalPaths.length-1, mLocalPaths.length-1, false);
-      mNotificationManager.cancel(42);
-      run();
+
+        WebdavClient wc = new WebdavClient(ocUri);
+        wc.setCredentials(username, password);
+
+        for (int i = 0; i < mLocalPaths.length; ++i) {
+            String mimeType = MimeTypeMap.getSingleton()
+                    .getMimeTypeFromExtension(
+                            mLocalPaths[i].substring(mLocalPaths[i]
+                                    .lastIndexOf('.') + 1));
+            mResult = false;
+            if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
+                mResult |= true;
+            }
+            notification.contentView.setProgressBar(R.id.status_progress,
+                    mLocalPaths.length - 1, i + 1, false);
+
+            mNotificationManager.notify(42, notification);
+        }
+        // notification.contentView.setProgressBar(R.id.status_progress,
+        // mLocalPaths.length-1, mLocalPaths.length-1, false);
+        mNotificationManager.cancel(42);
+        run();
     }
 }

+ 4 - 4
src/eu/alefzero/owncloud/files/services/OnUploadCompletedListener.java

@@ -1,8 +1,8 @@
 package eu.alefzero.owncloud.files.services;
 
 public interface OnUploadCompletedListener extends Runnable {
-  
-  public boolean getUploadResult();
-  
-  public void setUploadResult(boolean result);
+
+    public boolean getUploadResult();
+
+    public void setUploadResult(boolean result);
 }

+ 56 - 51
src/eu/alefzero/owncloud/location/LocationServiceLauncherReciever.java

@@ -28,56 +28,61 @@ import android.util.Log;
 
 public class LocationServiceLauncherReciever extends BroadcastReceiver {
 
-	private final String TAG = getClass().getSimpleName();
-	
-	@Override
-	public void onReceive(Context context, Intent intent) {
-		Intent deviceTrackingIntent = new Intent();
-		deviceTrackingIntent.setAction("eu.alefzero.owncloud.location.LocationUpdateService");
-		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
-		boolean trackDevice = preferences.getBoolean("enable_devicetracking", true);
-		
-		// Used in Preferences activity so that tracking is disabled or reenabled
-		if(intent.hasExtra("TRACKING_SETTING")){
-			trackDevice = intent.getBooleanExtra("TRACKING_SETTING", true);
-		}
-		
-		startOrStopDeviceTracking(context, trackDevice);
-	}
-	
-	/**
-	 * Used internally. Starts or stops the device tracking service
-	 * 
-	 * @param trackDevice
-	 *            true to start the service, false to stop it
-	 */
-	private void startOrStopDeviceTracking(Context context, boolean trackDevice) {
-		Intent deviceTrackingIntent = new Intent();
-		deviceTrackingIntent
-				.setAction("eu.alefzero.owncloud.location.LocationUpdateService");
-		if (!isDeviceTrackingServiceRunning(context) && trackDevice) {
-			Log.d(TAG, "Starting device tracker service");
-			context.startService(deviceTrackingIntent);
-		} else if (isDeviceTrackingServiceRunning(context) && !trackDevice) {
-			Log.d(TAG, "Stopping device tracker service");
-			context.stopService(deviceTrackingIntent);
-		}
-	}
-	
-	/**
-	 * Checks to see whether or not the LocationUpdateService is running
-	 * 
-	 * @return true, if it is. Otherwise false
-	 */
-	private boolean isDeviceTrackingServiceRunning(Context context) {
-		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
-		for (RunningServiceInfo service : manager
-				.getRunningServices(Integer.MAX_VALUE)) {
-			if (getClass().getName().equals(service.service.getClassName())) {
-				return true;
-			}
-		}
-		return false;
-	}
+    private final String TAG = getClass().getSimpleName();
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Intent deviceTrackingIntent = new Intent();
+        deviceTrackingIntent
+                .setAction("eu.alefzero.owncloud.location.LocationUpdateService");
+        SharedPreferences preferences = PreferenceManager
+                .getDefaultSharedPreferences(context);
+        boolean trackDevice = preferences.getBoolean("enable_devicetracking",
+                true);
+
+        // Used in Preferences activity so that tracking is disabled or
+        // reenabled
+        if (intent.hasExtra("TRACKING_SETTING")) {
+            trackDevice = intent.getBooleanExtra("TRACKING_SETTING", true);
+        }
+
+        startOrStopDeviceTracking(context, trackDevice);
+    }
+
+    /**
+     * Used internally. Starts or stops the device tracking service
+     * 
+     * @param trackDevice
+     *            true to start the service, false to stop it
+     */
+    private void startOrStopDeviceTracking(Context context, boolean trackDevice) {
+        Intent deviceTrackingIntent = new Intent();
+        deviceTrackingIntent
+                .setAction("eu.alefzero.owncloud.location.LocationUpdateService");
+        if (!isDeviceTrackingServiceRunning(context) && trackDevice) {
+            Log.d(TAG, "Starting device tracker service");
+            context.startService(deviceTrackingIntent);
+        } else if (isDeviceTrackingServiceRunning(context) && !trackDevice) {
+            Log.d(TAG, "Stopping device tracker service");
+            context.stopService(deviceTrackingIntent);
+        }
+    }
+
+    /**
+     * Checks to see whether or not the LocationUpdateService is running
+     * 
+     * @return true, if it is. Otherwise false
+     */
+    private boolean isDeviceTrackingServiceRunning(Context context) {
+        ActivityManager manager = (ActivityManager) context
+                .getSystemService(Context.ACTIVITY_SERVICE);
+        for (RunningServiceInfo service : manager
+                .getRunningServices(Integer.MAX_VALUE)) {
+            if (getClass().getName().equals(service.service.getClassName())) {
+                return true;
+            }
+        }
+        return false;
+    }
 
 }

+ 73 - 67
src/eu/alefzero/owncloud/location/LocationUpdateService.java

@@ -30,73 +30,79 @@ import android.preference.PreferenceManager;
 import android.util.Log;
 import android.widget.Toast;
 
-public class LocationUpdateService extends IntentService implements LocationListener {
-
-	public static final String TAG = "LocationUpdateService";
-	
-	private LocationManager mLocationManager;
-	private LocationProvider mLocationProvider;
-	private SharedPreferences mPreferences;
-	
-	public LocationUpdateService() {
-		super(TAG);
-	}
-
-	@Override
-	protected void onHandleIntent(Intent intent) {
-		mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
-		// Determine, how we can track the device
-		Criteria criteria = new Criteria();
-		criteria.setAccuracy(Criteria.ACCURACY_FINE);
-		criteria.setPowerRequirement(Criteria.POWER_LOW);
-		mLocationProvider = mLocationManager.getProvider(mLocationManager.getBestProvider(criteria, true));
-		
-		// Notify user if there is no way to track the device
-		if(mLocationProvider == null){
-			Toast.makeText(this, eu.alefzero.owncloud.R.string.location_no_provider, Toast.LENGTH_LONG);
-			stopSelf();
-			return;
-		}
-		
-		// Get preferences for device tracking
-		mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
-		boolean trackDevice = mPreferences.getBoolean("enable_devicetracking", true);
-		int updateIntervall = Integer.parseInt(mPreferences.getString("devicetracking_update_intervall", "30")) * 60 * 1000;
-		int distanceBetweenLocationChecks = 50;
-		
-		// If we do shall track the device -> Stop
-		if(!trackDevice){
-			Log.d(TAG, "Devicetracking is disabled");
-			stopSelf();
-			return;
-		}
-		
-		mLocationManager.requestLocationUpdates(mLocationProvider.getName(), updateIntervall, distanceBetweenLocationChecks, this);
-	}
-
-	@Override
-	public void onLocationChanged(Location location) {
-		Log.d(TAG, "Location changed: " + location);
-		
-	}
-
-	@Override
-	public void onProviderDisabled(String arg0) {
-		// TODO Auto-generated method stub
-		
-	}
-
-	@Override
-	public void onProviderEnabled(String arg0) {
-		// TODO Auto-generated method stub
-		
-	}
-
-	@Override
-	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
-		// TODO Auto-generated method stub
-		
-	}
+public class LocationUpdateService extends IntentService implements
+        LocationListener {
 
+    public static final String TAG = "LocationUpdateService";
+
+    private LocationManager mLocationManager;
+    private LocationProvider mLocationProvider;
+    private SharedPreferences mPreferences;
+
+    public LocationUpdateService() {
+        super(TAG);
+    }
+
+    @Override
+    protected void onHandleIntent(Intent intent) {
+        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
+        // Determine, how we can track the device
+        Criteria criteria = new Criteria();
+        criteria.setAccuracy(Criteria.ACCURACY_FINE);
+        criteria.setPowerRequirement(Criteria.POWER_LOW);
+        mLocationProvider = mLocationManager.getProvider(mLocationManager
+                .getBestProvider(criteria, true));
+
+        // Notify user if there is no way to track the device
+        if (mLocationProvider == null) {
+            Toast.makeText(this,
+                    eu.alefzero.owncloud.R.string.location_no_provider,
+                    Toast.LENGTH_LONG);
+            stopSelf();
+            return;
+        }
+
+        // Get preferences for device tracking
+        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
+        boolean trackDevice = mPreferences.getBoolean("enable_devicetracking",
+                true);
+        int updateIntervall = Integer.parseInt(mPreferences.getString(
+                "devicetracking_update_intervall", "30")) * 60 * 1000;
+        int distanceBetweenLocationChecks = 50;
+
+        // If we do shall track the device -> Stop
+        if (!trackDevice) {
+            Log.d(TAG, "Devicetracking is disabled");
+            stopSelf();
+            return;
+        }
+
+        mLocationManager.requestLocationUpdates(mLocationProvider.getName(),
+                updateIntervall, distanceBetweenLocationChecks, this);
+    }
+
+    @Override
+    public void onLocationChanged(Location location) {
+        Log.d(TAG, "Location changed: " + location);
+
+    }
+
+    @Override
+    public void onProviderDisabled(String arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void onProviderEnabled(String arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
+        // TODO Auto-generated method stub
+
+    }
 
 }

+ 165 - 157
src/eu/alefzero/owncloud/providers/FileContentProvider.java

@@ -37,176 +37,184 @@ import android.net.Uri;
 import android.text.TextUtils;
 
 /**
-* The ContentProvider for the ownCloud App.
-* @author Bartek Przybylski
-* 
-*/
+ * The ContentProvider for the ownCloud App.
+ * 
+ * @author Bartek Przybylski
+ * 
+ */
 public class FileContentProvider extends ContentProvider {
 
-  private DataBaseHelper mDbHelper;
-  
-  private static HashMap<String, String> mProjectionMap;
-  static {
-    mProjectionMap = new HashMap<String, String>();
-    mProjectionMap.put(ProviderTableMeta._ID,
-                       ProviderTableMeta._ID);
-    mProjectionMap.put(ProviderTableMeta.FILE_PARENT,
-                       ProviderTableMeta.FILE_PARENT);
-    mProjectionMap.put(ProviderTableMeta.FILE_PATH,
-                       ProviderTableMeta.FILE_PATH);
-    mProjectionMap.put(ProviderTableMeta.FILE_NAME,
-                       ProviderTableMeta.FILE_NAME);
-    mProjectionMap.put(ProviderTableMeta.FILE_CREATION,
-                       ProviderTableMeta.FILE_CREATION);
-    mProjectionMap.put(ProviderTableMeta.FILE_MODIFIED,
-                       ProviderTableMeta.FILE_MODIFIED);
-    mProjectionMap.put(ProviderTableMeta.FILE_CONTENT_LENGTH,
-                       ProviderTableMeta.FILE_CONTENT_LENGTH);
-    mProjectionMap.put(ProviderTableMeta.FILE_CONTENT_TYPE,
-                       ProviderTableMeta.FILE_CONTENT_TYPE);
-    mProjectionMap.put(ProviderTableMeta.FILE_STORAGE_PATH,
-                       ProviderTableMeta.FILE_STORAGE_PATH);
-  }
-  
-  private static final int SINGLE_FILE = 1;
-  private static final int DIRECTORY = 2;
-  private static final int ROOT_DIRECTORY = 3;
-  private static final UriMatcher mUriMatcher;
-  static {
-    mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
-    mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "/", ROOT_DIRECTORY);
-    mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "file/", SINGLE_FILE);
-    mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "file/#", SINGLE_FILE);
-    mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "dir/#", DIRECTORY);
-  }
-  
-  @Override
-  public int delete(Uri uri, String where, String[] whereArgs) {
-    SQLiteDatabase db = mDbHelper.getWritableDatabase();
-    int count = 0;
-    switch (mUriMatcher.match(uri)) {
-      case SINGLE_FILE:
-        count = db.delete(ProviderTableMeta.DB_NAME,
-                          ProviderTableMeta._ID + "=" + uri.getPathSegments().get(1)
-                          + (!TextUtils.isEmpty(where)?" AND (" + where +")" : ""),
-                          whereArgs);
-        break;
-      case ROOT_DIRECTORY:
-        count = db.delete(ProviderTableMeta.DB_NAME, where, whereArgs);
-        break;
-      default:
-        throw new IllegalArgumentException("Unknown uri: " + uri.toString());
-    }
-    getContext().getContentResolver().notifyChange(uri, null);
-    return count;
-  }
-
-  @Override
-  public String getType(Uri uri) {
-    switch (mUriMatcher.match(uri)) {
-      case ROOT_DIRECTORY:
-        return ProviderTableMeta.CONTENT_TYPE;
-      case SINGLE_FILE:
-        return ProviderTableMeta.CONTENT_TYPE_ITEM;
-      default:
-        throw new IllegalArgumentException("Unknown Uri id." + uri.toString());
+    private DataBaseHelper mDbHelper;
+
+    private static HashMap<String, String> mProjectionMap;
+    static {
+        mProjectionMap = new HashMap<String, String>();
+        mProjectionMap.put(ProviderTableMeta._ID, ProviderTableMeta._ID);
+        mProjectionMap.put(ProviderTableMeta.FILE_PARENT,
+                ProviderTableMeta.FILE_PARENT);
+        mProjectionMap.put(ProviderTableMeta.FILE_PATH,
+                ProviderTableMeta.FILE_PATH);
+        mProjectionMap.put(ProviderTableMeta.FILE_NAME,
+                ProviderTableMeta.FILE_NAME);
+        mProjectionMap.put(ProviderTableMeta.FILE_CREATION,
+                ProviderTableMeta.FILE_CREATION);
+        mProjectionMap.put(ProviderTableMeta.FILE_MODIFIED,
+                ProviderTableMeta.FILE_MODIFIED);
+        mProjectionMap.put(ProviderTableMeta.FILE_CONTENT_LENGTH,
+                ProviderTableMeta.FILE_CONTENT_LENGTH);
+        mProjectionMap.put(ProviderTableMeta.FILE_CONTENT_TYPE,
+                ProviderTableMeta.FILE_CONTENT_TYPE);
+        mProjectionMap.put(ProviderTableMeta.FILE_STORAGE_PATH,
+                ProviderTableMeta.FILE_STORAGE_PATH);
     }
-  }
 
-  @Override
-  public Uri insert(Uri uri, ContentValues values) {
-    if (mUriMatcher.match(uri) != SINGLE_FILE) {
-      throw new IllegalArgumentException("Unknown uri id: " + uri);
+    private static final int SINGLE_FILE = 1;
+    private static final int DIRECTORY = 2;
+    private static final int ROOT_DIRECTORY = 3;
+    private static final UriMatcher mUriMatcher;
+    static {
+        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
+        mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "/", ROOT_DIRECTORY);
+        mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "file/", SINGLE_FILE);
+        mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "file/#", SINGLE_FILE);
+        mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "dir/#", DIRECTORY);
     }
-    
-    SQLiteDatabase db = mDbHelper.getWritableDatabase();
-    long rowId = db.insert(ProviderTableMeta.DB_NAME, null, values);
-    if (rowId > 0) {
-      Uri insertedFileUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, rowId);
-      getContext().getContentResolver().notifyChange(insertedFileUri, null);
-      return insertedFileUri;
+
+    @Override
+    public int delete(Uri uri, String where, String[] whereArgs) {
+        SQLiteDatabase db = mDbHelper.getWritableDatabase();
+        int count = 0;
+        switch (mUriMatcher.match(uri)) {
+        case SINGLE_FILE:
+            count = db.delete(ProviderTableMeta.DB_NAME,
+                    ProviderTableMeta._ID
+                            + "="
+                            + uri.getPathSegments().get(1)
+                            + (!TextUtils.isEmpty(where) ? " AND (" + where
+                                    + ")" : ""), whereArgs);
+            break;
+        case ROOT_DIRECTORY:
+            count = db.delete(ProviderTableMeta.DB_NAME, where, whereArgs);
+            break;
+        default:
+            throw new IllegalArgumentException("Unknown uri: " + uri.toString());
+        }
+        getContext().getContentResolver().notifyChange(uri, null);
+        return count;
     }
-    throw new SQLException("ERROR " + uri);
-  }
-
-  @Override
-  public boolean onCreate() {
-    mDbHelper = new DataBaseHelper(getContext());
-    return true;
-  }
-
-  @Override
-  public Cursor query(Uri uri, String[] projection, String selection,
-      String[] selectionArgs, String sortOrder) {
-    SQLiteQueryBuilder sqlQuery = new SQLiteQueryBuilder();
-        
-    sqlQuery.setTables(ProviderTableMeta.DB_NAME);
-    sqlQuery.setProjectionMap(mProjectionMap);
-    
-    switch (mUriMatcher.match(uri)) {
-      case ROOT_DIRECTORY:
-        break;
-      case DIRECTORY:
-        sqlQuery.appendWhere(ProviderTableMeta.FILE_PARENT + "="+uri.getPathSegments().get(1));
-        break;
-      case SINGLE_FILE:
-        if (uri.getPathSegments().size() > 1) {
-          sqlQuery.appendWhere(ProviderTableMeta._ID + "=" +
-                               uri.getPathSegments().get(1));
+
+    @Override
+    public String getType(Uri uri) {
+        switch (mUriMatcher.match(uri)) {
+        case ROOT_DIRECTORY:
+            return ProviderTableMeta.CONTENT_TYPE;
+        case SINGLE_FILE:
+            return ProviderTableMeta.CONTENT_TYPE_ITEM;
+        default:
+            throw new IllegalArgumentException("Unknown Uri id."
+                    + uri.toString());
         }
-        break;
-      default:
-        throw new IllegalArgumentException("Unknown uri id: " + uri);
     }
-    
-    String order;
-    if (TextUtils.isEmpty(sortOrder)) {
-      order = ProviderTableMeta.DEFAULT_SORT_ORDER;
-    } else {
-      order = sortOrder;
+
+    @Override
+    public Uri insert(Uri uri, ContentValues values) {
+        if (mUriMatcher.match(uri) != SINGLE_FILE) {
+            throw new IllegalArgumentException("Unknown uri id: " + uri);
+        }
+
+        SQLiteDatabase db = mDbHelper.getWritableDatabase();
+        long rowId = db.insert(ProviderTableMeta.DB_NAME, null, values);
+        if (rowId > 0) {
+            Uri insertedFileUri = ContentUris.withAppendedId(
+                    ProviderTableMeta.CONTENT_URI_FILE, rowId);
+            getContext().getContentResolver().notifyChange(insertedFileUri,
+                    null);
+            return insertedFileUri;
+        }
+        throw new SQLException("ERROR " + uri);
     }
-    
-    SQLiteDatabase db = mDbHelper.getReadableDatabase();
-    Cursor c = sqlQuery.query(db, projection, selection, selectionArgs, null, null, order);
-    
-    c.setNotificationUri(getContext().getContentResolver(), uri);
-
-    return c;
-  }
-
-  @Override
-  public int update(Uri uri, ContentValues values, String selection,
-      String[] selectionArgs) {
-    return mDbHelper.getWritableDatabase().update(ProviderTableMeta.DB_NAME, values, selection, selectionArgs);
-  }
-
-  class DataBaseHelper extends SQLiteOpenHelper {
-
-    public DataBaseHelper(Context context) {
-      super(context, ProviderMeta.DB_NAME, null, ProviderMeta.DB_VERSION);
-      
+
+    @Override
+    public boolean onCreate() {
+        mDbHelper = new DataBaseHelper(getContext());
+        return true;
     }
-    
+
     @Override
-    public void onCreate(SQLiteDatabase db) {
-      db.execSQL("CREATE TABLE " + ProviderTableMeta.DB_NAME + "(" +
-                 ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +
-                 ProviderTableMeta.FILE_NAME + " TEXT, " +
-                 ProviderTableMeta.FILE_PATH + " TEXT, " +
-                 ProviderTableMeta.FILE_PARENT + " INTEGER, " +
-                 ProviderTableMeta.FILE_CREATION + " INTEGER, " +
-                 ProviderTableMeta.FILE_MODIFIED + " INTEGER, " +
-                 ProviderTableMeta.FILE_CONTENT_TYPE + " TEXT, " +
-                 ProviderTableMeta.FILE_CONTENT_LENGTH + " INTEGER, " +
-                 ProviderTableMeta.FILE_STORAGE_PATH + " TEXT, " +
-                 ProviderTableMeta.FILE_ACCOUNT_OWNER + " TEXT);");
+    public Cursor query(Uri uri, String[] projection, String selection,
+            String[] selectionArgs, String sortOrder) {
+        SQLiteQueryBuilder sqlQuery = new SQLiteQueryBuilder();
+
+        sqlQuery.setTables(ProviderTableMeta.DB_NAME);
+        sqlQuery.setProjectionMap(mProjectionMap);
+
+        switch (mUriMatcher.match(uri)) {
+        case ROOT_DIRECTORY:
+            break;
+        case DIRECTORY:
+            sqlQuery.appendWhere(ProviderTableMeta.FILE_PARENT + "="
+                    + uri.getPathSegments().get(1));
+            break;
+        case SINGLE_FILE:
+            if (uri.getPathSegments().size() > 1) {
+                sqlQuery.appendWhere(ProviderTableMeta._ID + "="
+                        + uri.getPathSegments().get(1));
+            }
+            break;
+        default:
+            throw new IllegalArgumentException("Unknown uri id: " + uri);
+        }
+
+        String order;
+        if (TextUtils.isEmpty(sortOrder)) {
+            order = ProviderTableMeta.DEFAULT_SORT_ORDER;
+        } else {
+            order = sortOrder;
+        }
+
+        SQLiteDatabase db = mDbHelper.getReadableDatabase();
+        Cursor c = sqlQuery.query(db, projection, selection, selectionArgs,
+                null, null, order);
+
+        c.setNotificationUri(getContext().getContentResolver(), uri);
+
+        return c;
     }
 
     @Override
-    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-      
+    public int update(Uri uri, ContentValues values, String selection,
+            String[] selectionArgs) {
+        return mDbHelper.getWritableDatabase().update(
+                ProviderTableMeta.DB_NAME, values, selection, selectionArgs);
+    }
+
+    class DataBaseHelper extends SQLiteOpenHelper {
+
+        public DataBaseHelper(Context context) {
+            super(context, ProviderMeta.DB_NAME, null, ProviderMeta.DB_VERSION);
+
+        }
+
+        @Override
+        public void onCreate(SQLiteDatabase db) {
+            db.execSQL("CREATE TABLE " + ProviderTableMeta.DB_NAME + "("
+                    + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, "
+                    + ProviderTableMeta.FILE_NAME + " TEXT, "
+                    + ProviderTableMeta.FILE_PATH + " TEXT, "
+                    + ProviderTableMeta.FILE_PARENT + " INTEGER, "
+                    + ProviderTableMeta.FILE_CREATION + " INTEGER, "
+                    + ProviderTableMeta.FILE_MODIFIED + " INTEGER, "
+                    + ProviderTableMeta.FILE_CONTENT_TYPE + " TEXT, "
+                    + ProviderTableMeta.FILE_CONTENT_LENGTH + " INTEGER, "
+                    + ProviderTableMeta.FILE_STORAGE_PATH + " TEXT, "
+                    + ProviderTableMeta.FILE_ACCOUNT_OWNER + " TEXT);");
+        }
+
+        @Override
+        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+
+        }
+
     }
-    
-  }
-  
+
 }

+ 119 - 115
src/eu/alefzero/owncloud/syncadapter/AbstractOwnCloudSyncAdapter.java

@@ -47,119 +47,123 @@ import eu.alefzero.webdav.WebdavClient;
  * @author sassman
  * 
  */
-public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAdapter {
-
-	private AccountManager accountManager;
-	private Account account;
-	private ContentProviderClient contentProvider;
-	private Date lastUpdated;
-	private DataStorageManager mStoreManager;
-
-	private WebdavClient mClient = null;
-
-	public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {
-		super(context, autoInitialize);
-		this.setAccountManager(AccountManager.get(context));
-	}
-
-	public AccountManager getAccountManager() {
-		return accountManager;
-	}
-
-	public void setAccountManager(AccountManager accountManager) {
-		this.accountManager = accountManager;
-	}
-
-	public Account getAccount() {
-		return account;
-	}
-
-	public void setAccount(Account account) {
-		this.account = account;
-	}
-
-	public ContentProviderClient getContentProvider() {
-		return contentProvider;
-	}
-
-	public void setContentProvider(ContentProviderClient contentProvider) {
-		this.contentProvider = contentProvider;
-	}
-
-	public Date getLastUpdated() {
-		return lastUpdated;
-	}
-
-	public void setLastUpdated(Date lastUpdated) {
-		this.lastUpdated = lastUpdated;
-	}
-
-	public void setStorageManager(DataStorageManager storage_manager) {
-	  mStoreManager = storage_manager;
-	}
-	
-	public DataStorageManager getStorageManager() {
-	  return mStoreManager;
-	}
-	
-	protected ConnectionKeepAliveStrategy getKeepAliveStrategy() {
-		return new ConnectionKeepAliveStrategy() {
-			public long getKeepAliveDuration(HttpResponse response,
-					HttpContext context) {
-				// Change keep alive straategy basing on response: ie
-				// forbidden/not found/etc
-				// should have keep alive 0
-				// default return: 5s
-				int statusCode = response.getStatusLine().getStatusCode();
-
-				// HTTP 400, 500 Errors as well as HTTP 118 - Connection timed
-				// out
-				if ((statusCode >= 400 && statusCode <= 418)
-						|| (statusCode >= 421 && statusCode <= 426)
-						|| (statusCode >= 500 && statusCode <= 510)
-						|| statusCode == 118) {
-					return 0;
-				}
-
-				return 5 * 1000;
-			}
-		};
-	}
-
-	protected HttpResponse fireRawRequest(HttpRequest query)
-			throws ClientProtocolException, OperationCanceledException,
-			AuthenticatorException, IOException {
-		/*BasicHttpContext httpContext = new BasicHttpContext();
-		BasicScheme basicAuth = new BasicScheme();
-		httpContext.setAttribute("preemptive-auth", basicAuth);
-
-		HttpResponse response = getClient().execute(mHost, query, httpContext);*/
-		return null;
-	}
-
-	protected Uri getUri() {
-		return Uri.parse(this.getAccountManager().getUserData(getAccount(),
-				AccountAuthenticator.KEY_OC_URL));
-	}
-
-	protected WebdavClient getClient() throws OperationCanceledException,
-			AuthenticatorException, IOException {
-		if (mClient == null) {
-			String username = getAccount().name.split("@")[0];
-			String password = this.getAccountManager().blockingGetAuthToken(
-					getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);
-			if (this.getAccountManager().getUserData(getAccount(),
-					AccountAuthenticator.KEY_OC_URL) == null) {
-				throw new UnknownHostException();
-			}
-			Uri uri = getUri();
-
-			mClient = new WebdavClient(uri);
-			mClient.setCredentials(username, password);
-			mClient.allowUnsignedCertificates();
-			//mHost = mClient.getTargetHost();
-		}
-
-		return mClient;
-	}
+public abstract class AbstractOwnCloudSyncAdapter extends
+        AbstractThreadedSyncAdapter {
+
+    private AccountManager accountManager;
+    private Account account;
+    private ContentProviderClient contentProvider;
+    private Date lastUpdated;
+    private DataStorageManager mStoreManager;
+
+    private WebdavClient mClient = null;
+
+    public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {
+        super(context, autoInitialize);
+        this.setAccountManager(AccountManager.get(context));
+    }
+
+    public AccountManager getAccountManager() {
+        return accountManager;
+    }
+
+    public void setAccountManager(AccountManager accountManager) {
+        this.accountManager = accountManager;
+    }
+
+    public Account getAccount() {
+        return account;
+    }
+
+    public void setAccount(Account account) {
+        this.account = account;
+    }
+
+    public ContentProviderClient getContentProvider() {
+        return contentProvider;
+    }
+
+    public void setContentProvider(ContentProviderClient contentProvider) {
+        this.contentProvider = contentProvider;
+    }
+
+    public Date getLastUpdated() {
+        return lastUpdated;
+    }
+
+    public void setLastUpdated(Date lastUpdated) {
+        this.lastUpdated = lastUpdated;
+    }
+
+    public void setStorageManager(DataStorageManager storage_manager) {
+        mStoreManager = storage_manager;
+    }
+
+    public DataStorageManager getStorageManager() {
+        return mStoreManager;
+    }
+
+    protected ConnectionKeepAliveStrategy getKeepAliveStrategy() {
+        return new ConnectionKeepAliveStrategy() {
+            public long getKeepAliveDuration(HttpResponse response,
+                    HttpContext context) {
+                // Change keep alive straategy basing on response: ie
+                // forbidden/not found/etc
+                // should have keep alive 0
+                // default return: 5s
+                int statusCode = response.getStatusLine().getStatusCode();
+
+                // HTTP 400, 500 Errors as well as HTTP 118 - Connection timed
+                // out
+                if ((statusCode >= 400 && statusCode <= 418)
+                        || (statusCode >= 421 && statusCode <= 426)
+                        || (statusCode >= 500 && statusCode <= 510)
+                        || statusCode == 118) {
+                    return 0;
+                }
+
+                return 5 * 1000;
+            }
+        };
+    }
+
+    protected HttpResponse fireRawRequest(HttpRequest query)
+            throws ClientProtocolException, OperationCanceledException,
+            AuthenticatorException, IOException {
+        /*
+         * BasicHttpContext httpContext = new BasicHttpContext(); BasicScheme
+         * basicAuth = new BasicScheme();
+         * httpContext.setAttribute("preemptive-auth", basicAuth);
+         * 
+         * HttpResponse response = getClient().execute(mHost, query,
+         * httpContext);
+         */
+        return null;
+    }
+
+    protected Uri getUri() {
+        return Uri.parse(this.getAccountManager().getUserData(getAccount(),
+                AccountAuthenticator.KEY_OC_URL));
+    }
+
+    protected WebdavClient getClient() throws OperationCanceledException,
+            AuthenticatorException, IOException {
+        if (mClient == null) {
+            String username = getAccount().name.split("@")[0];
+            String password = this.getAccountManager().blockingGetAuthToken(
+                    getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);
+            if (this.getAccountManager().getUserData(getAccount(),
+                    AccountAuthenticator.KEY_OC_URL) == null) {
+                throw new UnknownHostException();
+            }
+            Uri uri = getUri();
+
+            mClient = new WebdavClient(uri);
+            mClient.setCredentials(username, password);
+            mClient.allowUnsignedCertificates();
+            // mHost = mClient.getTargetHost();
+        }
+
+        return mClient;
+    }
 }

+ 72 - 64
src/eu/alefzero/owncloud/syncadapter/ContactSyncAdapter.java

@@ -26,73 +26,81 @@ import android.provider.ContactsContract;
 import android.util.Log;
 
 public class ContactSyncAdapter extends AbstractOwnCloudSyncAdapter {
-  private String mAddrBookUri;
-  
-  public ContactSyncAdapter(Context context, boolean autoInitialize) {
-    super(context, autoInitialize);
-    mAddrBookUri = null;
-  }
+    private String mAddrBookUri;
 
-  @Override
-  public void onPerformSync(Account account, Bundle extras, String authority,
-      ContentProviderClient provider, SyncResult syncResult) {
-    setAccount(account);
-    setContentProvider(provider);
-    Cursor c = getLocalContacts(false);
-    if (c.moveToFirst()) {
-      do {
-      String lookup = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
-      String a = getAddressBookUri();
-      String uri = a + lookup + ".vcf";
-      FileInputStream f;
-      try {
-        f = getContactVcard(lookup);
-        HttpPut query = new HttpPut(uri);
-        byte[] b = new byte[f.available()];
-        f.read(b);
-        query.setEntity(new ByteArrayEntity(b));
-        HttpResponse response = fireRawRequest(query);
-      } catch (IOException e) {
-        e.printStackTrace();
-        return;
-      } catch (OperationCanceledException e) {
-        // TODO Auto-generated catch block
-        e.printStackTrace();
-      } catch (AuthenticatorException e) {
-        // TODO Auto-generated catch block
-        e.printStackTrace();
-      }
-      }while (c.moveToNext());
-      //} while (c.moveToNext());
+    public ContactSyncAdapter(Context context, boolean autoInitialize) {
+        super(context, autoInitialize);
+        mAddrBookUri = null;
     }
 
-  }
+    @Override
+    public void onPerformSync(Account account, Bundle extras, String authority,
+            ContentProviderClient provider, SyncResult syncResult) {
+        setAccount(account);
+        setContentProvider(provider);
+        Cursor c = getLocalContacts(false);
+        if (c.moveToFirst()) {
+            do {
+                String lookup = c.getString(c
+                        .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
+                String a = getAddressBookUri();
+                String uri = a + lookup + ".vcf";
+                FileInputStream f;
+                try {
+                    f = getContactVcard(lookup);
+                    HttpPut query = new HttpPut(uri);
+                    byte[] b = new byte[f.available()];
+                    f.read(b);
+                    query.setEntity(new ByteArrayEntity(b));
+                    HttpResponse response = fireRawRequest(query);
+                } catch (IOException e) {
+                    e.printStackTrace();
+                    return;
+                } catch (OperationCanceledException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                } catch (AuthenticatorException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            } while (c.moveToNext());
+            // } while (c.moveToNext());
+        }
 
-  private String getAddressBookUri() {
-    if (mAddrBookUri != null) return mAddrBookUri;
+    }
+
+    private String getAddressBookUri() {
+        if (mAddrBookUri != null)
+            return mAddrBookUri;
+
+        AccountManager am = getAccountManager();
+        String uri = am.getUserData(getAccount(),
+                AccountAuthenticator.KEY_OC_URL).replace(
+                AccountUtils.WEBDAV_PATH_2_0, AccountUtils.CARDDAV_PATH_2_0);
+        uri += "/addressbooks/"
+                + getAccount().name.substring(0,
+                        getAccount().name.lastIndexOf('@')) + "/default/";
+        mAddrBookUri = uri;
+        return uri;
+    }
+
+    private FileInputStream getContactVcard(String lookupKey)
+            throws IOException {
+        Uri uri = Uri.withAppendedPath(
+                ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
+        AssetFileDescriptor fd = getContext().getContentResolver()
+                .openAssetFileDescriptor(uri, "r");
+        return fd.createInputStream();
+    }
+
+    private Cursor getLocalContacts(boolean include_hidden_contacts) {
+        return getContext().getContentResolver().query(
+                ContactsContract.Contacts.CONTENT_URI,
+                new String[] { ContactsContract.Contacts._ID,
+                        ContactsContract.Contacts.LOOKUP_KEY },
+                ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?",
+                new String[] { (include_hidden_contacts ? "0" : "1") },
+                ContactsContract.Contacts._ID + " DESC");
+    }
 
-    AccountManager am = getAccountManager();
-    String uri = am.getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL)
-                   .replace(AccountUtils.WEBDAV_PATH_2_0, AccountUtils.CARDDAV_PATH_2_0);
-    uri += "/addressbooks/" + getAccount().name.substring(0, getAccount().name.lastIndexOf('@'))
-        + "/default/";
-    mAddrBookUri = uri;
-    return uri;
-  }
-  
-  private FileInputStream getContactVcard(String lookupKey) throws IOException {
-    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
-    AssetFileDescriptor fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
-    return fd.createInputStream();
-  }
-  
-  private Cursor getLocalContacts(boolean include_hidden_contacts) {
-    return getContext().getContentResolver().query(
-        ContactsContract.Contacts.CONTENT_URI,
-        new String[] {ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY},
-        ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?",
-        new String[]{ (include_hidden_contacts?"0":"1")},
-        ContactsContract.Contacts._ID + " DESC");
-  }
-  
 }

+ 17 - 16
src/eu/alefzero/owncloud/syncadapter/ContactSyncService.java

@@ -5,21 +5,22 @@ import android.content.Intent;
 import android.os.IBinder;
 
 public class ContactSyncService extends Service {
-  private static final Object syncAdapterLock = new Object();
-  private static AbstractOwnCloudSyncAdapter mSyncAdapter = null;
-  
-  @Override
-  public void onCreate() {
-      synchronized (syncAdapterLock) {
-          if (mSyncAdapter == null) {
-              mSyncAdapter = new ContactSyncAdapter(getApplicationContext(), true);
-          }
-      }
-  }
-  
-  @Override
-  public IBinder onBind(Intent arg0) {
-    return mSyncAdapter.getSyncAdapterBinder();
-  }
+    private static final Object syncAdapterLock = new Object();
+    private static AbstractOwnCloudSyncAdapter mSyncAdapter = null;
+
+    @Override
+    public void onCreate() {
+        synchronized (syncAdapterLock) {
+            if (mSyncAdapter == null) {
+                mSyncAdapter = new ContactSyncAdapter(getApplicationContext(),
+                        true);
+            }
+        }
+    }
+
+    @Override
+    public IBinder onBind(Intent arg0) {
+        return mSyncAdapter.getSyncAdapterBinder();
+    }
 
 }

+ 87 - 87
src/eu/alefzero/owncloud/syncadapter/FileSyncAdapter.java

@@ -45,96 +45,96 @@ import eu.alefzero.webdav.WebdavEntry;
  */
 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
 
-	public FileSyncAdapter(Context context, boolean autoInitialize) {
-		super(context, autoInitialize);
-	}
-	
-	@Override
-	public synchronized void onPerformSync(
-			Account account, 
-			Bundle extras, 
-			String authority, 
-			ContentProviderClient provider, 
-			SyncResult syncResult) {
+    public FileSyncAdapter(Context context, boolean autoInitialize) {
+        super(context, autoInitialize);
+    }
+
+    @Override
+    public synchronized void onPerformSync(Account account, Bundle extras,
+            String authority, ContentProviderClient provider,
+            SyncResult syncResult) {
+
+        this.setAccount(account);
+        this.setContentProvider(provider);
+        this.setStorageManager(new FileDataStorageManager(account,
+                getContentProvider()));
+
+        Log.d("ASD", "syncing owncloud account " + account.name);
+
+        Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
+        i.putExtra(FileSyncService.IN_PROGRESS, true);
+        i.putExtra(FileSyncService.ACCOUNT_NAME, account.name);
+        getContext().sendStickyBroadcast(i);
 
-			this.setAccount(account);
-			this.setContentProvider(provider);
-			this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
+        PropFindMethod query;
+        try {
+            Log.e("ASD", getUri().toString());
+            query = new PropFindMethod(getUri().toString() + "/");
+            getClient().executeMethod(query);
+            MultiStatus resp = null;
+            resp = query.getResponseBodyAsMultiStatus();
 
-			Log.d("ASD", "syncing owncloud account " + account.name);
-			
-			Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
-			i.putExtra(FileSyncService.IN_PROGRESS, true);
-			i.putExtra(FileSyncService.ACCOUNT_NAME, account.name);
-			getContext().sendStickyBroadcast(i);
-			
-			PropFindMethod query;
-      try {
-        Log.e("ASD", getUri().toString());
-        query = new PropFindMethod(getUri().toString()+"/");
-        getClient().executeMethod(query);
-        MultiStatus resp = null;
-        resp = query.getResponseBodyAsMultiStatus();
-        
-        if (resp.getResponses().length > 0) {
-          WebdavEntry we = new WebdavEntry(resp.getResponses()[0]);
-          OCFile file = fillOCFile(we);
-          file.setParentId(0);
-          getStorageManager().saveFile(file);
-          fetchData(getUri().toString(), syncResult, file.getFileId());
+            if (resp.getResponses().length > 0) {
+                WebdavEntry we = new WebdavEntry(resp.getResponses()[0]);
+                OCFile file = fillOCFile(we);
+                file.setParentId(0);
+                getStorageManager().saveFile(file);
+                fetchData(getUri().toString(), syncResult, file.getFileId());
+            }
+        } catch (OperationCanceledException e) {
+            e.printStackTrace();
+        } catch (AuthenticatorException e) {
+            syncResult.stats.numAuthExceptions++;
+            e.printStackTrace();
+        } catch (IOException e) {
+            syncResult.stats.numIoExceptions++;
+            e.printStackTrace();
+        } catch (DavException e) {
+            syncResult.stats.numIoExceptions++;
+            e.printStackTrace();
         }
-      } catch (OperationCanceledException e) {
-        e.printStackTrace();
-      } catch (AuthenticatorException e) {
-        syncResult.stats.numAuthExceptions++;
-        e.printStackTrace();
-      } catch (IOException e) {
-        syncResult.stats.numIoExceptions++;
-        e.printStackTrace();
-      } catch (DavException e) {
-        syncResult.stats.numIoExceptions++;
-        e.printStackTrace();
-      }
-      i.putExtra(FileSyncService.IN_PROGRESS, false);
-      getContext().sendStickyBroadcast(i);
-	}
+        i.putExtra(FileSyncService.IN_PROGRESS, false);
+        getContext().sendStickyBroadcast(i);
+    }
 
-  private void fetchData(String uri, SyncResult syncResult, long parentId) {
-    try {
-      PropFindMethod query = new PropFindMethod(uri);
-      getClient().executeMethod(query);
-      MultiStatus resp = null;
-      resp = query.getResponseBodyAsMultiStatus();
-      for (int i = 1; i < resp.getResponses().length; ++i) {
-        WebdavEntry we = new WebdavEntry(resp.getResponses()[i]);
-        OCFile file = fillOCFile(we);
-        file.setParentId(parentId);
-        getStorageManager().saveFile(file);
-        if (parentId == 0) parentId = file.getFileId();
-        if (we.contentType().equals("DIR"))
-          fetchData(getUri().toString() + we.path(), syncResult, file.getFileId());
-      }
-    } catch (OperationCanceledException e) {
-      e.printStackTrace();
-    } catch (AuthenticatorException e) {
-      syncResult.stats.numAuthExceptions++;
-      e.printStackTrace();
-    } catch (IOException e) {
-      syncResult.stats.numIoExceptions++;
-      e.printStackTrace();
-    } catch (DavException e) {
-      syncResult.stats.numIoExceptions++;
-      e.printStackTrace();
+    private void fetchData(String uri, SyncResult syncResult, long parentId) {
+        try {
+            PropFindMethod query = new PropFindMethod(uri);
+            getClient().executeMethod(query);
+            MultiStatus resp = null;
+            resp = query.getResponseBodyAsMultiStatus();
+            for (int i = 1; i < resp.getResponses().length; ++i) {
+                WebdavEntry we = new WebdavEntry(resp.getResponses()[i]);
+                OCFile file = fillOCFile(we);
+                file.setParentId(parentId);
+                getStorageManager().saveFile(file);
+                if (parentId == 0)
+                    parentId = file.getFileId();
+                if (we.contentType().equals("DIR"))
+                    fetchData(getUri().toString() + we.path(), syncResult,
+                            file.getFileId());
+            }
+        } catch (OperationCanceledException e) {
+            e.printStackTrace();
+        } catch (AuthenticatorException e) {
+            syncResult.stats.numAuthExceptions++;
+            e.printStackTrace();
+        } catch (IOException e) {
+            syncResult.stats.numIoExceptions++;
+            e.printStackTrace();
+        } catch (DavException e) {
+            syncResult.stats.numIoExceptions++;
+            e.printStackTrace();
+        }
     }
-  }
-  
-  private OCFile fillOCFile(WebdavEntry we) {
-    OCFile file = new OCFile(we.path());
-    file.setCreationTimestamp(we.createTimestamp());
-    file.setFileLength(we.contentLength());
-    file.setMimetype(we.contentType());
-    file.setModificationTimestamp(we.modifiedTimesamp());
-    return file;
-  }
-	
+
+    private OCFile fillOCFile(WebdavEntry we) {
+        OCFile file = new OCFile(we.path());
+        file.setCreationTimestamp(we.createTimestamp());
+        file.setFileLength(we.contentLength());
+        file.setMimetype(we.contentType());
+        file.setModificationTimestamp(we.modifiedTimesamp());
+        return file;
+    }
+
 }

+ 26 - 25
src/eu/alefzero/owncloud/syncadapter/FileSyncService.java

@@ -22,35 +22,36 @@ import android.content.Intent;
 import android.os.IBinder;
 
 /**
- * Background service for syncing files to our
- * local Database
+ * Background service for syncing files to our local Database
+ * 
  * @author Bartek Przybylski
- *
+ * 
  */
 public class FileSyncService extends Service {
-  public static final String SYNC_MESSAGE = "eu.alefzero.owncloud.files.ACCOUNT_SYNC";
-  public static final String IN_PROGRESS = "sync_in_progress";
-  public static final String ACCOUNT_NAME = "account_name";
-  
-  private static final Object syncAdapterLock = new Object();
-  private static AbstractOwnCloudSyncAdapter concretSyncAdapter = null;
+    public static final String SYNC_MESSAGE = "eu.alefzero.owncloud.files.ACCOUNT_SYNC";
+    public static final String IN_PROGRESS = "sync_in_progress";
+    public static final String ACCOUNT_NAME = "account_name";
+
+    private static final Object syncAdapterLock = new Object();
+    private static AbstractOwnCloudSyncAdapter concretSyncAdapter = null;
 
-  /*
-   * {@inheritDoc}
-   */
-  @Override
-  public void onCreate() {
-    synchronized (syncAdapterLock) {
-      if (concretSyncAdapter == null)
-        concretSyncAdapter = new FileSyncAdapter(getApplicationContext(), true);
+    /*
+     * {@inheritDoc}
+     */
+    @Override
+    public void onCreate() {
+        synchronized (syncAdapterLock) {
+            if (concretSyncAdapter == null)
+                concretSyncAdapter = new FileSyncAdapter(
+                        getApplicationContext(), true);
+        }
     }
-  }
 
-  /*
-   * {@inheritDoc}
-   */
-  @Override
-  public IBinder onBind(Intent intent) {
-    return concretSyncAdapter.getSyncAdapterBinder();
-  }
+    /*
+     * {@inheritDoc}
+     */
+    @Override
+    public IBinder onBind(Intent intent) {
+        return concretSyncAdapter.getSyncAdapterBinder();
+    }
 }

+ 36 - 34
src/eu/alefzero/owncloud/ui/ActionItem.java

@@ -21,39 +21,41 @@ import android.graphics.drawable.Drawable;
 import android.view.View.OnClickListener;
 
 /**
-* Represents an Item on the ActionBar.
-* @author Bartek Przybylski
-* 
-*/
+ * Represents an Item on the ActionBar.
+ * 
+ * @author Bartek Przybylski
+ * 
+ */
 public class ActionItem {
-  private Drawable mIcon;
-  private String mTitle;
-  private OnClickListener mClickListener;
-  
-  public ActionItem() { }
-  
-  public void setTitle(String title) {
-    mTitle = title;
-  }
-  
-  public String getTitle() {
-    return mTitle;
-  }
-  
-  public void setIcon(Drawable icon) {
-    mIcon = icon;
-  }
-  
-  public Drawable getIcon() {
-    return mIcon;
-  }
-  
-  public void setOnClickListener(OnClickListener listener) {
-    mClickListener = listener;
-  }
-  
-  public OnClickListener getOnClickListerner() {
-    return mClickListener;
-  }
-  
+    private Drawable mIcon;
+    private String mTitle;
+    private OnClickListener mClickListener;
+
+    public ActionItem() {
+    }
+
+    public void setTitle(String title) {
+        mTitle = title;
+    }
+
+    public String getTitle() {
+        return mTitle;
+    }
+
+    public void setIcon(Drawable icon) {
+        mIcon = icon;
+    }
+
+    public Drawable getIcon() {
+        return mIcon;
+    }
+
+    public void setOnClickListener(OnClickListener listener) {
+        mClickListener = listener;
+    }
+
+    public OnClickListener getOnClickListerner() {
+        return mClickListener;
+    }
+
 }

+ 112 - 106
src/eu/alefzero/owncloud/ui/CustomPopup.java

@@ -32,117 +32,123 @@ import android.widget.PopupWindow;
 
 /**
  * Represents a custom PopupWindows
+ * 
  * @author Lorensius. W. T
- *
+ * 
  */
 public class CustomPopup {
-  protected final View mAnchor;
-  protected final PopupWindow mWindow;
-  private View root;
-  private Drawable background = null;
-  protected final WindowManager mWManager;
-  
-  public CustomPopup(View anchor) {
-    mAnchor = anchor;
-    mWindow = new PopupWindow(anchor.getContext());
-    
-    mWindow.setTouchInterceptor(new OnTouchListener() {
-      
-      public boolean onTouch(View v, MotionEvent event) {
-        if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
-          CustomPopup.this.dismiss();
-          return true;
+    protected final View mAnchor;
+    protected final PopupWindow mWindow;
+    private View root;
+    private Drawable background = null;
+    protected final WindowManager mWManager;
+
+    public CustomPopup(View anchor) {
+        mAnchor = anchor;
+        mWindow = new PopupWindow(anchor.getContext());
+
+        mWindow.setTouchInterceptor(new OnTouchListener() {
+
+            public boolean onTouch(View v, MotionEvent event) {
+                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
+                    CustomPopup.this.dismiss();
+                    return true;
+                }
+                return false;
+            }
+        });
+
+        mWManager = (WindowManager) anchor.getContext().getSystemService(
+                Context.WINDOW_SERVICE);
+        onCreate();
+    }
+
+    public void onCreate() {
+    }
+
+    public void onShow() {
+    }
+
+    public void preShow() {
+        if (root == null) {
+            throw new IllegalStateException(
+                    "setContentView called with a view to display");
         }
-        return false;
-      }
-    });
-    
-    mWManager = (WindowManager) anchor.getContext().getSystemService(Context.WINDOW_SERVICE);
-    onCreate();
-  }
-  
-  
-  public void onCreate() {}
-  public void onShow() {}
-  
-  public void preShow() {
-    if (root == null) {
-      throw new IllegalStateException("setContentView called with a view to display");
+
+        onShow();
+
+        if (background == null) {
+            mWindow.setBackgroundDrawable(new BitmapDrawable());
+        } else {
+            mWindow.setBackgroundDrawable(background);
+        }
+
+        mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
+        mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
+        mWindow.setTouchable(true);
+        mWindow.setFocusable(true);
+        mWindow.setOutsideTouchable(true);
+
+        mWindow.setContentView(root);
+    }
+
+    public void setBackgroundDrawable(Drawable background) {
+        this.background = background;
+    }
+
+    public void setContentView(View root) {
+        this.root = root;
+        mWindow.setContentView(root);
+    }
+
+    public void setContentView(int layoutResId) {
+        LayoutInflater inflater = (LayoutInflater) mAnchor.getContext()
+                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        setContentView(inflater.inflate(layoutResId, null));
+    }
+
+    public void showDropDown() {
+        showDropDown(0, 0);
     }
-    
-    onShow();
-    
-    if (background == null) {
-      mWindow.setBackgroundDrawable(new BitmapDrawable());
-    } else {
-      mWindow.setBackgroundDrawable(background);
+
+    public void showDropDown(int x, int y) {
+        preShow();
+        mWindow.setAnimationStyle(android.R.style.Animation_Dialog);
+        mWindow.showAsDropDown(mAnchor, x, y);
     }
-    
-    mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
-    mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
-    mWindow.setTouchable(true);
-    mWindow.setFocusable(true);
-    mWindow.setOutsideTouchable(true);
-    
-    mWindow.setContentView(root);
-  }
-  
-  public void setBackgroundDrawable(Drawable background) {
-    this.background = background;
-  }
-  
-  public void setContentView(View root) {
-    this.root = root;
-    mWindow.setContentView(root);
-  }
-  
-  public void setContentView(int layoutResId) {
-    LayoutInflater inflater = 
-      (LayoutInflater) mAnchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-    setContentView(inflater.inflate(layoutResId, null));
-  }
-  
-  public void showDropDown() {
-    showDropDown(0, 0);
-  }
-  
-  public void showDropDown(int x, int y) {
-    preShow();
-    mWindow.setAnimationStyle(android.R.style.Animation_Dialog);
-    mWindow.showAsDropDown(mAnchor, x, y);
-  }
-  
-  public void showLikeQuickAction() {
-    showLikeQuickAction(0, 0);
-  }
-  
-  public void showLikeQuickAction(int x, int y) {
-    preShow();
-    
-    mWindow.setAnimationStyle(android.R.style.Animation_Dialog);
-    int[] location = new int[2];
-    mAnchor.getLocationOnScreen(location);
-    
-    Rect anchorRect = 
-      new Rect(location[0], location[1], location[0] + mAnchor.getWidth(), location[1] + mAnchor.getHeight());
-    
-    root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
-    root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
-    
-    int rootW = root.getWidth(), rootH = root.getHeight();
-    int screenW = mWManager.getDefaultDisplay().getWidth();
-    
-    int xpos = ((screenW-rootW)/2) + x;
-    int ypos = anchorRect.top - rootH + y;
-    
-    if (rootH > anchorRect.top) {
-      ypos = anchorRect.bottom + y;
+
+    public void showLikeQuickAction() {
+        showLikeQuickAction(0, 0);
     }
-    mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xpos, ypos);
-  }
-  
-  public void dismiss() {
-    mWindow.dismiss();
-  }
-  
+
+    public void showLikeQuickAction(int x, int y) {
+        preShow();
+
+        mWindow.setAnimationStyle(android.R.style.Animation_Dialog);
+        int[] location = new int[2];
+        mAnchor.getLocationOnScreen(location);
+
+        Rect anchorRect = new Rect(location[0], location[1], location[0]
+                + mAnchor.getWidth(), location[1] + mAnchor.getHeight());
+
+        root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
+                LayoutParams.WRAP_CONTENT));
+        root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
+
+        int rootW = root.getWidth(), rootH = root.getHeight();
+        int screenW = mWManager.getDefaultDisplay().getWidth();
+
+        int xpos = ((screenW - rootW) / 2) + x;
+        int ypos = anchorRect.top - rootH + y;
+
+        if (rootH > anchorRect.top) {
+            ypos = anchorRect.bottom + y;
+        }
+        mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xpos, ypos);
+    }
+
+    public void dismiss() {
+        mWindow.dismiss();
+    }
+
 }

+ 37 - 38
src/eu/alefzero/owncloud/ui/FragmentListView.java

@@ -12,42 +12,41 @@ import android.widget.ListAdapter;
 import android.widget.ListView;
 import android.widget.AdapterView.OnItemClickListener;
 
-public class FragmentListView extends SherlockFragment
-                              implements OnItemClickListener,
-                                         OnItemLongClickListener {
-  ListView mList;
-  
-  @Override
-  public void onCreate(Bundle savedInstanceState) {
-    mList = new ListView(getActivity());
-    mList.setOnItemClickListener(this);
-    mList.setOnItemLongClickListener(this);
-    super.onCreate(savedInstanceState);
-  }
-  
-  public void setListAdapter(ListAdapter listAdapter) {
-    mList.setAdapter(listAdapter);
-    mList.invalidate();
-  }
-  
-  public ListView getListView() {
-    return mList;
-  }
-
-  @Override
-  public View onCreateView(LayoutInflater inflater, ViewGroup container,
-      Bundle savedInstanceState) {
-    return mList;
-    //return super.onCreateView(inflater, container, savedInstanceState);
-  }
-  
-  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {}
-
-  @Override
-  public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
-    return false;
-  }
-  
-  
-  
+public class FragmentListView extends SherlockFragment implements
+        OnItemClickListener, OnItemLongClickListener {
+    ListView mList;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        mList = new ListView(getActivity());
+        mList.setOnItemClickListener(this);
+        mList.setOnItemLongClickListener(this);
+        super.onCreate(savedInstanceState);
+    }
+
+    public void setListAdapter(ListAdapter listAdapter) {
+        mList.setAdapter(listAdapter);
+        mList.invalidate();
+    }
+
+    public ListView getListView() {
+        return mList;
+    }
+
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+        return mList;
+        // return super.onCreateView(inflater, container, savedInstanceState);
+    }
+
+    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
+    }
+
+    @Override
+    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
+            long arg3) {
+        return false;
+    }
+
 }

+ 263 - 233
src/eu/alefzero/owncloud/ui/QuickAction.java

@@ -39,248 +39,278 @@ import java.util.ArrayList;
 import eu.alefzero.owncloud.R;
 
 /**
- * Popup window, shows action list as icon and text like the one in Gallery3D app. 
+ * Popup window, shows action list as icon and text like the one in Gallery3D
+ * app.
  * 
  * @author Lorensius. W. T
  */
 public class QuickAction extends CustomPopup {
-	private final View root;
-	private final ImageView mArrowUp;
-	private final ImageView mArrowDown;
-	private final LayoutInflater inflater;
-	private final Context context;
-	
-	protected static final int ANIM_GROW_FROM_LEFT = 1;
-	protected static final int ANIM_GROW_FROM_RIGHT = 2;
-	protected static final int ANIM_GROW_FROM_CENTER = 3;
-	protected static final int ANIM_REFLECT = 4;
-	protected static final int ANIM_AUTO = 5;
-
-	private int animStyle;
-	private ViewGroup mTrack;
-	private ScrollView scroller;
-	private ArrayList<ActionItem> actionList;
-	
-	/**
-	 * Constructor
-	 * 
-	 * @param anchor {@link View} on where the popup window should be displayed
-	 */
-	public QuickAction(View anchor) {
-		super(anchor);
-		
-		actionList	= new ArrayList<ActionItem>();
-		context		= anchor.getContext();
-		inflater 	= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-		
-		root		= (ViewGroup) inflater.inflate(R.layout.popup, null);
-		
-		mArrowDown 	= (ImageView) root.findViewById(R.id.arrow_down);
-		mArrowUp 	= (ImageView) root.findViewById(R.id.arrow_up);
-		
-		setContentView(root);
-	    
-		mTrack 			= (ViewGroup) root.findViewById(R.id.tracks);
-		scroller		= (ScrollView) root.findViewById(R.id.scroller);
-		animStyle		= ANIM_AUTO;
-	}
-
-	/**
-	 * Set animation style
-	 * 
-	 * @param animStyle animation style, default is set to ANIM_AUTO
-	 */
-	public void setAnimStyle(int animStyle) {
-		this.animStyle = animStyle;
-	}
-
-	/**
-	 * Add action item
-	 * 
-	 * @param action  {@link ActionItem} object
-	 */
-	public void addActionItem(ActionItem action) {
-		actionList.add(action); 
-	}
-	
-	/**
-	 * Show popup window. Popup is automatically positioned, on top or bottom of anchor view.
-	 * 
-	 */
-	public void show () {
-		preShow();
-		
-		int xPos, yPos;
-		
-		int[] location 		= new int[2];
-	
-		mAnchor.getLocationOnScreen(location);
-
-		Rect anchorRect 	= new Rect(location[0], location[1], location[0] + mAnchor.getWidth(), location[1] 
-		                	+ mAnchor.getHeight());
-
-		createActionList();
-		
-		root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
-		root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
-	
-		int rootHeight 		= root.getMeasuredHeight();
-		int rootWidth		= root.getMeasuredWidth();
-		
-		int screenWidth 	= mWManager.getDefaultDisplay().getWidth();
-		int screenHeight	= mWManager.getDefaultDisplay().getHeight();
-		
-		//automatically get X coord of popup (top left)
-		if ((anchorRect.left + rootWidth) > screenWidth) {
-			xPos = anchorRect.left - (rootWidth-mAnchor.getWidth());
-		} else {
-			if (mAnchor.getWidth() > rootWidth) {
-				xPos = anchorRect.centerX() - (rootWidth/2);
-			} else {
-				xPos = anchorRect.left;
-			}
-		}
-		
-		int dyTop			= anchorRect.top;
-		int dyBottom		= screenHeight - anchorRect.bottom;
-
-		boolean onTop		= (dyTop > dyBottom) ? true : false;
-
-		if (onTop) {
-			if (rootHeight > dyTop) {
-				yPos 			= 15;
-				LayoutParams l 	= scroller.getLayoutParams();
-				l.height		= dyTop - mAnchor.getHeight();
-			} else {
-				yPos = anchorRect.top - rootHeight;
-			}
-		} else {
-			yPos = anchorRect.bottom;
-			
-			if (rootHeight > dyBottom) { 
-				LayoutParams l 	= scroller.getLayoutParams();
-				l.height		= dyBottom;
-			}
-		}
-		
-		showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), anchorRect.centerX()-xPos);
-		
-		setAnimationStyle(screenWidth, anchorRect.centerX(), onTop);
-		
-		mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xPos, yPos);
-	}
-	
-	/**
-	 * Set animation style
-	 * 
-	 * @param screenWidth screen width
-	 * @param requestedX distance from left edge
-	 * @param onTop flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor view
-	 * 		  and vice versa
-	 */
-	private void setAnimationStyle(int screenWidth, int requestedX, boolean onTop) {
-		int arrowPos = requestedX - mArrowUp.getMeasuredWidth()/2;
-
-		switch (animStyle) {
-		case ANIM_GROW_FROM_LEFT:
-			mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left);
-			break;
-					
-		case ANIM_GROW_FROM_RIGHT:
-			mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right);
-			break;
-					
-		case ANIM_GROW_FROM_CENTER:
-			mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center);
-		break;
-			
-		case ANIM_REFLECT:
-			mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect : R.style.Animations_PopDownMenu_Reflect);
-		break;
-		
-		case ANIM_AUTO:
-			if (arrowPos <= screenWidth/4) {
-				mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left);
-			} else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) {
-				mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center);
-			} else {
-				mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right);
-			}
-					
-			break;
-		}
-	}
-	
-	/**
-	 * Create action list
-	 */
-	private void createActionList() {
-		View view;
-		String title;
-		Drawable icon;
-		OnClickListener listener;
-	
-		for (int i = 0; i < actionList.size(); i++) {
-			title 		= actionList.get(i).getTitle();
-			icon 		= actionList.get(i).getIcon();
-			listener	= actionList.get(i).getOnClickListerner();
-	
-			view 		= getActionItem(title, icon, listener);
-		
-			view.setFocusable(true);
-			view.setClickable(true);
-			 
-			mTrack.addView(view);
-		}
-	}
-	
-	/**
-	 * Get action item {@link View}
-	 * 
-	 * @param title action item title
-	 * @param icon {@link Drawable} action item icon
-	 * @param listener {@link View.OnClickListener} action item listener
-	 * @return action item {@link View}
-	 */
-	private View getActionItem(String title, Drawable icon, OnClickListener listener) {
-		LinearLayout container	= (LinearLayout) inflater.inflate(R.layout.action_item, null);
-		
-		ImageView img			= (ImageView) container.findViewById(R.id.icon);
-		TextView text			= (TextView) container.findViewById(R.id.title);
-		
-		if (icon != null) {
-			img.setImageDrawable(icon);
-		}
-		
-		if (title != null) {			
-			text.setText(title);
-		}
-		
-		if (listener != null) {
-			container.setOnClickListener(listener);
-		}
-
-		return container;
-	}
-	
-	/**
-	 * Show arrow
-	 * 
-	 * @param whichArrow arrow type resource id
-	 * @param requestedX distance from left screen
-	 */
-	private void showArrow(int whichArrow, int requestedX) {
-        final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown;
-        final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp;
+    private final View root;
+    private final ImageView mArrowUp;
+    private final ImageView mArrowDown;
+    private final LayoutInflater inflater;
+    private final Context context;
+
+    protected static final int ANIM_GROW_FROM_LEFT = 1;
+    protected static final int ANIM_GROW_FROM_RIGHT = 2;
+    protected static final int ANIM_GROW_FROM_CENTER = 3;
+    protected static final int ANIM_REFLECT = 4;
+    protected static final int ANIM_AUTO = 5;
+
+    private int animStyle;
+    private ViewGroup mTrack;
+    private ScrollView scroller;
+    private ArrayList<ActionItem> actionList;
+
+    /**
+     * Constructor
+     * 
+     * @param anchor
+     *            {@link View} on where the popup window should be displayed
+     */
+    public QuickAction(View anchor) {
+        super(anchor);
+
+        actionList = new ArrayList<ActionItem>();
+        context = anchor.getContext();
+        inflater = (LayoutInflater) context
+                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+
+        root = (ViewGroup) inflater.inflate(R.layout.popup, null);
+
+        mArrowDown = (ImageView) root.findViewById(R.id.arrow_down);
+        mArrowUp = (ImageView) root.findViewById(R.id.arrow_up);
+
+        setContentView(root);
+
+        mTrack = (ViewGroup) root.findViewById(R.id.tracks);
+        scroller = (ScrollView) root.findViewById(R.id.scroller);
+        animStyle = ANIM_AUTO;
+    }
+
+    /**
+     * Set animation style
+     * 
+     * @param animStyle
+     *            animation style, default is set to ANIM_AUTO
+     */
+    public void setAnimStyle(int animStyle) {
+        this.animStyle = animStyle;
+    }
+
+    /**
+     * Add action item
+     * 
+     * @param action
+     *            {@link ActionItem} object
+     */
+    public void addActionItem(ActionItem action) {
+        actionList.add(action);
+    }
+
+    /**
+     * Show popup window. Popup is automatically positioned, on top or bottom of
+     * anchor view.
+     * 
+     */
+    public void show() {
+        preShow();
+
+        int xPos, yPos;
+
+        int[] location = new int[2];
+
+        mAnchor.getLocationOnScreen(location);
+
+        Rect anchorRect = new Rect(location[0], location[1], location[0]
+                + mAnchor.getWidth(), location[1] + mAnchor.getHeight());
+
+        createActionList();
+
+        root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
+                LayoutParams.WRAP_CONTENT));
+        root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
+
+        int rootHeight = root.getMeasuredHeight();
+        int rootWidth = root.getMeasuredWidth();
+
+        int screenWidth = mWManager.getDefaultDisplay().getWidth();
+        int screenHeight = mWManager.getDefaultDisplay().getHeight();
+
+        // automatically get X coord of popup (top left)
+        if ((anchorRect.left + rootWidth) > screenWidth) {
+            xPos = anchorRect.left - (rootWidth - mAnchor.getWidth());
+        } else {
+            if (mAnchor.getWidth() > rootWidth) {
+                xPos = anchorRect.centerX() - (rootWidth / 2);
+            } else {
+                xPos = anchorRect.left;
+            }
+        }
+
+        int dyTop = anchorRect.top;
+        int dyBottom = screenHeight - anchorRect.bottom;
+
+        boolean onTop = (dyTop > dyBottom) ? true : false;
+
+        if (onTop) {
+            if (rootHeight > dyTop) {
+                yPos = 15;
+                LayoutParams l = scroller.getLayoutParams();
+                l.height = dyTop - mAnchor.getHeight();
+            } else {
+                yPos = anchorRect.top - rootHeight;
+            }
+        } else {
+            yPos = anchorRect.bottom;
+
+            if (rootHeight > dyBottom) {
+                LayoutParams l = scroller.getLayoutParams();
+                l.height = dyBottom;
+            }
+        }
+
+        showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up),
+                anchorRect.centerX() - xPos);
+
+        setAnimationStyle(screenWidth, anchorRect.centerX(), onTop);
+
+        mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xPos, yPos);
+    }
+
+    /**
+     * Set animation style
+     * 
+     * @param screenWidth
+     *            screen width
+     * @param requestedX
+     *            distance from left edge
+     * @param onTop
+     *            flag to indicate where the popup should be displayed. Set TRUE
+     *            if displayed on top of anchor view and vice versa
+     */
+    private void setAnimationStyle(int screenWidth, int requestedX,
+            boolean onTop) {
+        int arrowPos = requestedX - mArrowUp.getMeasuredWidth() / 2;
+
+        switch (animStyle) {
+        case ANIM_GROW_FROM_LEFT:
+            mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left
+                    : R.style.Animations_PopDownMenu_Left);
+            break;
+
+        case ANIM_GROW_FROM_RIGHT:
+            mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right
+                    : R.style.Animations_PopDownMenu_Right);
+            break;
+
+        case ANIM_GROW_FROM_CENTER:
+            mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center
+                    : R.style.Animations_PopDownMenu_Center);
+            break;
+
+        case ANIM_REFLECT:
+            mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect
+                    : R.style.Animations_PopDownMenu_Reflect);
+            break;
+
+        case ANIM_AUTO:
+            if (arrowPos <= screenWidth / 4) {
+                mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left
+                        : R.style.Animations_PopDownMenu_Left);
+            } else if (arrowPos > screenWidth / 4
+                    && arrowPos < 3 * (screenWidth / 4)) {
+                mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center
+                        : R.style.Animations_PopDownMenu_Center);
+            } else {
+                mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right
+                        : R.style.Animations_PopDownMenu_Right);
+            }
+
+            break;
+        }
+    }
+
+    /**
+     * Create action list
+     */
+    private void createActionList() {
+        View view;
+        String title;
+        Drawable icon;
+        OnClickListener listener;
+
+        for (int i = 0; i < actionList.size(); i++) {
+            title = actionList.get(i).getTitle();
+            icon = actionList.get(i).getIcon();
+            listener = actionList.get(i).getOnClickListerner();
+
+            view = getActionItem(title, icon, listener);
+
+            view.setFocusable(true);
+            view.setClickable(true);
+
+            mTrack.addView(view);
+        }
+    }
+
+    /**
+     * Get action item {@link View}
+     * 
+     * @param title
+     *            action item title
+     * @param icon
+     *            {@link Drawable} action item icon
+     * @param listener
+     *            {@link View.OnClickListener} action item listener
+     * @return action item {@link View}
+     */
+    private View getActionItem(String title, Drawable icon,
+            OnClickListener listener) {
+        LinearLayout container = (LinearLayout) inflater.inflate(
+                R.layout.action_item, null);
+
+        ImageView img = (ImageView) container.findViewById(R.id.icon);
+        TextView text = (TextView) container.findViewById(R.id.title);
+
+        if (icon != null) {
+            img.setImageDrawable(icon);
+        }
+
+        if (title != null) {
+            text.setText(title);
+        }
+
+        if (listener != null) {
+            container.setOnClickListener(listener);
+        }
+
+        return container;
+    }
+
+    /**
+     * Show arrow
+     * 
+     * @param whichArrow
+     *            arrow type resource id
+     * @param requestedX
+     *            distance from left screen
+     */
+    private void showArrow(int whichArrow, int requestedX) {
+        final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp
+                : mArrowDown;
+        final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown
+                : mArrowUp;
 
         final int arrowWidth = mArrowUp.getMeasuredWidth();
 
         showArrow.setVisibility(View.VISIBLE);
-        
-        ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.getLayoutParams();
-       
+
+        ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams) showArrow
+                .getLayoutParams();
+
         param.leftMargin = requestedX - arrowWidth / 2;
-        
+
         hideArrow.setVisibility(View.INVISIBLE);
     }
 }

+ 133 - 127
src/eu/alefzero/owncloud/ui/activity/AccountSelectActivity.java

@@ -36,139 +36,145 @@ import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
 import eu.alefzero.owncloud.AccountUtils;
 import eu.alefzero.owncloud.R;
 
-public class AccountSelectActivity extends SherlockListActivity
-                                   implements AccountManagerCallback<Boolean> {
-
-  private final Handler mHandler = new Handler(); 
-  
-  @Override
-  protected void onCreate(Bundle savedInstanceState) {
-    super.onCreate(savedInstanceState);
-    
-    ActionBar action_bar = getSupportActionBar();
-    action_bar.setDisplayShowTitleEnabled(true);
-    action_bar.setDisplayHomeAsUpEnabled(false);
-  }
-
-  @Override
-  protected void onResume() {
-    super.onResume();
-    populateAccountList();
-  }
-  
-  @Override
-  public boolean onCreateOptionsMenu(Menu menu) {
-    MenuInflater inflater = getSherlock().getMenuInflater();
-    inflater.inflate(eu.alefzero.owncloud.R.menu.account_picker, menu);
-    return true;
-  }
-  
-  @Override
-  public void onCreateContextMenu(ContextMenu menu, View v,
-      ContextMenuInfo menuInfo) {
-    getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
-    super.onCreateContextMenu(menu, v, menuInfo);
-  }
-  
-  @Override
-  protected void onListItemClick(ListView l, View v, int position, long id) {
-    String accountName = ((TextView)v.findViewById(android.R.id.text1)).getText().toString();
-    AccountUtils.setCurrentOwnCloudAccount(this, accountName);
-    Intent i = new Intent(this, FileDisplayActivity.class);
-    startActivity(i);
-    finish();
-  }
-
-  @Override
-  public boolean onMenuItemSelected(int featureId, MenuItem item) {
-    if (item.getItemId() == R.id.createAccount) {
-      Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
-      intent.putExtra("authorities",
-          new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
-      startActivity(intent);
-      return true;
+public class AccountSelectActivity extends SherlockListActivity implements
+        AccountManagerCallback<Boolean> {
+
+    private final Handler mHandler = new Handler();
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        ActionBar action_bar = getSupportActionBar();
+        action_bar.setDisplayShowTitleEnabled(true);
+        action_bar.setDisplayHomeAsUpEnabled(false);
     }
-    return false;
-  }
-  
-  @Override
-  public boolean onContextItemSelected(android.view.MenuItem item) {
-    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
-    int index = info.position;
-    HashMap<String, String> map = (HashMap<String, String>)getListAdapter().getItem(index);
-    String accountName = map.get("NAME");
-    AccountManager am = (AccountManager)getSystemService(ACCOUNT_SERVICE); 
-    Account accounts[] = am.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
-    for (Account a : accounts) {
-      if (a.name.equals(accountName)) {
-        am.removeAccount(a, this, mHandler);
-      }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        populateAccountList();
     }
-    
-    return false;
-  }
-
-
-  private void populateAccountList() {
-    AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
-    Account accounts[] = am.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
-    LinkedList< HashMap<String, String>> ll = new LinkedList<HashMap<String,String>>();
-    for (Account a : accounts) {
-      HashMap<String, String> h = new HashMap<String, String>();
-      h.put("NAME", a.name);
-      h.put("VER", "ownCloud version: " + am.getUserData(a, AccountAuthenticator.KEY_OC_VERSION));
-      ll.add(h);
+
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        MenuInflater inflater = getSherlock().getMenuInflater();
+        inflater.inflate(eu.alefzero.owncloud.R.menu.account_picker, menu);
+        return true;
     }
-    
-    setListAdapter(new AccountCheckedSimpleAdepter(this,
-                                                   ll,
-                                                   android.R.layout.simple_list_item_single_choice,
-                                                   new String[]{"NAME"},
-                                                   new int[]{android.R.id.text1}));
-    registerForContextMenu(getListView());
-  }
-  
-  @Override
-  public void run(AccountManagerFuture<Boolean> future) {
-    if (future.isDone()) {
-      Account a = AccountUtils.getCurrentOwnCloudAccount(this);
-      String accountName = "";
-      if (a == null) {
-        Account[] accounts = AccountManager.get(this).getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
-        if (accounts.length != 0)
-          accountName = accounts[0].name;
+
+    @Override
+    public void onCreateContextMenu(ContextMenu menu, View v,
+            ContextMenuInfo menuInfo) {
+        getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
+        super.onCreateContextMenu(menu, v, menuInfo);
+    }
+
+    @Override
+    protected void onListItemClick(ListView l, View v, int position, long id) {
+        String accountName = ((TextView) v.findViewById(android.R.id.text1))
+                .getText().toString();
         AccountUtils.setCurrentOwnCloudAccount(this, accountName);
-      }
-      populateAccountList();
+        Intent i = new Intent(this, FileDisplayActivity.class);
+        startActivity(i);
+        finish();
+    }
+
+    @Override
+    public boolean onMenuItemSelected(int featureId, MenuItem item) {
+        if (item.getItemId() == R.id.createAccount) {
+            Intent intent = new Intent(
+                    android.provider.Settings.ACTION_ADD_ACCOUNT);
+            intent.putExtra("authorities",
+                    new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+            startActivity(intent);
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public boolean onContextItemSelected(android.view.MenuItem item) {
+        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
+                .getMenuInfo();
+        int index = info.position;
+        HashMap<String, String> map = (HashMap<String, String>) getListAdapter()
+                .getItem(index);
+        String accountName = map.get("NAME");
+        AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
+        Account accounts[] = am
+                .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+        for (Account a : accounts) {
+            if (a.name.equals(accountName)) {
+                am.removeAccount(a, this, mHandler);
+            }
+        }
+
+        return false;
     }
-  }
-  
-  private class AccountCheckedSimpleAdepter extends SimpleAdapter {
-    private Account mCurrentAccount;
-    private List<? extends Map<String, ?>> mPrivateData;
-    
-    public AccountCheckedSimpleAdepter(Context context,
-                                       List<? extends Map<String, ?>> data,
-                                       int resource,
-                                       String[] from,
-                                       int[] to) {
-      super(context, data, resource, from, to);
-      mCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(AccountSelectActivity.this);
-      mPrivateData = data;
+
+    private void populateAccountList() {
+        AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
+        Account accounts[] = am
+                .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+        LinkedList<HashMap<String, String>> ll = new LinkedList<HashMap<String, String>>();
+        for (Account a : accounts) {
+            HashMap<String, String> h = new HashMap<String, String>();
+            h.put("NAME", a.name);
+            h.put("VER",
+                    "ownCloud version: "
+                            + am.getUserData(a,
+                                    AccountAuthenticator.KEY_OC_VERSION));
+            ll.add(h);
+        }
+
+        setListAdapter(new AccountCheckedSimpleAdepter(this, ll,
+                android.R.layout.simple_list_item_single_choice,
+                new String[] { "NAME" }, new int[] { android.R.id.text1 }));
+        registerForContextMenu(getListView());
     }
-    
-   @Override
-  public View getView(int position, View convertView, ViewGroup parent) {
-    View v = super.getView(position, convertView, parent);
-    CheckedTextView ctv = (CheckedTextView) v.findViewById(android.R.id.text1);
-    if (mPrivateData.get(position).get("NAME").equals(mCurrentAccount.name)) {
-      ctv.setChecked(true);
+
+    @Override
+    public void run(AccountManagerFuture<Boolean> future) {
+        if (future.isDone()) {
+            Account a = AccountUtils.getCurrentOwnCloudAccount(this);
+            String accountName = "";
+            if (a == null) {
+                Account[] accounts = AccountManager.get(this)
+                        .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+                if (accounts.length != 0)
+                    accountName = accounts[0].name;
+                AccountUtils.setCurrentOwnCloudAccount(this, accountName);
+            }
+            populateAccountList();
+        }
     }
-    return v;
-  } 
-    
-    
-  }
 
-}
+    private class AccountCheckedSimpleAdepter extends SimpleAdapter {
+        private Account mCurrentAccount;
+        private List<? extends Map<String, ?>> mPrivateData;
 
+        public AccountCheckedSimpleAdepter(Context context,
+                List<? extends Map<String, ?>> data, int resource,
+                String[] from, int[] to) {
+            super(context, data, resource, from, to);
+            mCurrentAccount = AccountUtils
+                    .getCurrentOwnCloudAccount(AccountSelectActivity.this);
+            mPrivateData = data;
+        }
+
+        @Override
+        public View getView(int position, View convertView, ViewGroup parent) {
+            View v = super.getView(position, convertView, parent);
+            CheckedTextView ctv = (CheckedTextView) v
+                    .findViewById(android.R.id.text1);
+            if (mPrivateData.get(position).get("NAME")
+                    .equals(mCurrentAccount.name)) {
+                ctv.setChecked(true);
+            }
+            return v;
+        }
+
+    }
+
+}

+ 317 - 302
src/eu/alefzero/owncloud/ui/activity/AuthenticatorActivity.java

@@ -59,319 +59,334 @@ import eu.alefzero.owncloud.utils.OwnCloudVersion;
  * 
  */
 public class AuthenticatorActivity extends AccountAuthenticatorActivity
-                                   implements OnAuthenticationResultListener,
-                                              OnConnectCheckListener,
-                                              OnFocusChangeListener,
-                                              OnClickListener {
-  private static final int DIALOG_LOGIN_PROGRESS = 0;
-  
-  private static final String TAG = "AuthActivity";
-
-  private Thread mAuthThread;
-  private AuthenticationRunnable mAuthRunnable;
-  private ConnectionCheckerRunnable mConnChkRunnable;
-  private final Handler mHandler = new Handler();
-  private String mBaseUrl;
-  
-  private static final String STATUS_TEXT = "STATUS_TEXT"; 
-  private static final String STATUS_ICON = "STATUS_ICON";
-  private static final String STATUS_CORRECT = "STATUS_CORRECT";
-  private static final String IS_SSL_CONN = "IS_SSL_CONN";
-  private int mStatusText, mStatusIcon;
-  private boolean mStatusCorrect, mIsSslConn;
-
-  public static final String PARAM_USERNAME = "param_Username";
-  public static final String PARAM_HOSTNAME = "param_Hostname";
-
-  @Override
-  protected void onCreate(Bundle savedInstanceState) {
-    super.onCreate(savedInstanceState);
-    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
-    setContentView(R.layout.account_setup);
-    ImageView iv = (ImageView) findViewById(R.id.refreshButton);
-    ImageView iv2 = (ImageView) findViewById(R.id.viewPassword);
-    TextView tv = (TextView) findViewById(R.id.host_URL);
-    TextView tv2 = (TextView) findViewById(R.id.account_password);
-    
-    if (savedInstanceState != null) {
-      mStatusIcon = savedInstanceState.getInt(STATUS_ICON);
-      mStatusText = savedInstanceState.getInt(STATUS_TEXT);
-      mStatusCorrect = savedInstanceState.getBoolean(STATUS_CORRECT);
-      mIsSslConn = savedInstanceState.getBoolean(IS_SSL_CONN);
-      setResultIconAndText(mStatusIcon, mStatusText);
-      findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
-      if (!mStatusCorrect)
-        iv.setVisibility(View.VISIBLE);
-      else
-        iv.setVisibility(View.INVISIBLE);
-     
-    } else {
-      mStatusText = mStatusIcon = 0;
-      mStatusCorrect = false;
-      mIsSslConn = false;
+        implements OnAuthenticationResultListener, OnConnectCheckListener,
+        OnFocusChangeListener, OnClickListener {
+    private static final int DIALOG_LOGIN_PROGRESS = 0;
+
+    private static final String TAG = "AuthActivity";
+
+    private Thread mAuthThread;
+    private AuthenticationRunnable mAuthRunnable;
+    private ConnectionCheckerRunnable mConnChkRunnable;
+    private final Handler mHandler = new Handler();
+    private String mBaseUrl;
+
+    private static final String STATUS_TEXT = "STATUS_TEXT";
+    private static final String STATUS_ICON = "STATUS_ICON";
+    private static final String STATUS_CORRECT = "STATUS_CORRECT";
+    private static final String IS_SSL_CONN = "IS_SSL_CONN";
+    private int mStatusText, mStatusIcon;
+    private boolean mStatusCorrect, mIsSslConn;
+
+    public static final String PARAM_USERNAME = "param_Username";
+    public static final String PARAM_HOSTNAME = "param_Hostname";
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
+        setContentView(R.layout.account_setup);
+        ImageView iv = (ImageView) findViewById(R.id.refreshButton);
+        ImageView iv2 = (ImageView) findViewById(R.id.viewPassword);
+        TextView tv = (TextView) findViewById(R.id.host_URL);
+        TextView tv2 = (TextView) findViewById(R.id.account_password);
+
+        if (savedInstanceState != null) {
+            mStatusIcon = savedInstanceState.getInt(STATUS_ICON);
+            mStatusText = savedInstanceState.getInt(STATUS_TEXT);
+            mStatusCorrect = savedInstanceState.getBoolean(STATUS_CORRECT);
+            mIsSslConn = savedInstanceState.getBoolean(IS_SSL_CONN);
+            setResultIconAndText(mStatusIcon, mStatusText);
+            findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
+            if (!mStatusCorrect)
+                iv.setVisibility(View.VISIBLE);
+            else
+                iv.setVisibility(View.INVISIBLE);
+
+        } else {
+            mStatusText = mStatusIcon = 0;
+            mStatusCorrect = false;
+            mIsSslConn = false;
+        }
+        iv.setOnClickListener(this);
+        iv2.setOnClickListener(this);
+        tv.setOnFocusChangeListener(this);
+        tv2.setOnFocusChangeListener(this);
     }
-    iv.setOnClickListener(this);
-    iv2.setOnClickListener(this);
-    tv.setOnFocusChangeListener(this);
-    tv2.setOnFocusChangeListener(this);
-  }
-
-  @Override
-  protected void onSaveInstanceState(Bundle outState) {
-    outState.putInt(STATUS_ICON, mStatusIcon);
-    outState.putInt(STATUS_TEXT, mStatusText);
-    outState.putBoolean(STATUS_CORRECT, mStatusCorrect);
-    super.onSaveInstanceState(outState);
-  }
-
-  @Override
-  protected Dialog onCreateDialog(int id) {
-    Dialog dialog = null;
-    switch (id) {
-      case DIALOG_LOGIN_PROGRESS : {
-        ProgressDialog working_dialog = new ProgressDialog(this);
-        working_dialog.setMessage(getResources().getString(R.string.auth_trying_to_login));
-        working_dialog.setIndeterminate(true);
-        working_dialog.setCancelable(true);
-        working_dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
-          @Override
-          public void onCancel(DialogInterface dialog) {
-            Log.i(TAG, "Login canceled");
-            if (mAuthThread != null) {
-              mAuthThread.interrupt();
-              finish();
-            }
-          }
-        });
-        dialog = working_dialog;
-        break;
-      }
-      default :
-        Log.e(TAG, "Incorrect dialog called with id = " + id);
+
+    @Override
+    protected void onSaveInstanceState(Bundle outState) {
+        outState.putInt(STATUS_ICON, mStatusIcon);
+        outState.putInt(STATUS_TEXT, mStatusText);
+        outState.putBoolean(STATUS_CORRECT, mStatusCorrect);
+        super.onSaveInstanceState(outState);
     }
-    return dialog;
-  }
-
-  public void onAuthenticationResult(boolean success, String message) {
-    if (success) {
-      TextView username_text = (TextView) findViewById(R.id.account_username), password_text = (TextView) findViewById(R.id.account_password);
-
-      URL url;
-      try {
-        url = new URL(message);
-      } catch (MalformedURLException e) {
-        // should never happen
-        Log.e(getClass().getName(), "Malformed URL: " + message);
-        return;
-      }
-
-      String username = username_text.getText().toString().trim();
-      String accountName = username + "@" + url.getHost();
-      Account account = new Account(accountName,
-          AccountAuthenticator.ACCOUNT_TYPE);
-      AccountManager accManager = AccountManager.get(this);
-      accManager.addAccountExplicitly(account, password_text.getText()
-          .toString(), null);
-
-      // Add this account as default in the preferences, if there is none
-      // already
-      Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
-      if (defaultAccount == null) {
-        SharedPreferences.Editor editor = PreferenceManager
-            .getDefaultSharedPreferences(this).edit();
-        editor.putString("select_oc_account", accountName);
-        editor.commit();
-      }
-
-      final Intent intent = new Intent();
-      intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);
-      intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
-      intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE);
-      intent.putExtra(AccountManager.KEY_USERDATA, username);
-
-      accManager.setUserData(account,
-                             AccountAuthenticator.KEY_OC_URL,
-                             url.toString());
-      accManager.setUserData(account,
-                             AccountAuthenticator.KEY_OC_VERSION,
-                             mConnChkRunnable.getDiscoveredVersion().toString());
-      accManager.setUserData(account,
-                             AccountAuthenticator.KEY_OC_BASE_URL,
-                             mBaseUrl);
-
-      setAccountAuthenticatorResult(intent.getExtras());
-      setResult(RESULT_OK, intent);
-      Bundle bundle = new Bundle();
-      bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
-      getContentResolver().startSync(ProviderTableMeta.CONTENT_URI, bundle);
-
-      /*if (mConnChkRunnable.getDiscoveredVersion().compareTo(OwnCloudVersion.owncloud_v2) >= 0) {
-        Intent i = new Intent(this, ExtensionsAvailableActivity.class);
-        startActivity(i);
-      }*/
-
-      finish();
-    } else {
-      dismissDialog(DIALOG_LOGIN_PROGRESS);
-      TextView tv = (TextView) findViewById(R.id.account_username);
-      tv.setError(message);
+
+    @Override
+    protected Dialog onCreateDialog(int id) {
+        Dialog dialog = null;
+        switch (id) {
+        case DIALOG_LOGIN_PROGRESS: {
+            ProgressDialog working_dialog = new ProgressDialog(this);
+            working_dialog.setMessage(getResources().getString(
+                    R.string.auth_trying_to_login));
+            working_dialog.setIndeterminate(true);
+            working_dialog.setCancelable(true);
+            working_dialog
+                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
+                        @Override
+                        public void onCancel(DialogInterface dialog) {
+                            Log.i(TAG, "Login canceled");
+                            if (mAuthThread != null) {
+                                mAuthThread.interrupt();
+                                finish();
+                            }
+                        }
+                    });
+            dialog = working_dialog;
+            break;
+        }
+        default:
+            Log.e(TAG, "Incorrect dialog called with id = " + id);
+        }
+        return dialog;
     }
-  }
-
-  public void onOkClick(View view) {
-    String prefix = "";
-    String url = ((TextView) findViewById(R.id.host_URL)).getText().toString();
-    if (mIsSslConn) {
-      prefix = "https://";
-    } else {
-      prefix = "http://";
+
+    public void onAuthenticationResult(boolean success, String message) {
+        if (success) {
+            TextView username_text = (TextView) findViewById(R.id.account_username), password_text = (TextView) findViewById(R.id.account_password);
+
+            URL url;
+            try {
+                url = new URL(message);
+            } catch (MalformedURLException e) {
+                // should never happen
+                Log.e(getClass().getName(), "Malformed URL: " + message);
+                return;
+            }
+
+            String username = username_text.getText().toString().trim();
+            String accountName = username + "@" + url.getHost();
+            Account account = new Account(accountName,
+                    AccountAuthenticator.ACCOUNT_TYPE);
+            AccountManager accManager = AccountManager.get(this);
+            accManager.addAccountExplicitly(account, password_text.getText()
+                    .toString(), null);
+
+            // Add this account as default in the preferences, if there is none
+            // already
+            Account defaultAccount = AccountUtils
+                    .getCurrentOwnCloudAccount(this);
+            if (defaultAccount == null) {
+                SharedPreferences.Editor editor = PreferenceManager
+                        .getDefaultSharedPreferences(this).edit();
+                editor.putString("select_oc_account", accountName);
+                editor.commit();
+            }
+
+            final Intent intent = new Intent();
+            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,
+                    AccountAuthenticator.ACCOUNT_TYPE);
+            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
+            intent.putExtra(AccountManager.KEY_AUTHTOKEN,
+                    AccountAuthenticator.ACCOUNT_TYPE);
+            intent.putExtra(AccountManager.KEY_USERDATA, username);
+
+            accManager.setUserData(account, AccountAuthenticator.KEY_OC_URL,
+                    url.toString());
+            accManager.setUserData(account,
+                    AccountAuthenticator.KEY_OC_VERSION, mConnChkRunnable
+                            .getDiscoveredVersion().toString());
+            accManager.setUserData(account,
+                    AccountAuthenticator.KEY_OC_BASE_URL, mBaseUrl);
+
+            setAccountAuthenticatorResult(intent.getExtras());
+            setResult(RESULT_OK, intent);
+            Bundle bundle = new Bundle();
+            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
+            getContentResolver().startSync(ProviderTableMeta.CONTENT_URI,
+                    bundle);
+
+            /*
+             * if
+             * (mConnChkRunnable.getDiscoveredVersion().compareTo(OwnCloudVersion
+             * .owncloud_v2) >= 0) { Intent i = new Intent(this,
+             * ExtensionsAvailableActivity.class); startActivity(i); }
+             */
+
+            finish();
+        } else {
+            dismissDialog(DIALOG_LOGIN_PROGRESS);
+            TextView tv = (TextView) findViewById(R.id.account_username);
+            tv.setError(message);
+        }
     }
-    if (url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) {
-      prefix = "";
+
+    public void onOkClick(View view) {
+        String prefix = "";
+        String url = ((TextView) findViewById(R.id.host_URL)).getText()
+                .toString();
+        if (mIsSslConn) {
+            prefix = "https://";
+        } else {
+            prefix = "http://";
+        }
+        if (url.toLowerCase().startsWith("http://")
+                || url.toLowerCase().startsWith("https://")) {
+            prefix = "";
+        }
+        continueConnection(prefix);
     }
-    continueConnection(prefix);
-  }
-  
-  private void continueConnection(String prefix) {
-    String url = ((TextView) findViewById(R.id.host_URL)).getText().toString();
-    String username = ((TextView) findViewById(R.id.account_username)).getText().toString();
-    String password = ((TextView) findViewById(R.id.account_password)).getText().toString();
-    if (url.endsWith("/"))
-      url = url.substring(0, url.length()-1);
-
-    URL uri = null;
-    String webdav_path = AccountUtils.getWebdavPath(mConnChkRunnable.getDiscoveredVersion());
-
-    try {
-      mBaseUrl = prefix + url;
-      String url_str = prefix + url + webdav_path;
-      uri = new URL(url_str);
-    } catch (MalformedURLException e) {
-      // should not happend
-      e.printStackTrace();
+
+    private void continueConnection(String prefix) {
+        String url = ((TextView) findViewById(R.id.host_URL)).getText()
+                .toString();
+        String username = ((TextView) findViewById(R.id.account_username))
+                .getText().toString();
+        String password = ((TextView) findViewById(R.id.account_password))
+                .getText().toString();
+        if (url.endsWith("/"))
+            url = url.substring(0, url.length() - 1);
+
+        URL uri = null;
+        String webdav_path = AccountUtils.getWebdavPath(mConnChkRunnable
+                .getDiscoveredVersion());
+
+        try {
+            mBaseUrl = prefix + url;
+            String url_str = prefix + url + webdav_path;
+            uri = new URL(url_str);
+        } catch (MalformedURLException e) {
+            // should not happend
+            e.printStackTrace();
+        }
+
+        showDialog(DIALOG_LOGIN_PROGRESS);
+        mAuthRunnable = new AuthenticationRunnable(uri, username, password);
+        mAuthRunnable.setOnAuthenticationResultListener(this, mHandler);
+        mAuthThread = new Thread(mAuthRunnable);
+        mAuthThread.start();
     }
 
-    showDialog(DIALOG_LOGIN_PROGRESS);
-    mAuthRunnable = new AuthenticationRunnable(uri, username, password);
-    mAuthRunnable.setOnAuthenticationResultListener(this, mHandler);
-    mAuthThread = new Thread(mAuthRunnable);
-    mAuthThread.start();
-  }
-  
-  @Override
-  public void onConnectionCheckResult(ResultType type) {
-    mStatusText = mStatusIcon = 0;
-    mStatusCorrect = false;
-    String t_url = ((TextView) findViewById(R.id.host_URL)).getText().toString().toLowerCase();
-
-    switch (type) {
-      case OK:
-        // ugly as hell
-        if (t_url.startsWith("http://") || t_url.startsWith("https://")) {
-          mIsSslConn = t_url.startsWith("http://") ? false : true;
-          mStatusIcon = R.drawable.ic_ok;
-          mStatusText = R.string.auth_connection_established;
-          mStatusCorrect = true;
-        } else {
-          mIsSslConn = true;
-          mStatusIcon = android.R.drawable.ic_secure;
-          mStatusText =  R.string.auth_secure_connection;
-          mStatusCorrect = true;          
+    @Override
+    public void onConnectionCheckResult(ResultType type) {
+        mStatusText = mStatusIcon = 0;
+        mStatusCorrect = false;
+        String t_url = ((TextView) findViewById(R.id.host_URL)).getText()
+                .toString().toLowerCase();
+
+        switch (type) {
+        case OK:
+            // ugly as hell
+            if (t_url.startsWith("http://") || t_url.startsWith("https://")) {
+                mIsSslConn = t_url.startsWith("http://") ? false : true;
+                mStatusIcon = R.drawable.ic_ok;
+                mStatusText = R.string.auth_connection_established;
+                mStatusCorrect = true;
+            } else {
+                mIsSslConn = true;
+                mStatusIcon = android.R.drawable.ic_secure;
+                mStatusText = R.string.auth_secure_connection;
+                mStatusCorrect = true;
+            }
+            break;
+        case OK_NO_SSL:
+            mStatusIcon = android.R.drawable.ic_secure;
+            mStatusText = R.string.auth_nossl_plain_ok_title;
+            mStatusCorrect = true;
+            mIsSslConn = false;
+            break;
+        case TIMEOUT:
+        case INORRECT_ADDRESS:
+        case SSL_INIT_ERROR:
+        case HOST_NOT_AVAILABLE:
+            mStatusIcon = R.drawable.common_error;
+            mStatusText = R.string.auth_unknow_host_title;
+            break;
+        case NO_NETWORK_CONNECTION:
+            mStatusIcon = R.drawable.no_network;
+            mStatusText = R.string.auth_no_net_conn_title;
+            break;
+        case INSTANCE_NOT_CONFIGURED:
+            mStatusIcon = R.drawable.common_error;
+            mStatusText = R.string.auth_not_configured_title;
+            break;
+        case UNKNOWN_ERROR:
+            mStatusIcon = R.drawable.common_error;
+            mStatusText = R.string.auth_unknow_error;
+            break;
+        case FILE_NOT_FOUND:
+            mStatusIcon = R.drawable.common_error;
+            mStatusText = R.string.auth_incorrect_path_title;
+            break;
+        default:
+            Log.e(TAG, "Incorrect connection checker result type: " + type);
         }
-        break;
-      case OK_NO_SSL:
-        mStatusIcon = android.R.drawable.ic_secure;
-        mStatusText = R.string.auth_nossl_plain_ok_title;
-        mStatusCorrect = true;
-        mIsSslConn = false;
-        break;
-      case TIMEOUT:
-      case INORRECT_ADDRESS:
-      case SSL_INIT_ERROR:
-      case HOST_NOT_AVAILABLE:
-        mStatusIcon = R.drawable.common_error;
-        mStatusText = R.string.auth_unknow_host_title;
-        break;
-      case NO_NETWORK_CONNECTION:
-        mStatusIcon = R.drawable.no_network;
-        mStatusText = R.string.auth_no_net_conn_title;
-        break;
-      case INSTANCE_NOT_CONFIGURED:
-        mStatusIcon = R.drawable.common_error;
-        mStatusText = R.string.auth_not_configured_title;
-        break;
-      case UNKNOWN_ERROR:
-        mStatusIcon = R.drawable.common_error;
-        mStatusText = R.string.auth_unknow_error;
-        break;
-      case FILE_NOT_FOUND:
-        mStatusIcon = R.drawable.common_error;
-        mStatusText = R.string.auth_incorrect_path_title;
-        break;
-      default:
-        Log.e(TAG, "Incorrect connection checker result type: " + type);
+        setResultIconAndText(mStatusIcon, mStatusText);
+        if (!mStatusCorrect)
+            findViewById(R.id.refreshButton).setVisibility(View.VISIBLE);
+        else
+            findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);
+        findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
     }
-    setResultIconAndText(mStatusIcon, mStatusText);
-    if (!mStatusCorrect)
-      findViewById(R.id.refreshButton).setVisibility(View.VISIBLE);
-    else
-      findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);
-    findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);
-  }
-
-  @Override
-  public void onFocusChange(View view, boolean hasFocus) {
-    if (view.getId() == R.id.host_URL) {
-      if (!hasFocus) {
-        TextView tv = ((TextView)findViewById(R.id.host_URL));
-        String uri = tv.getText().toString();
-        if (uri.length() != 0) {
-          setResultIconAndText(R.drawable.progress_small, R.string.auth_testing_connection);
-          mConnChkRunnable = new ConnectionCheckerRunnable(uri, this);
-          mConnChkRunnable.setListener(this, mHandler);
-          mAuthThread = new Thread(mConnChkRunnable);
-          mAuthThread.start();
-        } else {
-          findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);
-          setResultIconAndText(0, 0);
+
+    @Override
+    public void onFocusChange(View view, boolean hasFocus) {
+        if (view.getId() == R.id.host_URL) {
+            if (!hasFocus) {
+                TextView tv = ((TextView) findViewById(R.id.host_URL));
+                String uri = tv.getText().toString();
+                if (uri.length() != 0) {
+                    setResultIconAndText(R.drawable.progress_small,
+                            R.string.auth_testing_connection);
+                    mConnChkRunnable = new ConnectionCheckerRunnable(uri, this);
+                    mConnChkRunnable.setListener(this, mHandler);
+                    mAuthThread = new Thread(mConnChkRunnable);
+                    mAuthThread.start();
+                } else {
+                    findViewById(R.id.refreshButton).setVisibility(
+                            View.INVISIBLE);
+                    setResultIconAndText(0, 0);
+                }
+            }
+        } else if (view.getId() == R.id.account_password) {
+            ImageView iv = (ImageView) findViewById(R.id.viewPassword);
+            if (hasFocus) {
+                iv.setVisibility(View.VISIBLE);
+            } else {
+                TextView v = (TextView) findViewById(R.id.account_password);
+                int input_type = InputType.TYPE_CLASS_TEXT
+                        | InputType.TYPE_TEXT_VARIATION_PASSWORD;
+                v.setInputType(input_type);
+                iv.setVisibility(View.INVISIBLE);
+            }
         }
-      }
-    } else if (view.getId() == R.id.account_password) {
-      ImageView iv = (ImageView) findViewById(R.id.viewPassword);
-      if (hasFocus) {
-        iv.setVisibility(View.VISIBLE);
-      } else {
-        TextView v = (TextView) findViewById(R.id.account_password);
-        int input_type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD; 
-        v.setInputType(input_type);
-        iv.setVisibility(View.INVISIBLE);
-      }
     }
-  }
-  
-  private void setResultIconAndText(int drawable_id, int text_id) {
-    ImageView iv = (ImageView) findViewById(R.id.action_indicator);
-    TextView tv = (TextView) findViewById(R.id.status_text);
-    
-    if (drawable_id == 0 && text_id == 0) {
-      iv.setVisibility(View.INVISIBLE);
-      tv.setVisibility(View.INVISIBLE);
-    } else {
-      iv.setImageResource(drawable_id);
-      tv.setText(text_id);
-      iv.setVisibility(View.VISIBLE);
-      tv.setVisibility(View.VISIBLE);
+
+    private void setResultIconAndText(int drawable_id, int text_id) {
+        ImageView iv = (ImageView) findViewById(R.id.action_indicator);
+        TextView tv = (TextView) findViewById(R.id.status_text);
+
+        if (drawable_id == 0 && text_id == 0) {
+            iv.setVisibility(View.INVISIBLE);
+            tv.setVisibility(View.INVISIBLE);
+        } else {
+            iv.setImageResource(drawable_id);
+            tv.setText(text_id);
+            iv.setVisibility(View.VISIBLE);
+            tv.setVisibility(View.VISIBLE);
+        }
     }
-  }
-
-  @Override
-  public void onClick(View v) {
-    if (v.getId() == R.id.refreshButton) {
-        onFocusChange(findViewById(R.id.host_URL), false);
-    } else if (v.getId() == R.id.viewPassword) {
-      TextView view = (TextView) findViewById(R.id.account_password);
-      int input_type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
-      view.setInputType(input_type);
+
+    @Override
+    public void onClick(View v) {
+        if (v.getId() == R.id.refreshButton) {
+            onFocusChange(findViewById(R.id.host_URL), false);
+        } else if (v.getId() == R.id.viewPassword) {
+            TextView view = (TextView) findViewById(R.id.account_password);
+            int input_type = InputType.TYPE_CLASS_TEXT
+                    | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
+            view.setInputType(input_type);
+        }
     }
-  }
 }

+ 19 - 19
src/eu/alefzero/owncloud/ui/activity/FileDetailActivity.java

@@ -17,7 +17,6 @@
  */
 package eu.alefzero.owncloud.ui.activity;
 
-
 import android.os.Bundle;
 import android.support.v4.app.FragmentTransaction;
 import android.view.Window;
@@ -28,26 +27,27 @@ import eu.alefzero.owncloud.R;
 import eu.alefzero.owncloud.ui.fragment.FileDetailFragment;
 
 /**
- * This activity displays the details of a file like
- * its name, its size and so on.
+ * This activity displays the details of a file like its name, its size and so
+ * on.
+ * 
  * @author Bartek Przybylski
- *
+ * 
  */
 public class FileDetailActivity extends SherlockFragmentActivity {
-  private FileDetailFragment mFileDetail;
-  
-@Override
-protected void onCreate(Bundle savedInstanceState) {
-  // TODO Auto-generated method stub
-  super.onCreate(savedInstanceState);
-  getWindow().requestFeature(Window.FEATURE_NO_TITLE);
-  setContentView(R.layout.file_activity_details);
-  
-  mFileDetail = new FileDetailFragment();
-  FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
-  ft.add(R.id.fileDetail, mFileDetail);
-  ft.commit();
-  
-}
+    private FileDetailFragment mFileDetail;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        // TODO Auto-generated method stub
+        super.onCreate(savedInstanceState);
+        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
+        setContentView(R.layout.file_activity_details);
+
+        mFileDetail = new FileDetailFragment();
+        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
+        ft.add(R.id.fileDetail, mFileDetail);
+        ft.commit();
+
+    }
 
 }

+ 357 - 351
src/eu/alefzero/owncloud/ui/activity/FileDisplayActivity.java

@@ -72,376 +72,382 @@ import eu.alefzero.webdav.WebdavClient;
  */
 
 public class FileDisplayActivity extends SherlockFragmentActivity implements
-		OnNavigationListener, OnClickListener {
-	private ArrayAdapter<String> mDirectories;
-	private DataStorageManager mStorageManager;
-
-	private SyncBroadcastReceiver  syncBroadcastRevceiver;
-	
-	private static final int DIALOG_SETUP_ACCOUNT = 0;
-	private static final int DIALOG_CREATE_DIR = 1;
-	
-	private static final int REQUEST_ACCOUNT_SETUP = 0;
-	private static final int ACTION_SELECT_FILE = 1;
-
-	public void pushPath(String path) {
-		mDirectories.insert(path, 0);
-	}
-
-	public boolean popPath() {
-		mDirectories.remove(mDirectories.getItem(0));
-		return !mDirectories.isEmpty();
-	}
-
-	@Override
-  protected Dialog onCreateDialog(int id) {
-    Dialog dialog;
-    AlertDialog.Builder builder;
-    switch(id){
-    case DIALOG_SETUP_ACCOUNT:
-      builder = new AlertDialog.Builder(this);
-      builder.setTitle(R.string.main_tit_accsetup);
-      builder.setMessage(R.string.main_wrn_accsetup);
-      builder.setCancelable(false);
-      builder.setPositiveButton(android.R.string.ok, this);
-      builder.setNegativeButton(android.R.string.cancel, this);
-      dialog = builder.create();
-      break;
-    case DIALOG_CREATE_DIR:
-    {
-      builder = new Builder(this);
-      final EditText dirName = new EditText(getBaseContext());
-      final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
-      builder.setView(dirName);
-      builder.setTitle(R.string.uploader_info_dirname);
-      int typed_color = getResources().getColor(R.color.setup_text_typed);
-      dirName.setTextColor(typed_color);
-
-      builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
-        public void onClick(DialogInterface dialog, int which) {
-          String s = dirName.getText().toString();
-          if (s.trim().length() == 0) {
-            dialog.cancel();
+        OnNavigationListener, OnClickListener {
+    private ArrayAdapter<String> mDirectories;
+    private DataStorageManager mStorageManager;
+
+    private SyncBroadcastReceiver syncBroadcastRevceiver;
+
+    private static final int DIALOG_SETUP_ACCOUNT = 0;
+    private static final int DIALOG_CREATE_DIR = 1;
+
+    private static final int REQUEST_ACCOUNT_SETUP = 0;
+    private static final int ACTION_SELECT_FILE = 1;
+
+    public void pushPath(String path) {
+        mDirectories.insert(path, 0);
+    }
+
+    public boolean popPath() {
+        mDirectories.remove(mDirectories.getItem(0));
+        return !mDirectories.isEmpty();
+    }
+
+    @Override
+    protected Dialog onCreateDialog(int id) {
+        Dialog dialog;
+        AlertDialog.Builder builder;
+        switch (id) {
+        case DIALOG_SETUP_ACCOUNT:
+            builder = new AlertDialog.Builder(this);
+            builder.setTitle(R.string.main_tit_accsetup);
+            builder.setMessage(R.string.main_wrn_accsetup);
+            builder.setCancelable(false);
+            builder.setPositiveButton(android.R.string.ok, this);
+            builder.setNegativeButton(android.R.string.cancel, this);
+            dialog = builder.create();
+            break;
+        case DIALOG_CREATE_DIR: {
+            builder = new Builder(this);
+            final EditText dirName = new EditText(getBaseContext());
+            final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
+            builder.setView(dirName);
+            builder.setTitle(R.string.uploader_info_dirname);
+            int typed_color = getResources().getColor(R.color.setup_text_typed);
+            dirName.setTextColor(typed_color);
+
+            builder.setPositiveButton(android.R.string.ok,
+                    new OnClickListener() {
+                        public void onClick(DialogInterface dialog, int which) {
+                            String s = dirName.getText().toString();
+                            if (s.trim().length() == 0) {
+                                dialog.cancel();
+                                return;
+                            }
+
+                            String path = "";
+                            for (int i = mDirectories.getCount() - 2; i >= 0; --i) {
+                                path += "/" + mDirectories.getItem(i);
+                            }
+                            OCFile parent = mStorageManager.getFileByPath(path
+                                    + "/");
+                            path += s + "/";
+                            Thread thread = new Thread(new DirectoryCreator(
+                                    path, a));
+                            thread.start();
+
+                            OCFile new_file = new OCFile(path);
+                            new_file.setMimetype("DIR");
+                            new_file.setParentId(parent.getParentId());
+                            mStorageManager.saveFile(new_file);
+
+                            dialog.dismiss();
+                        }
+                    });
+            builder.setNegativeButton(R.string.common_cancel,
+                    new OnClickListener() {
+                        public void onClick(DialogInterface dialog, int which) {
+                            dialog.cancel();
+                        }
+                    });
+            dialog = builder.create();
+            break;
+        }
+        default:
+            dialog = null;
+        }
+
+        return dialog;
+    }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        if (!accountsAreSetup()) {
+            showDialog(DIALOG_SETUP_ACCOUNT);
+            return;
+        }
+
+        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
+        setProgressBarIndeterminateVisibility(false);
+        // if (getSupportFragmentManager().findFragmentById(R.id.fileList) ==
+        // null)
+        setContentView(R.layout.files);
+
+    }
+
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        boolean retval = true;
+        switch (item.getItemId()) {
+        case R.id.settingsItem: {
+            Intent i = new Intent(this, Preferences.class);
+            startActivity(i);
+            break;
+        }
+        case R.id.createDirectoryItem: {
+            showDialog(DIALOG_CREATE_DIR);
+            break;
+        }
+        case R.id.startSync: {
+            Bundle bundle = new Bundle();
+            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
+            ContentResolver.requestSync(
+                    AccountUtils.getCurrentOwnCloudAccount(this),
+                    "org.owncloud", bundle);
+            break;
+        }
+        case R.id.action_upload: {
+            Intent action = new Intent(Intent.ACTION_GET_CONTENT);
+            action = action.setType("*/*")
+                    .addCategory(Intent.CATEGORY_OPENABLE);
+            startActivityForResult(
+                    Intent.createChooser(action, "Upload file from..."),
+                    ACTION_SELECT_FILE);
+            break;
+        }
+
+        case android.R.id.home: {
+            Intent i = new Intent(this, AccountSelectActivity.class);
+            startActivity(i);
+            finish();
+            break;
+        }
+        default:
+            retval = false;
+        }
+        return retval;
+    }
+
+    @Override
+    public void onBackPressed() {
+        if (mDirectories.getCount() == 1) {
+            finish();
             return;
-          }
-
-          String path = "";
-          for (int i = mDirectories.getCount() - 2; i >= 0; --i) {
-            path += "/" + mDirectories.getItem(i);
-          }
-          OCFile parent = mStorageManager.getFileByPath(path + "/");
-          path += s + "/";
-          Thread thread = new Thread(new DirectoryCreator(path, a));
-          thread.start();
-          
-          OCFile new_file = new OCFile(path);
-          new_file.setMimetype("DIR");
-          new_file.setParentId(parent.getParentId());
-          mStorageManager.saveFile(new_file);
-
-          dialog.dismiss();
         }
-      });
-      builder.setNegativeButton(R.string.common_cancel,
-          new OnClickListener() {
-            public void onClick(DialogInterface dialog, int which) {
-              dialog.cancel();
+        popPath();
+        ((FileListFragment) getSupportFragmentManager().findFragmentById(
+                R.id.fileList)).onNavigateUp();
+    }
+
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        MenuInflater inflater = getSherlock().getMenuInflater();
+        inflater.inflate(R.menu.menu, menu);
+        return true;
+    }
+
+    @Override
+    protected void onRestoreInstanceState(Bundle savedInstanceState) {
+        super.onRestoreInstanceState(savedInstanceState);
+        // Check, if there are ownCloud accounts
+        if (!accountsAreSetup()) {
+            showDialog(DIALOG_SETUP_ACCOUNT);
+        }
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        if (!accountsAreSetup()) {
+            showDialog(DIALOG_SETUP_ACCOUNT);
+            return;
+        }
+
+        IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);
+        syncBroadcastRevceiver = new SyncBroadcastReceiver();
+        registerReceiver(syncBroadcastRevceiver, f);
+
+        mDirectories = new CustomArrayAdapter<String>(this,
+                R.layout.sherlock_spinner_dropdown_item);
+        mDirectories.add("/");
+
+        mStorageManager = new FileDataStorageManager(
+                AccountUtils.getCurrentOwnCloudAccount(this),
+                getContentResolver());
+        ActionBar action_bar = getSupportActionBar();
+        action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
+        action_bar.setDisplayShowTitleEnabled(false);
+        action_bar.setListNavigationCallbacks(mDirectories, this);
+        action_bar.setDisplayHomeAsUpEnabled(true);
+    }
+
+    public void onActivityResult(int requestCode, int resultCode, Intent data) {
+        Log.e("ASD", requestCode + " " + resultCode);
+        if (resultCode == RESULT_OK) {
+            if (requestCode == ACTION_SELECT_FILE) {
+                Uri selectedImageUri = data.getData();
+
+                String filemanagerstring = selectedImageUri.getPath();
+                String selectedImagePath = getPath(selectedImageUri);
+                String filepath;
+
+                if (selectedImagePath != null)
+                    filepath = selectedImagePath;
+                else
+                    filepath = filemanagerstring;
+
+                if (filepath == null) {
+                    Log.e("FileDisplay", "Couldnt resolve path to file");
+                    return;
+                }
+
+                Intent i = new Intent(this, FileUploader.class);
+                i.putExtra(FileUploader.KEY_ACCOUNT,
+                        AccountUtils.getCurrentOwnCloudAccount(this));
+                String remotepath = new String();
+                for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
+                    remotepath += "/" + mDirectories.getItem(j);
+                }
+                if (!remotepath.endsWith("/"))
+                    remotepath += "/";
+                remotepath += new File(filepath).getName();
+                Log.e("ASD", remotepath + "");
+
+                i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
+                i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
+                i.putExtra(FileUploader.KEY_UPLOAD_TYPE,
+                        FileUploader.UPLOAD_SINGLE_FILE);
+                startService(i);
             }
-          });
-      dialog = builder.create();
-      break;
+        }
     }
-    default: 
-      dialog = null;
+
+    public String getPath(Uri uri) {
+        String[] projection = { MediaStore.Images.Media.DATA };
+        Cursor cursor = managedQuery(uri, projection, null, null, null);
+        if (cursor != null) {
+            int column_index = cursor
+                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
+            cursor.moveToFirst();
+            return cursor.getString(column_index);
+        } else
+            return null;
     }
-      
-    return dialog;
-  }
 
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
+    @Override
+    protected void onPause() {
+        super.onPause();
+        if (syncBroadcastRevceiver != null) {
+            unregisterReceiver(syncBroadcastRevceiver);
+            syncBroadcastRevceiver = null;
+        }
 
-		if(!accountsAreSetup()){
-      showDialog(DIALOG_SETUP_ACCOUNT);
-      return;
     }
-		
-		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
-    setProgressBarIndeterminateVisibility(false);
-    //if (getSupportFragmentManager().findFragmentById(R.id.fileList) == null)
-      setContentView(R.layout.files);
-    
-	}
-
-	@Override
-	public boolean onOptionsItemSelected(MenuItem item) {
-	  boolean retval = true;
-		switch (item.getItemId()) {
-		case R.id.settingsItem: {
-			Intent i = new Intent(this, Preferences.class);
-			startActivity(i);
-			break;
-		}
-		case R.id.createDirectoryItem: {
-			showDialog(DIALOG_CREATE_DIR);
-			break;
-		}
-		case R.id.startSync: {
-		  Bundle bundle = new Bundle();
-      bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
-      ContentResolver.requestSync(AccountUtils.getCurrentOwnCloudAccount(this),
-		      "org.owncloud",
-		      bundle);
-      break;
-		}
-		case R.id.action_upload: {
-		  Intent action = new Intent(Intent.ACTION_GET_CONTENT);  
-		  action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);  
-		  startActivityForResult(Intent.createChooser(action, "Upload file from..."), ACTION_SELECT_FILE);
-		  break;
-		}
-		  
-		case android.R.id.home: {
-		  Intent i = new Intent(this, AccountSelectActivity.class);
-		  startActivity(i);
-		  finish();
-			break;
-		}
-			default:
-			  retval = false;
-		}
-		return retval;
-	}
-	
-	@Override
-	public void onBackPressed(){
-		if(mDirectories.getCount() == 1) {
-		  finish();
-			return;
-		}
-		popPath();
-		((FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList))
-				.onNavigateUp();
-	}
-
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		MenuInflater inflater = getSherlock().getMenuInflater();
-		inflater.inflate(R.menu.menu, menu);
-		return true;
-	}
-
-	 @Override
-	  protected void onRestoreInstanceState(Bundle savedInstanceState) {
-	    super.onRestoreInstanceState(savedInstanceState);
-	    // Check, if there are ownCloud accounts
-	    if(!accountsAreSetup()){
-	      showDialog(DIALOG_SETUP_ACCOUNT);
-	    }
-	  }
-
-	    
-	 @Override
-	protected void onResume() {
-	  super.onResume();
-	  if(!accountsAreSetup()){
-      showDialog(DIALOG_SETUP_ACCOUNT);
-      return;
+
+    @Override
+    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
+        int i = itemPosition;
+        while (i-- != 0) {
+            onBackPressed();
+        }
+        return true;
     }
-	  
-	   IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);
-	   syncBroadcastRevceiver = new  SyncBroadcastReceiver();
-	   registerReceiver(syncBroadcastRevceiver, f);
-	   
-	   mDirectories = new CustomArrayAdapter<String>(this,
-	        R.layout.sherlock_spinner_dropdown_item);
-	    mDirectories.add("/");
-	    
-	    mStorageManager = new FileDataStorageManager(AccountUtils.getCurrentOwnCloudAccount(this), getContentResolver());
-	    ActionBar action_bar = getSupportActionBar();
-	    action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
-	    action_bar.setDisplayShowTitleEnabled(false);
-	    action_bar.setListNavigationCallbacks(mDirectories, this);
-	    action_bar.setDisplayHomeAsUpEnabled(true);
-	}
-	    
-	 public void onActivityResult(int requestCode, int resultCode, Intent data) {
-	   Log.e("ASD", requestCode + " " + resultCode);
-     if (resultCode == RESULT_OK) {
-         if (requestCode == ACTION_SELECT_FILE) {
-           Uri selectedImageUri = data.getData();
-
-           String filemanagerstring = selectedImageUri.getPath();
-           String selectedImagePath = getPath(selectedImageUri);
-           String filepath;
-
-           if(selectedImagePath!=null)
-               filepath = selectedImagePath;
-           else
-               filepath = filemanagerstring;
-             
-         if (filepath == null) {
-           Log.e("FileDisplay", "Couldnt resolve path to file");
-           return;
-         }
-         
-         Intent i = new Intent(this, FileUploader.class);
-         i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
-         String remotepath = new String();
-         for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
-           remotepath += "/" + mDirectories.getItem(j);
-         }
-         if (!remotepath.endsWith("/")) remotepath += "/";
-         remotepath += new File(filepath).getName();
-         Log.e("ASD", remotepath+"");
-         
-         i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
-         i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
-         i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
-         startService(i);
-       }
-     }
-	 }
-	 
-     public String getPath(Uri uri) {
-       String[] projection = { MediaStore.Images.Media.DATA };
-       Cursor cursor = managedQuery(uri, projection, null, null, null);
-       if(cursor!=null)
-       {
-           int column_index = cursor
-           .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
-           cursor.moveToFirst();
-           return cursor.getString(column_index);
-       }
-       else return null;
-   }
-     
-	 @Override
-	protected void onPause() {
-	  super.onPause();
-	  if (syncBroadcastRevceiver != null) {
-	    unregisterReceiver(syncBroadcastRevceiver);
-	    syncBroadcastRevceiver = null;
-	  }
-	  
-	}
-	 
-	@Override
-	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
-		int i = itemPosition;
-		while (i-- != 0) {
-			onBackPressed();
-		}
-		return true;
-	}
-
-	private class DirectoryCreator implements Runnable {
-		private String mTargetPath;
-		private Account mAccount;
-		private AccountManager mAm;
-
-		public DirectoryCreator(String targetPath, Account account) {
-			mTargetPath = targetPath;
-			mAccount = account;
-			mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
-		}
-
-		@Override
-		public void run() {
-			WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
-					mAccount, AccountAuthenticator.KEY_OC_URL)));
-
-			String username = mAccount.name.substring(0,
-					mAccount.name.lastIndexOf('@'));
-			String password = mAm.getPassword(mAccount);
-
-			wdc.setCredentials(username, password);
-			wdc.allowUnsignedCertificates();
-			wdc.createDirectory(mTargetPath);
-		}
-
-	}
-
-	// Custom array adapter to override text colors
-	private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
-		
-		public CustomArrayAdapter(FileDisplayActivity ctx,
-				int view) {
-			super(ctx, view);
-		}
-
-		public View getView(int position, View convertView,
-                ViewGroup parent) {
+
+    private class DirectoryCreator implements Runnable {
+        private String mTargetPath;
+        private Account mAccount;
+        private AccountManager mAm;
+
+        public DirectoryCreator(String targetPath, Account account) {
+            mTargetPath = targetPath;
+            mAccount = account;
+            mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
+        }
+
+        @Override
+        public void run() {
+            WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
+                    mAccount, AccountAuthenticator.KEY_OC_URL)));
+
+            String username = mAccount.name.substring(0,
+                    mAccount.name.lastIndexOf('@'));
+            String password = mAm.getPassword(mAccount);
+
+            wdc.setCredentials(username, password);
+            wdc.allowUnsignedCertificates();
+            wdc.createDirectory(mTargetPath);
+        }
+
+    }
+
+    // Custom array adapter to override text colors
+    private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
+
+        public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
+            super(ctx, view);
+        }
+
+        public View getView(int position, View convertView, ViewGroup parent) {
             View v = super.getView(position, convertView, parent);
 
-            ((TextView) v).setTextColor(
-                    getResources()
-                    .getColorStateList(android.R.color.white));
+            ((TextView) v).setTextColor(getResources().getColorStateList(
+                    android.R.color.white));
             return v;
         }
-		
-		public View getDropDownView(int position, View convertView,
+
+        public View getDropDownView(int position, View convertView,
                 ViewGroup parent) {
-            View v = super.getDropDownView(position, convertView,
-                    parent);
+            View v = super.getDropDownView(position, convertView, parent);
 
             ((TextView) v).setTextColor(getResources().getColorStateList(
-                            android.R.color.white));
+                    android.R.color.white));
 
             return v;
         }
 
+    }
+
+    public void onClick(DialogInterface dialog, int which) {
+        // In any case - we won't need it anymore
+        dialog.dismiss();
+        switch (which) {
+        case DialogInterface.BUTTON_POSITIVE:
+            Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
+            intent.putExtra("authorities",
+                    new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+            startActivity(intent);
+            break;
+        case DialogInterface.BUTTON_NEGATIVE:
+            finish();
+        }
+
+    }
+
+    /**
+     * Checks, whether or not there are any ownCloud accounts setup.
+     * 
+     * @return true, if there is at least one account.
+     */
+    private boolean accountsAreSetup() {
+        AccountManager accMan = AccountManager.get(this);
+        Account[] accounts = accMan
+                .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+        return accounts.length > 0;
+    }
+
+    private class SyncBroadcastReceiver extends BroadcastReceiver {
+        /**
+         * {@link BroadcastReceiver} to enable syncing feedback in UI
+         */
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            boolean inProgress = intent.getBooleanExtra(
+                    FileSyncService.IN_PROGRESS, false);
+            String account_name = intent
+                    .getStringExtra(FileSyncService.ACCOUNT_NAME);
+            Log.d("FileDisplay", "sync of account " + account_name
+                    + " is in_progress: " + inProgress);
+            setProgressBarIndeterminateVisibility(inProgress);
+            if (!inProgress) {
+                FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
+                        .findFragmentById(R.id.fileList);
+                if (fileListFramgent != null)
+                    fileListFramgent.populateFileList();
+            }
+        }
 
-		
-	}
-	
-	 public void onClick(DialogInterface dialog, int which) {
-	    // In any case - we won't need it anymore
-	    dialog.dismiss();
-	    switch(which){
-	    case DialogInterface.BUTTON_POSITIVE:
-	      Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
-	      intent.putExtra("authorities",
-	          new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
-	      startActivity(intent);
-	      break;
-	    case DialogInterface.BUTTON_NEGATIVE:
-	      finish();
-	    }
-	    
-	  }
-	
-	/**
-   * Checks, whether or not there are any ownCloud accounts 
-   * setup. 
-   *  
-   * @return true, if there is at least one account.
-   */
-  private boolean accountsAreSetup() {
-    AccountManager accMan = AccountManager.get(this);
-    Account[] accounts = accMan
-        .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE); 
-    return accounts.length > 0;
-  }
-  
-  private class SyncBroadcastReceiver extends BroadcastReceiver {
-	  /**
-	   * {@link BroadcastReceiver} to enable syncing feedback in UI
-	   */
-    @Override
-    public void onReceive(Context context, Intent intent) {
-      boolean inProgress = intent.getBooleanExtra(FileSyncService.IN_PROGRESS, false);
-      String account_name = intent.getStringExtra(FileSyncService.ACCOUNT_NAME);
-      Log.d("FileDisplay", "sync of account " + account_name + " is in_progress: " + inProgress);
-      setProgressBarIndeterminateVisibility(inProgress);
-      if (!inProgress) {
-        FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
-        if (fileListFramgent != null)
-          fileListFramgent.populateFileList();
-      }
     }
-    
-  }
-  
-}
+
+}

+ 114 - 111
src/eu/alefzero/owncloud/ui/activity/LandingActivity.java

@@ -38,118 +38,121 @@ import eu.alefzero.owncloud.ui.adapter.LandingScreenAdapter;
 
 /**
  * This activity is used as a landing page when the user first opens this app.
+ * 
  * @author Lennart Rosam
  * 
  */
-public class LandingActivity extends SherlockFragmentActivity implements OnClickListener, OnItemClickListener {
-
-	public static final int DIALOG_SETUP_ACCOUNT = 1;
-	
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.main);
-		
-		// Fill the grid view of the landing screen with icons
-		GridView landingScreenItems = (GridView) findViewById(R.id.homeScreenGrid);
-		landingScreenItems.setAdapter(new LandingScreenAdapter(this));
-		landingScreenItems.setOnItemClickListener(this);
-		
-		// Check, if there are ownCloud accounts
-		if(!accountsAreSetup()){
-			showDialog(DIALOG_SETUP_ACCOUNT);
-		} else {
-			// Start device tracking service 
-			Intent locationServiceIntent = new Intent();
-			locationServiceIntent.setAction("eu.alefzero.owncloud.location.LocationLauncher");
-			sendBroadcast(locationServiceIntent);
-		}
-
-	}
-	
-	@Override
-	protected void onRestart() {
-		super.onRestart();
-		// Check, if there are ownCloud accounts
-		if(!accountsAreSetup()){
-			showDialog(DIALOG_SETUP_ACCOUNT);
-		}
-	}
-
-	@Override
-	protected void onRestoreInstanceState(Bundle savedInstanceState) {
-		super.onRestoreInstanceState(savedInstanceState);
-		// Check, if there are ownCloud accounts
-		if(!accountsAreSetup()){
-			showDialog(DIALOG_SETUP_ACCOUNT);
-		}
-	}
-
-	@Override
-	protected Dialog onCreateDialog(int id) {
-		Dialog dialog;
-		switch(id){
-		case DIALOG_SETUP_ACCOUNT:
-			AlertDialog.Builder builder = new AlertDialog.Builder(this);
-			builder.setTitle(R.string.main_tit_accsetup);
-			builder.setMessage(R.string.main_wrn_accsetup);
-			builder.setCancelable(false);
-			builder.setPositiveButton(R.string.common_ok, this);
-			builder.setNegativeButton(R.string.common_cancel, this);
-			dialog = builder.create();
-			break;
-		default: 
-			dialog = null;
-		}
-			
-		return dialog;
-	}
-
-	public void onClick(DialogInterface dialog, int which) {
-		// In any case - we won't need it anymore
-		dialog.dismiss();
-		switch(which){
-		case DialogInterface.BUTTON_POSITIVE:
-			Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
-			intent.putExtra("authorities",
-					new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
-			startActivity(intent);
-			break;
-		case DialogInterface.BUTTON_NEGATIVE:
-			finish();
-		}
-		
-	}
-	
-	@Override
-	/**
-	 * Start an activity based on the selection
-	 * the user made
-	 */
-	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
-		Intent intent;
-		intent = (Intent) parent.getAdapter().getItem(position);
-		if(intent != null ){
-			startActivity(intent);
-		} else {
-			// TODO: Implement all of this and make this text go away ;-)
-			Toast toast = Toast.makeText(this, "Not yet implemented!", Toast.LENGTH_SHORT);
-			toast.show();
-		} 
-	}
-	
-	/**
-	 * Checks, whether or not there are any ownCloud accounts 
-	 * setup. 
-	 *  
-	 * @return true, if there is at least one account.
-	 */
-	private boolean accountsAreSetup() {
-		AccountManager accMan = AccountManager.get(this);
-		Account[] accounts = accMan
-				.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE); 
-		return accounts.length > 0;
-	}
-
-	
+public class LandingActivity extends SherlockFragmentActivity implements
+        OnClickListener, OnItemClickListener {
+
+    public static final int DIALOG_SETUP_ACCOUNT = 1;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.main);
+
+        // Fill the grid view of the landing screen with icons
+        GridView landingScreenItems = (GridView) findViewById(R.id.homeScreenGrid);
+        landingScreenItems.setAdapter(new LandingScreenAdapter(this));
+        landingScreenItems.setOnItemClickListener(this);
+
+        // Check, if there are ownCloud accounts
+        if (!accountsAreSetup()) {
+            showDialog(DIALOG_SETUP_ACCOUNT);
+        } else {
+            // Start device tracking service
+            Intent locationServiceIntent = new Intent();
+            locationServiceIntent
+                    .setAction("eu.alefzero.owncloud.location.LocationLauncher");
+            sendBroadcast(locationServiceIntent);
+        }
+
+    }
+
+    @Override
+    protected void onRestart() {
+        super.onRestart();
+        // Check, if there are ownCloud accounts
+        if (!accountsAreSetup()) {
+            showDialog(DIALOG_SETUP_ACCOUNT);
+        }
+    }
+
+    @Override
+    protected void onRestoreInstanceState(Bundle savedInstanceState) {
+        super.onRestoreInstanceState(savedInstanceState);
+        // Check, if there are ownCloud accounts
+        if (!accountsAreSetup()) {
+            showDialog(DIALOG_SETUP_ACCOUNT);
+        }
+    }
+
+    @Override
+    protected Dialog onCreateDialog(int id) {
+        Dialog dialog;
+        switch (id) {
+        case DIALOG_SETUP_ACCOUNT:
+            AlertDialog.Builder builder = new AlertDialog.Builder(this);
+            builder.setTitle(R.string.main_tit_accsetup);
+            builder.setMessage(R.string.main_wrn_accsetup);
+            builder.setCancelable(false);
+            builder.setPositiveButton(R.string.common_ok, this);
+            builder.setNegativeButton(R.string.common_cancel, this);
+            dialog = builder.create();
+            break;
+        default:
+            dialog = null;
+        }
+
+        return dialog;
+    }
+
+    public void onClick(DialogInterface dialog, int which) {
+        // In any case - we won't need it anymore
+        dialog.dismiss();
+        switch (which) {
+        case DialogInterface.BUTTON_POSITIVE:
+            Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
+            intent.putExtra("authorities",
+                    new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+            startActivity(intent);
+            break;
+        case DialogInterface.BUTTON_NEGATIVE:
+            finish();
+        }
+
+    }
+
+    @Override
+    /**
+     * Start an activity based on the selection
+     * the user made
+     */
+    public void onItemClick(AdapterView<?> parent, View view, int position,
+            long id) {
+        Intent intent;
+        intent = (Intent) parent.getAdapter().getItem(position);
+        if (intent != null) {
+            startActivity(intent);
+        } else {
+            // TODO: Implement all of this and make this text go away ;-)
+            Toast toast = Toast.makeText(this, "Not yet implemented!",
+                    Toast.LENGTH_SHORT);
+            toast.show();
+        }
+    }
+
+    /**
+     * Checks, whether or not there are any ownCloud accounts setup.
+     * 
+     * @return true, if there is at least one account.
+     */
+    private boolean accountsAreSetup() {
+        AccountManager accMan = AccountManager.get(this);
+        Account[] accounts = accMan
+                .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+        return accounts.length > 0;
+    }
+
 }

+ 190 - 188
src/eu/alefzero/owncloud/ui/activity/Preferences.java

@@ -56,210 +56,212 @@ import eu.alefzero.owncloud.db.DbHandler;
  * 
  */
 public class Preferences extends SherlockPreferenceActivity implements
-		OnPreferenceChangeListener {
-	private static final String TAG = "OwnCloudPreferences";
-	private final int mNewSession = 47;
-	private final int mEditSession = 48;
-	private DbHandler mDbHandler;
-	private Vector<OwnCloudSession> mSessions;
-	private Account[] mAccounts;
-	private ListPreference mAccountList;
-	private ListPreference mTrackingUpdateInterval;
-	private CheckBoxPreference mDeviceTracking;
-	private int mSelectedMenuItem;
+        OnPreferenceChangeListener {
+    private static final String TAG = "OwnCloudPreferences";
+    private final int mNewSession = 47;
+    private final int mEditSession = 48;
+    private DbHandler mDbHandler;
+    private Vector<OwnCloudSession> mSessions;
+    private Account[] mAccounts;
+    private ListPreference mAccountList;
+    private ListPreference mTrackingUpdateInterval;
+    private CheckBoxPreference mDeviceTracking;
+    private int mSelectedMenuItem;
 
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		mDbHandler = new DbHandler(getBaseContext());
-		mSessions = new Vector<OwnCloudSession>();
-		addPreferencesFromResource(R.xml.preferences);
-		registerForContextMenu(getListView());
-		populateAccountList();
-		ActionBar actionBar = getSherlock().getActionBar();
-		actionBar.setDisplayHomeAsUpEnabled(true);
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mDbHandler = new DbHandler(getBaseContext());
+        mSessions = new Vector<OwnCloudSession>();
+        addPreferencesFromResource(R.xml.preferences);
+        registerForContextMenu(getListView());
+        populateAccountList();
+        ActionBar actionBar = getSherlock().getActionBar();
+        actionBar.setDisplayHomeAsUpEnabled(true);
 
-		// Update summary for device tracking preference
-		mTrackingUpdateInterval = (ListPreference) findPreference("devicetracking_update_intervall");
-		String trackingSummary = getResources().getString(
-				R.string.prefs_trackmydevice_interval_summary);
-		trackingSummary = String.format(trackingSummary,
-				mTrackingUpdateInterval.getValue());
-		mTrackingUpdateInterval.setSummary(trackingSummary);
-		mTrackingUpdateInterval.setOnPreferenceChangeListener(this);
+        // Update summary for device tracking preference
+        mTrackingUpdateInterval = (ListPreference) findPreference("devicetracking_update_intervall");
+        String trackingSummary = getResources().getString(
+                R.string.prefs_trackmydevice_interval_summary);
+        trackingSummary = String.format(trackingSummary,
+                mTrackingUpdateInterval.getValue());
+        mTrackingUpdateInterval.setSummary(trackingSummary);
+        mTrackingUpdateInterval.setOnPreferenceChangeListener(this);
 
-		// Enable or disable device tracking service. Listen on events
-		mDeviceTracking = (CheckBoxPreference) findPreference("enable_devicetracking");
-		mDeviceTracking.setOnPreferenceChangeListener(this);
-		
-		// populateSessionList();
-	}
+        // Enable or disable device tracking service. Listen on events
+        mDeviceTracking = (CheckBoxPreference) findPreference("enable_devicetracking");
+        mDeviceTracking.setOnPreferenceChangeListener(this);
 
-	private void populateSessionList() {
-		mSessions.clear();
-		mSessions = mDbHandler.getSessionList();
-		PreferenceScreen ps = getPreferenceScreen();
-		ps.removeAll();
-		addPreferencesFromResource(R.xml.preferences);
-		for (int i = 0; i < mSessions.size(); i++) {
-			Preference preference = new Preference(getBaseContext());
-			preference.setTitle(mSessions.get(i).getName());
-			URI uri;
-			try {
-				uri = new URI(mSessions.get(i).getUrl());
-			} catch (URISyntaxException e) {
-				e.printStackTrace(); // should never happen
-				continue;
-			}
-			preference.setSummary(uri.getScheme() + "://" + uri.getHost()
-					+ uri.getPath());
-			ps.addPreference(preference);
-		}
-	}
+        // populateSessionList();
+    }
 
-	/**
-	 * Populates the account selector
-	 */
-	private void populateAccountList() {
-		AccountManager accMan = AccountManager.get(this);
-		mAccounts = accMan.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
-		mAccountList = (ListPreference) findPreference("select_oc_account");
-		mAccountList.setOnPreferenceChangeListener(this);
+    private void populateSessionList() {
+        mSessions.clear();
+        mSessions = mDbHandler.getSessionList();
+        PreferenceScreen ps = getPreferenceScreen();
+        ps.removeAll();
+        addPreferencesFromResource(R.xml.preferences);
+        for (int i = 0; i < mSessions.size(); i++) {
+            Preference preference = new Preference(getBaseContext());
+            preference.setTitle(mSessions.get(i).getName());
+            URI uri;
+            try {
+                uri = new URI(mSessions.get(i).getUrl());
+            } catch (URISyntaxException e) {
+                e.printStackTrace(); // should never happen
+                continue;
+            }
+            preference.setSummary(uri.getScheme() + "://" + uri.getHost()
+                    + uri.getPath());
+            ps.addPreference(preference);
+        }
+    }
 
-		// Display the name of the current account if there is any
-		Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
-		if (defaultAccount != null) {
-			mAccountList.setSummary(defaultAccount.name);
-		}
+    /**
+     * Populates the account selector
+     */
+    private void populateAccountList() {
+        AccountManager accMan = AccountManager.get(this);
+        mAccounts = accMan.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+        mAccountList = (ListPreference) findPreference("select_oc_account");
+        mAccountList.setOnPreferenceChangeListener(this);
 
-		// Transform accounts into array of string for preferences to use
-		String[] accNames = new String[mAccounts.length];
-		for (int i = 0; i < mAccounts.length; i++) {
-			Account account = mAccounts[i];
-			accNames[i] = account.name;
-		}
+        // Display the name of the current account if there is any
+        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
+        if (defaultAccount != null) {
+            mAccountList.setSummary(defaultAccount.name);
+        }
 
-		mAccountList.setEntries(accNames);
-		mAccountList.setEntryValues(accNames);
-	}
+        // Transform accounts into array of string for preferences to use
+        String[] accNames = new String[mAccounts.length];
+        for (int i = 0; i < mAccounts.length; i++) {
+            Account account = mAccounts[i];
+            accNames[i] = account.name;
+        }
 
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		super.onCreateOptionsMenu(menu);
-		MenuInflater inflater = getSherlock().getMenuInflater();
-		inflater.inflate(R.menu.prefs_menu, menu);
-		return true;
-	}
+        mAccountList.setEntries(accNames);
+        mAccountList.setEntryValues(accNames);
+    }
 
-	@Override
-	public boolean onMenuItemSelected(int featureId, MenuItem item) {
-		super.onMenuItemSelected(featureId, item);
-		Intent intent;
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        super.onCreateOptionsMenu(menu);
+        MenuInflater inflater = getSherlock().getMenuInflater();
+        inflater.inflate(R.menu.prefs_menu, menu);
+        return true;
+    }
 
-		switch (item.getItemId()) {
-		case R.id.addSessionItem:
-			intent = new Intent(this, PreferencesNewSession.class);
-			startActivityForResult(intent, mNewSession);
-			break;
-		case R.id.SessionContextEdit:
-			intent = new Intent(this, PreferencesNewSession.class);
-			intent.putExtra("sessionId", mSessions.get(mSelectedMenuItem)
-					.getEntryId());
-			intent.putExtra("sessionName", mSessions.get(mSelectedMenuItem)
-					.getName());
-			intent.putExtra("sessionURL", mSessions.get(mSelectedMenuItem)
-					.getUrl());
-			startActivityForResult(intent, mEditSession);
-			break;
-		case R.id.SessionContextRemove:
-			OwnCloudSession ocs = mSessions.get(mSelectedMenuItem);
-			mDbHandler.removeSessionWithId(ocs.getEntryId());
-			mSessions.remove(ocs);
-			getPreferenceScreen().removePreference(
-					getPreferenceScreen().getPreference(mSelectedMenuItem + 1));
-			break;
-		case android.R.id.home:
-			intent = new Intent(getBaseContext(), LandingActivity.class);
-			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-			startActivity(intent);
-			break;
-		default:
-			Log.w(TAG, "Unknown menu item triggered");
-			return false;
-		}
-		return true;
-	}
+    @Override
+    public boolean onMenuItemSelected(int featureId, MenuItem item) {
+        super.onMenuItemSelected(featureId, item);
+        Intent intent;
 
-	@Override
-	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
-		super.onActivityResult(requestCode, resultCode, data);
-		if (resultCode == Activity.RESULT_OK) {
-			switch (requestCode) {
-			case mNewSession:
-				mDbHandler.addSession(data.getStringExtra("sessionName"),
-						data.getStringExtra("sessionURL"));
-				getPreferenceScreen().removeAll();
-				addPreferencesFromResource(R.xml.preferences);
-				populateSessionList();
-				break;
-			case mEditSession:
-				mDbHandler.changeSessionFields(
-						data.getIntExtra("sessionId", -1),
-						data.getStringExtra("sessionName"),
-						data.getStringExtra("sessionURL"));
-				populateSessionList();
-				break;
-			}
-		}
-	}
+        switch (item.getItemId()) {
+        case R.id.addSessionItem:
+            intent = new Intent(this, PreferencesNewSession.class);
+            startActivityForResult(intent, mNewSession);
+            break;
+        case R.id.SessionContextEdit:
+            intent = new Intent(this, PreferencesNewSession.class);
+            intent.putExtra("sessionId", mSessions.get(mSelectedMenuItem)
+                    .getEntryId());
+            intent.putExtra("sessionName", mSessions.get(mSelectedMenuItem)
+                    .getName());
+            intent.putExtra("sessionURL", mSessions.get(mSelectedMenuItem)
+                    .getUrl());
+            startActivityForResult(intent, mEditSession);
+            break;
+        case R.id.SessionContextRemove:
+            OwnCloudSession ocs = mSessions.get(mSelectedMenuItem);
+            mDbHandler.removeSessionWithId(ocs.getEntryId());
+            mSessions.remove(ocs);
+            getPreferenceScreen().removePreference(
+                    getPreferenceScreen().getPreference(mSelectedMenuItem + 1));
+            break;
+        case android.R.id.home:
+            intent = new Intent(getBaseContext(), LandingActivity.class);
+            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+            startActivity(intent);
+            break;
+        default:
+            Log.w(TAG, "Unknown menu item triggered");
+            return false;
+        }
+        return true;
+    }
 
-	@Override
-	public void onCreateContextMenu(ContextMenu menu, View v,
-			ContextMenuInfo menuInfo) {
-		super.onCreateContextMenu(menu, v, menuInfo);
-		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
-		mSelectedMenuItem = info.position - 1;
-		menu.setHeaderTitle(mSessions.get(mSelectedMenuItem).getName());
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        super.onActivityResult(requestCode, resultCode, data);
+        if (resultCode == Activity.RESULT_OK) {
+            switch (requestCode) {
+            case mNewSession:
+                mDbHandler.addSession(data.getStringExtra("sessionName"),
+                        data.getStringExtra("sessionURL"));
+                getPreferenceScreen().removeAll();
+                addPreferencesFromResource(R.xml.preferences);
+                populateSessionList();
+                break;
+            case mEditSession:
+                mDbHandler.changeSessionFields(
+                        data.getIntExtra("sessionId", -1),
+                        data.getStringExtra("sessionName"),
+                        data.getStringExtra("sessionURL"));
+                populateSessionList();
+                break;
+            }
+        }
+    }
 
-		MenuInflater inflater = getSherlock().getMenuInflater();
-		inflater.inflate(R.menu.session_context_menu, (Menu) menu);
+    @Override
+    public void onCreateContextMenu(ContextMenu menu, View v,
+            ContextMenuInfo menuInfo) {
+        super.onCreateContextMenu(menu, v, menuInfo);
+        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
+        mSelectedMenuItem = info.position - 1;
+        menu.setHeaderTitle(mSessions.get(mSelectedMenuItem).getName());
 
-	}
+        MenuInflater inflater = getSherlock().getMenuInflater();
+        inflater.inflate(R.menu.session_context_menu, (Menu) menu);
 
-	@Override
-	protected void onDestroy() {
-		mDbHandler.close();
-		super.onDestroy();
-	}
+    }
 
-	@Override
-	/**
-	 * Updates various summaries after updates. Also starts and stops 
-	 * the
-	 */
-	public boolean onPreferenceChange(Preference preference, Object newValue) {
-		// Update current account summary
-		if (preference.equals(mAccountList)) {
-			mAccountList.setSummary(newValue.toString());
-		} 
-		
-		// Update tracking interval summary
-		else if (preference.equals(mTrackingUpdateInterval)) {
-			String trackingSummary = getResources().getString(
-					R.string.prefs_trackmydevice_interval_summary);
-			trackingSummary = String.format(trackingSummary,
-					newValue.toString());
-			mTrackingUpdateInterval.setSummary(trackingSummary);
-		} 
-		
-		// Start or stop tracking service
-		else if (preference.equals(mDeviceTracking)) {
-			Intent locationServiceIntent = new Intent();
-			locationServiceIntent.setAction("eu.alefzero.owncloud.location.LocationLauncher");
-			locationServiceIntent.putExtra("TRACKING_SETTING", (Boolean) newValue);
-			sendBroadcast(locationServiceIntent);
-		}
-		return true;
-	}
+    @Override
+    protected void onDestroy() {
+        mDbHandler.close();
+        super.onDestroy();
+    }
+
+    @Override
+    /**
+     * Updates various summaries after updates. Also starts and stops 
+     * the
+     */
+    public boolean onPreferenceChange(Preference preference, Object newValue) {
+        // Update current account summary
+        if (preference.equals(mAccountList)) {
+            mAccountList.setSummary(newValue.toString());
+        }
+
+        // Update tracking interval summary
+        else if (preference.equals(mTrackingUpdateInterval)) {
+            String trackingSummary = getResources().getString(
+                    R.string.prefs_trackmydevice_interval_summary);
+            trackingSummary = String.format(trackingSummary,
+                    newValue.toString());
+            mTrackingUpdateInterval.setSummary(trackingSummary);
+        }
+
+        // Start or stop tracking service
+        else if (preference.equals(mDeviceTracking)) {
+            Intent locationServiceIntent = new Intent();
+            locationServiceIntent
+                    .setAction("eu.alefzero.owncloud.location.LocationLauncher");
+            locationServiceIntent.putExtra("TRACKING_SETTING",
+                    (Boolean) newValue);
+            sendBroadcast(locationServiceIntent);
+        }
+        return true;
+    }
 
 }

+ 85 - 116
src/eu/alefzero/owncloud/ui/activity/PreferencesNewSession.java

@@ -6,124 +6,93 @@ import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 
-public class PreferencesNewSession extends AccountAuthenticatorActivity implements OnClickListener {
-  @Override
-  public void onCreate(Bundle savedInstanceState){
-    super.onCreate(savedInstanceState);
-    //setContentView(R.layout.add_new_session);
-    /*
-    EditText et;// = (EditText) findViewById(R.id.newSession_sessionName);
-    
-    et = (EditText) findViewById(R.id.newSession_URL);
-    if (getIntent().hasExtra("sessionURL")) {
-      try {
-        URI uri = new URI(getIntent().getStringExtra("sessionURL"));
-        String url = uri.getHost();
-        if (uri.getPort() != -1) {
-          url += ":" + String.valueOf(uri.getPort());
-        }
-        if (uri.getPath() != null) {
-          url += uri.getPath();
-        } else {
-          url += "/";
-        }
-        et.setText(url);
-        et = (EditText) findViewById(R.id.newSession_username);
-        if (uri.getAuthority() != null) {
-          if (uri.getUserInfo().indexOf(':') != -1) {
-            et.setText(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(':')));
-            et = (EditText) findViewById(R.id.newSession_password);
-            et.setText(uri.getUserInfo().substring(uri.getUserInfo().indexOf(':')+1));
-          } else {
-            et.setText(uri.getUserInfo());
-          }
-        }
-        
-      } catch (URISyntaxException e) {
-        Log.e(TAG, "Incorrect URI syntax " + e.getLocalizedMessage());
-      }
+public class PreferencesNewSession extends AccountAuthenticatorActivity
+        implements OnClickListener {
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        // setContentView(R.layout.add_new_session);
+        /*
+         * EditText et;// = (EditText)
+         * findViewById(R.id.newSession_sessionName);
+         * 
+         * et = (EditText) findViewById(R.id.newSession_URL); if
+         * (getIntent().hasExtra("sessionURL")) { try { URI uri = new
+         * URI(getIntent().getStringExtra("sessionURL")); String url =
+         * uri.getHost(); if (uri.getPort() != -1) { url += ":" +
+         * String.valueOf(uri.getPort()); } if (uri.getPath() != null) { url +=
+         * uri.getPath(); } else { url += "/"; } et.setText(url); et =
+         * (EditText) findViewById(R.id.newSession_username); if
+         * (uri.getAuthority() != null) { if (uri.getUserInfo().indexOf(':') !=
+         * -1) { et.setText(uri.getUserInfo().substring(0,
+         * uri.getUserInfo().indexOf(':'))); et = (EditText)
+         * findViewById(R.id.newSession_password);
+         * et.setText(uri.getUserInfo().substring
+         * (uri.getUserInfo().indexOf(':')+1)); } else {
+         * et.setText(uri.getUserInfo()); } }
+         * 
+         * } catch (URISyntaxException e) { Log.e(TAG, "Incorrect URI syntax " +
+         * e.getLocalizedMessage()); } }
+         * 
+         * mReturnData = new Intent(); setResult(Activity.RESULT_OK,
+         * mReturnData); ((Button)
+         * findViewById(R.id.button1)).setOnClickListener(this); ((Button)
+         * findViewById(R.id.button2)).setOnClickListener(this);
+         */
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+    }
+
+    public void onClick(View v) {
+        /*
+         * switch (v.getId()) { case R.id.button1: Intent intent = new Intent();
+         * if (getIntent().hasExtra("sessionId")) { intent.putExtra("sessionId",
+         * getIntent().getIntExtra("sessionId", -1)); } //String sessionName =
+         * ((EditText)
+         * findViewById(R.id.newSession_sessionName)).getText().toString(); //
+         * if (sessionName.trim().equals("") || !isNameValid(sessionName)) { //
+         * Toast.makeText(this, R.string.new_session_session_name_error,
+         * Toast.LENGTH_LONG).show(); // break; // } URI uri = prepareURI(); if
+         * (uri != null) { //intent.putExtra("sessionName", sessionName);
+         * intent.putExtra("sessionURL", uri.toString());
+         * setResult(Activity.RESULT_OK, intent); AccountManager accMgr =
+         * AccountManager.get(this); Account a = new Account("OwnCloud",
+         * AccountAuthenticatorService.ACCOUNT_TYPE);
+         * accMgr.addAccountExplicitly(a, "asd", null); finish(); } break; case
+         * R.id.button2: setResult(Activity.RESULT_CANCELED); finish(); break; }
+         */
     }
-    
-    mReturnData = new Intent();
-    setResult(Activity.RESULT_OK, mReturnData);
-    ((Button) findViewById(R.id.button1)).setOnClickListener(this);
-    ((Button) findViewById(R.id.button2)).setOnClickListener(this);*/
-  }
-  
-  @Override
-  protected void onResume() {
-    super.onResume();
-  }
 
-  public void onClick(View v) {
-   /* switch (v.getId()) {
-      case R.id.button1:
-        Intent intent = new Intent();
-        if (getIntent().hasExtra("sessionId")) {
-          intent.putExtra("sessionId", getIntent().getIntExtra("sessionId", -1));
-        }
-        //String sessionName = ((EditText) findViewById(R.id.newSession_sessionName)).getText().toString();
-      //  if (sessionName.trim().equals("") || !isNameValid(sessionName)) {
-     //    Toast.makeText(this, R.string.new_session_session_name_error, Toast.LENGTH_LONG).show();
-     //     break;
-       // }
-        URI uri = prepareURI();
-        if (uri != null) {
-          //intent.putExtra("sessionName", sessionName);
-          intent.putExtra("sessionURL", uri.toString());
-          setResult(Activity.RESULT_OK, intent);
-          AccountManager accMgr = AccountManager.get(this);
-          Account a = new Account("OwnCloud", AccountAuthenticatorService.ACCOUNT_TYPE);
-          accMgr.addAccountExplicitly(a, "asd", null);
-          finish();
-        }
-        break;
-      case R.id.button2:
+    /*
+     * private URI prepareURI() { URI uri = null; String url = ""; try { String
+     * username = ((EditText)
+     * findViewById(R.id.newSession_username)).getText().toString().trim();
+     * String password = ((EditText)
+     * findViewById(R.id.newSession_password)).getText().toString().trim();
+     * String hostname = ((EditText)
+     * findViewById(R.id.newSession_URL)).getText().toString().trim(); String
+     * scheme; if (hostname.matches("[A-Za-z]://")) { scheme =
+     * hostname.substring(0, hostname.indexOf("://")+3); hostname =
+     * hostname.substring(hostname.indexOf("://")+3); } else { scheme =
+     * "http://"; } if (!username.equals("")) { if (!password.equals("")) {
+     * username += ":" + password + "@"; } else { username += "@"; } } url =
+     * scheme + username + hostname; Log.i(TAG, url); uri = new URI(url); }
+     * catch (URISyntaxException e) { Log.e(TAG, "Incorrect URI syntax " +
+     * e.getLocalizedMessage()); Toast.makeText(this,
+     * R.string.new_session_uri_error, Toast.LENGTH_LONG).show(); } return uri;
+     * }
+     * 
+     * private boolean isNameValid(String string) { return
+     * string.matches("[A-Za-z0-9 _-]*"); }
+     */
+
+    @Override
+    public void onBackPressed() {
         setResult(Activity.RESULT_CANCELED);
-        finish();
-        break;
-    }*/
-  }
-  
-  /*private URI prepareURI() {
-    URI uri = null;
-    String url = "";
-    try {
-      String username = ((EditText) findViewById(R.id.newSession_username)).getText().toString().trim();
-      String password = ((EditText) findViewById(R.id.newSession_password)).getText().toString().trim();
-      String hostname = ((EditText) findViewById(R.id.newSession_URL)).getText().toString().trim();
-      String scheme;
-      if (hostname.matches("[A-Za-z]://")) {
-        scheme = hostname.substring(0, hostname.indexOf("://")+3);
-        hostname = hostname.substring(hostname.indexOf("://")+3);
-      } else {
-        scheme = "http://";
-      }
-      if (!username.equals("")) {
-        if (!password.equals("")) {
-          username += ":" + password + "@";
-        } else {
-          username += "@";
-        }
-      }
-      url = scheme + username + hostname;
-      Log.i(TAG, url);
-      uri = new URI(url);
-    } catch (URISyntaxException e) {
-      Log.e(TAG, "Incorrect URI syntax " + e.getLocalizedMessage());
-      Toast.makeText(this, R.string.new_session_uri_error, Toast.LENGTH_LONG).show();
+        super.onBackPressed();
     }
-    return uri;
-  }
-  
-  private boolean isNameValid(String string) {
-    return string.matches("[A-Za-z0-9 _-]*");
-  }*/
-  
-  @Override
-  public void onBackPressed() {
-    setResult(Activity.RESULT_CANCELED);
-    super.onBackPressed();
-  }
-  
+
 }

+ 122 - 114
src/eu/alefzero/owncloud/ui/adapter/FileListActionListAdapter.java

@@ -40,124 +40,132 @@ import android.widget.TextView;
 
 public class FileListActionListAdapter implements ListAdapter {
 
-  private Context mContext;
-  private Account mAccount;
-  private String mFilename, mFileType, mFilePath, mFileStoragePath;
-  
-  private final int ITEM_DOWNLOAD = 0;
-  //private final int ITEM_SHARE = 1;
-  
-  public FileListActionListAdapter(Cursor c, Context co, Account account) {
-    mContext = co;
-    mFilename = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_NAME));
-    mFileType = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE));
-    mFilePath = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH));
-    mFileStoragePath = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
-    //mItemId = c.getString(c.getColumnIndex(ProviderTableMeta._ID));
-    mAccount = account;
-  }
-  
-  public boolean areAllItemsEnabled() {
-    // TODO Auto-generated method stub
-    return true;
-  }
-
-  public boolean isEnabled(int position) {
-    // TODO Auto-generated method stub
-    return true;
-  }
-
-  public int getCount() {
-    // TODO Auto-generated method stub
-    return 1;
-  }
-
-  public Object getItem(int position) {
-    if (position == 0) {
-      Intent intent = new Intent(Intent.ACTION_VIEW);
-      if (TextUtils.isEmpty(mFileStoragePath)) {
-        intent.putExtra("toDownload", true);
-        AccountManager accm = (AccountManager) mContext.getSystemService(Context.ACCOUNT_SERVICE);
-        String ocurl = accm.getUserData(mAccount, AccountAuthenticator.KEY_OC_URL);
-        ocurl += mFilePath + mFilename;
-        intent.setData(Uri.parse(ocurl));
-      } else {
-        intent.putExtra("toDownload", false);
-        intent.setDataAndType(Uri.fromFile(new File(mFileStoragePath)), mFileType);
-      }
-      return intent;
+    private Context mContext;
+    private Account mAccount;
+    private String mFilename, mFileType, mFilePath, mFileStoragePath;
+
+    private final int ITEM_DOWNLOAD = 0;
+
+    // private final int ITEM_SHARE = 1;
+
+    public FileListActionListAdapter(Cursor c, Context co, Account account) {
+        mContext = co;
+        mFilename = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_NAME));
+        mFileType = c.getString(c
+                .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE));
+        mFilePath = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH));
+        mFileStoragePath = c.getString(c
+                .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
+        // mItemId = c.getString(c.getColumnIndex(ProviderTableMeta._ID));
+        mAccount = account;
     }
-    return null;
-  }
-
-  public long getItemId(int position) {
-    // TODO Auto-generated method stub
-    return 0;
-  }
-
-  public int getItemViewType(int position) {
-    // TODO Auto-generated method stub
-    return 0;
-  }
-
-  public View getView(int position, View convertView, ViewGroup parent) {
-    View v = convertView;
-    if (v == null) {
-      LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-      v = vi.inflate(R.layout.file_display_action_list_element, null);
+
+    public boolean areAllItemsEnabled() {
+        // TODO Auto-generated method stub
+        return true;
     }
 
-    TextView tv;
-    ImageView iv;
-    switch (position) {
-      case ITEM_DOWNLOAD :
-        tv = (TextView) v.findViewById(R.id.textView1);
-        if (mFileStoragePath == null) {
-          tv.setText("Download");
-        } else {
-          setActionName(tv);
+    public boolean isEnabled(int position) {
+        // TODO Auto-generated method stub
+        return true;
+    }
+
+    public int getCount() {
+        // TODO Auto-generated method stub
+        return 1;
+    }
+
+    public Object getItem(int position) {
+        if (position == 0) {
+            Intent intent = new Intent(Intent.ACTION_VIEW);
+            if (TextUtils.isEmpty(mFileStoragePath)) {
+                intent.putExtra("toDownload", true);
+                AccountManager accm = (AccountManager) mContext
+                        .getSystemService(Context.ACCOUNT_SERVICE);
+                String ocurl = accm.getUserData(mAccount,
+                        AccountAuthenticator.KEY_OC_URL);
+                ocurl += mFilePath + mFilename;
+                intent.setData(Uri.parse(ocurl));
+            } else {
+                intent.putExtra("toDownload", false);
+                intent.setDataAndType(Uri.fromFile(new File(mFileStoragePath)),
+                        mFileType);
+            }
+            return intent;
+        }
+        return null;
+    }
+
+    public long getItemId(int position) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    public int getItemViewType(int position) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    public View getView(int position, View convertView, ViewGroup parent) {
+        View v = convertView;
+        if (v == null) {
+            LayoutInflater vi = (LayoutInflater) mContext
+                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+            v = vi.inflate(R.layout.file_display_action_list_element, null);
+        }
+
+        TextView tv;
+        ImageView iv;
+        switch (position) {
+        case ITEM_DOWNLOAD:
+            tv = (TextView) v.findViewById(R.id.textView1);
+            if (mFileStoragePath == null) {
+                tv.setText("Download");
+            } else {
+                setActionName(tv);
+            }
+            iv = (ImageView) v.findViewById(R.id.imageView1);
+            iv.setImageResource(R.drawable.download);
+            break;
         }
-        iv = (ImageView) v.findViewById(R.id.imageView1);
-        iv.setImageResource(R.drawable.download);
-        break;
+
+        return v;
     }
-    
-    return v;
-  }
-
-  public int getViewTypeCount() {
-    // TODO Auto-generated method stub
-    return 2;
-  }
-
-  public boolean hasStableIds() {
-    // TODO Auto-generated method stub
-    return false;
-  }
-
-  public boolean isEmpty() {
-    // TODO Auto-generated method stub
-    return false;
-  }
-
-  public void registerDataSetObserver(DataSetObserver observer) {
-    // TODO Auto-generated method stub
-    
-  }
-
-  public void unregisterDataSetObserver(DataSetObserver observer) {
-    // TODO Auto-generated method stub
-    
-  }
-
-  private void setActionName(TextView tv) {
-    if (mFileType.matches("image/.*")) {
-      tv.setText("View");
-    } else if (mFileType.matches("audio/.*") || mFileType.matches("video/.*")) {
-      tv.setText("Play");
-    } else {
-      tv.setText("Open");
+
+    public int getViewTypeCount() {
+        // TODO Auto-generated method stub
+        return 2;
+    }
+
+    public boolean hasStableIds() {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    public boolean isEmpty() {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    public void registerDataSetObserver(DataSetObserver observer) {
+        // TODO Auto-generated method stub
+
     }
-  }
-  
+
+    public void unregisterDataSetObserver(DataSetObserver observer) {
+        // TODO Auto-generated method stub
+
+    }
+
+    private void setActionName(TextView tv) {
+        if (mFileType.matches("image/.*")) {
+            tv.setText("View");
+        } else if (mFileType.matches("audio/.*")
+                || mFileType.matches("video/.*")) {
+            tv.setText("Play");
+        } else {
+            tv.setText("Open");
+        }
+    }
+
 }

+ 114 - 109
src/eu/alefzero/owncloud/ui/adapter/FileListListAdapter.java

@@ -34,119 +34,124 @@ import android.widget.ListAdapter;
 import android.widget.TextView;
 
 /**
- * This Adapter populates a ListView with all files and 
- * folders in an ownCloud instance.
+ * This Adapter populates a ListView with all files and folders in an ownCloud
+ * instance.
+ * 
  * @author Bartek Przybylski
- *
+ * 
  */
 public class FileListListAdapter implements ListAdapter {
-  private Context mContext;
-  private OCFile mFile;
-  private Vector<OCFile> mFiles;
-  private DataStorageManager mStorageManager;
-  
-  public FileListListAdapter(OCFile file, DataStorageManager storage_man, Context context) {
-    mFile = file;
-    mStorageManager = storage_man;
-    mFiles = mStorageManager.getDirectoryContent(mFile);
-    mContext = context;
-  }
-  
-  @Override
-  public boolean areAllItemsEnabled() {
-    return true;
-  }
-
-  @Override
-  public boolean isEnabled(int position) {
-    // TODO Auto-generated method stub
-    return true;
-  }
-
-  @Override
-  public int getCount() {
-    return mFiles != null ? mFiles.size() : 0;
-  }
-
-  @Override
-  public Object getItem(int position) {
-    if (mFiles.size() <= position)
-      return null;
-    return mFiles.get(position);
-  }
-
-  @Override
-  public long getItemId(int position) {
-    return mFiles != null ? mFiles.get(position).getFileId() : 0;
-  }
-
-  @Override
-  public int getItemViewType(int position) {
-    // TODO Auto-generated method stub
-    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_layout, null);
+    private Context mContext;
+    private OCFile mFile;
+    private Vector<OCFile> mFiles;
+    private DataStorageManager mStorageManager;
+
+    public FileListListAdapter(OCFile file, DataStorageManager storage_man,
+            Context context) {
+        mFile = file;
+        mStorageManager = storage_man;
+        mFiles = mStorageManager.getDirectoryContent(mFile);
+        mContext = context;
+    }
+
+    @Override
+    public boolean areAllItemsEnabled() {
+        return true;
     }
-    if (mFiles.size() > position) {
-      OCFile file = mFiles.get(position);
-      TextView fileName = (TextView) view.findViewById(R.id.Filename);
-      TextView ext_text = (TextView) view.findViewById(R.id.Extension);
-      String name = file.getFileName();
-      String ext = file.getFileName();
-      if (name.lastIndexOf('.') != -1) {
-        name = name.substring(0, name.lastIndexOf('.'));
-        ext = ext.substring(ext.lastIndexOf('.'));
-      } else {
-        ext = "";
-      }
-      
-      fileName.setText(DisplayUtils.HtmlDecode(name));
-      ext_text.setText(ext);
-      ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
-      if (!file.getMimetype().equals("DIR")) {
-        fileIcon.setImageResource(R.drawable.file);
-      } else {
-        fileIcon.setImageResource(R.drawable.ic_menu_archive);
-      }
-      ImageView down = (ImageView) view.findViewById(R.id.imageView2);
-      if (file.getStoragePath() != null) down.setVisibility(View.VISIBLE);
-      else down.setVisibility(View.INVISIBLE);
-      
+
+    @Override
+    public boolean isEnabled(int position) {
+        // TODO Auto-generated method stub
+        return true;
     }
 
-    return view;
-  }
-
-  @Override
-  public int getViewTypeCount() {
-    return 4;
-  }
-
-  @Override
-  public boolean hasStableIds() {
-    return true;
-  }
-
-  @Override
-  public boolean isEmpty() {
-    return mFiles != null ? mFiles.isEmpty() : false;
-  }
-
-  @Override
-  public void registerDataSetObserver(DataSetObserver observer) {
-    // TODO Auto-generated method stub
-    
-  }
-
-  @Override
-  public void unregisterDataSetObserver(DataSetObserver observer) {
-    // TODO Auto-generated method stub
-    
-  }
+    @Override
+    public int getCount() {
+        return mFiles != null ? mFiles.size() : 0;
+    }
+
+    @Override
+    public Object getItem(int position) {
+        if (mFiles.size() <= position)
+            return null;
+        return mFiles.get(position);
+    }
+
+    @Override
+    public long getItemId(int position) {
+        return mFiles != null ? mFiles.get(position).getFileId() : 0;
+    }
+
+    @Override
+    public int getItemViewType(int position) {
+        // TODO Auto-generated method stub
+        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_layout, null);
+        }
+        if (mFiles.size() > position) {
+            OCFile file = mFiles.get(position);
+            TextView fileName = (TextView) view.findViewById(R.id.Filename);
+            TextView ext_text = (TextView) view.findViewById(R.id.Extension);
+            String name = file.getFileName();
+            String ext = file.getFileName();
+            if (name.lastIndexOf('.') != -1) {
+                name = name.substring(0, name.lastIndexOf('.'));
+                ext = ext.substring(ext.lastIndexOf('.'));
+            } else {
+                ext = "";
+            }
+
+            fileName.setText(DisplayUtils.HtmlDecode(name));
+            ext_text.setText(ext);
+            ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
+            if (!file.getMimetype().equals("DIR")) {
+                fileIcon.setImageResource(R.drawable.file);
+            } else {
+                fileIcon.setImageResource(R.drawable.ic_menu_archive);
+            }
+            ImageView down = (ImageView) view.findViewById(R.id.imageView2);
+            if (file.getStoragePath() != null)
+                down.setVisibility(View.VISIBLE);
+            else
+                down.setVisibility(View.INVISIBLE);
+
+        }
+
+        return view;
+    }
+
+    @Override
+    public int getViewTypeCount() {
+        return 4;
+    }
+
+    @Override
+    public boolean hasStableIds() {
+        return true;
+    }
+
+    @Override
+    public boolean isEmpty() {
+        return mFiles != null ? mFiles.isEmpty() : false;
+    }
+
+    @Override
+    public void registerDataSetObserver(DataSetObserver observer) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void unregisterDataSetObserver(DataSetObserver observer) {
+        // TODO Auto-generated method stub
+
+    }
 }

+ 64 - 64
src/eu/alefzero/owncloud/ui/adapter/LandingScreenAdapter.java

@@ -32,80 +32,80 @@ import eu.alefzero.owncloud.ui.activity.Preferences;
 
 /**
  * Populates the landing screen icons.
+ * 
  * @author Lennart Rosam
- *
+ * 
  */
 public class LandingScreenAdapter extends BaseAdapter {
-	
-	private Context mContext;
 
-	private final Integer[] mLandingScreenIcons = { R.drawable.home,
-			R.drawable.music, R.drawable.contacts,
-			R.drawable.calendar,
-			android.R.drawable.ic_menu_agenda,
-			R.drawable.settings };
+    private Context mContext;
+
+    private final Integer[] mLandingScreenIcons = { R.drawable.home,
+            R.drawable.music, R.drawable.contacts, R.drawable.calendar,
+            android.R.drawable.ic_menu_agenda, R.drawable.settings };
+
+    private final Integer[] mLandingScreenTexts = { R.string.main_files,
+            R.string.main_music, R.string.main_contacts,
+            R.string.main_calendar, R.string.main_bookmarks,
+            R.string.main_settings };
 
-	private final Integer[] mLandingScreenTexts = { R.string.main_files,
-			R.string.main_music, R.string.main_contacts,
-			R.string.main_calendar, R.string.main_bookmarks,
-			R.string.main_settings };
+    public LandingScreenAdapter(Context context) {
+        mContext = context;
+    }
 
-	public LandingScreenAdapter(Context context) {
-		mContext = context;
-	}
+    @Override
+    public int getCount() {
+        return mLandingScreenIcons.length;
+    }
 
-	@Override
-	public int getCount() {
-		return mLandingScreenIcons.length;
-	}
+    @Override
+    /**
+     * Returns the Intent associated with this object
+     * or null if the functionality is not yet implemented
+     */
+    public Object getItem(int position) {
+        Intent intent = new Intent();
 
-	@Override
-	/**
-	 * Returns the Intent associated with this object
-	 * or null if the functionality is not yet implemented
-	 */
-	public Object getItem(int position) {
-		Intent intent = new Intent();
-		
-		switch (position) {
-		case 0:
-			/* 
-			 * The FileDisplayActivity requires the ownCloud account as an parcableExtra.
-			 * We will put in the one that is selected in the preferences
-			 */
-			intent.setClass(mContext, FileDisplayActivity.class);	
-			intent.putExtra("ACCOUNT", AccountUtils.getCurrentOwnCloudAccount(mContext));
-			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-			break;
-		case 5:
-			intent.setClass(mContext, Preferences.class);
-			break;
-		default:
-			intent = null;
-		}
-		return intent;
-	}
+        switch (position) {
+        case 0:
+            /*
+             * The FileDisplayActivity requires the ownCloud account as an
+             * parcableExtra. We will put in the one that is selected in the
+             * preferences
+             */
+            intent.setClass(mContext, FileDisplayActivity.class);
+            intent.putExtra("ACCOUNT",
+                    AccountUtils.getCurrentOwnCloudAccount(mContext));
+            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            break;
+        case 5:
+            intent.setClass(mContext, Preferences.class);
+            break;
+        default:
+            intent = null;
+        }
+        return intent;
+    }
 
-	@Override
-	public long getItemId(int position) {
-		return position;
-	}
+    @Override
+    public long getItemId(int position) {
+        return position;
+    }
 
-	@Override
-	public View getView(int position, View convertView, ViewGroup parent) {
-		if (convertView == null) {
-			LayoutInflater inflator = LayoutInflater.from(mContext);
-			convertView = inflator
-					.inflate(R.layout.landing_page_item, null);
+    @Override
+    public View getView(int position, View convertView, ViewGroup parent) {
+        if (convertView == null) {
+            LayoutInflater inflator = LayoutInflater.from(mContext);
+            convertView = inflator.inflate(R.layout.landing_page_item, null);
 
-			ImageView icon = (ImageView) convertView
-					.findViewById(R.id.gridImage);
-			TextView iconText = (TextView) convertView
-					.findViewById(R.id.gridText);
+            ImageView icon = (ImageView) convertView
+                    .findViewById(R.id.gridImage);
+            TextView iconText = (TextView) convertView
+                    .findViewById(R.id.gridText);
 
-			icon.setImageResource(mLandingScreenIcons[position]);
-			iconText.setText(mLandingScreenTexts[position]);
-		}
-		return convertView;
-	}
+            icon.setImageResource(mLandingScreenIcons[position]);
+            iconText.setText(mLandingScreenTexts[position]);
+        }
+        return convertView;
+    }
 }

+ 175 - 175
src/eu/alefzero/owncloud/ui/fragment/FileDetailFragment.java

@@ -48,180 +48,180 @@ import eu.alefzero.owncloud.datamodel.OCFile;
  * 
  */
 public class FileDetailFragment extends SherlockFragment implements
-		OnClickListener {
-
-	public static final String FILE = "FILE";
-
-	private Intent mIntent;
-	private View mView;
-	private DownloadFinishReceiver mDownloadFinishReceiver;
-	private OCFile mFile;
-
-	private int mLayout;
-	private boolean mEmptyLayout;
-
-	/**
-	 * Default constructor. When inflated by android -> display empty layout
-	 */
-	public FileDetailFragment() {
-		mLayout = R.layout.file_details_empty;
-		mEmptyLayout = true;
-	}
-
-	/**
-	 * Custom construtor. Use with a {@link FragmentTransaction}.
-	 * The intent has to contain {@link FileDetailFragment#FILE} with an OCFile
-	 * and also {@link FileDownloader#EXTRA_ACCOUNT} with the account.
-	 * 
-	 * @param nonEmptyFragment
-	 *            True, to enable file detail rendering
-	 */
-	public FileDetailFragment(Intent intent) {
-		mLayout = R.layout.file_details_fragment;
-		mIntent = intent;
-		mEmptyLayout = false;
-	}
-
-	@Override
-	public void onResume() {
-		super.onResume();
-		mDownloadFinishReceiver = new DownloadFinishReceiver();
-		IntentFilter filter = new IntentFilter(
-				FileDownloader.DOWNLOAD_FINISH_MESSAGE);
-		getActivity().registerReceiver(mDownloadFinishReceiver, filter);
-	}
-
-	@Override
-	public void onPause() {
-		super.onPause();
-		getActivity().unregisterReceiver(mDownloadFinishReceiver);
-		mDownloadFinishReceiver = null;
-	}
-
-	/**
-	 * Use this method to signal this Activity that it shall update its view.
-	 * 
-	 * @param intent
-	 *            The {@link Intent} that contains extra information about this
-	 *            file The intent needs to have these extras:
-	 *            <p>
-	 * 
-	 *            {@link FileDetailFragment#FILE}: An {@link OCFile}
-	 *            {@link FileDownloader#EXTRA_ACCOUNT}: The Account that file
-	 *            belongs to (required for downloading)
-	 */
-	public void updateFileDetails(Intent intent) {
-		mIntent = intent;
-		updateFileDetails();
-	}
-
-	private void updateFileDetails() {
-		mFile = mIntent.getParcelableExtra(FILE);
-
-		if (mFile != null) {
-			// set file details
-			setFilename(mFile.getFileName());
-			setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
-					.getMimetype()));
-			setFilesize(mFile.getFileLength());
-
-			// set file preview if available and possible
-			VideoView videoView = (VideoView) mView
-					.findViewById(R.id.videoView1);
-			videoView.setVisibility(View.INVISIBLE);
-			if (mFile.getPath() == null) {
-				ImageView imageView = (ImageView) getView().findViewById(
-						R.id.imageView2);
-				imageView.setImageResource(R.drawable.download);
-				imageView.setOnClickListener(this);
-			} else {
-				if (mFile.getMimetype().startsWith("image/")) {
-					ImageView imageView = (ImageView) mView
-							.findViewById(R.id.imageView2);
-					Bitmap bmp = BitmapFactory.decodeFile(mFile.getPath());
-					imageView.setImageBitmap(bmp);
-				} else if (mFile.getMimetype().startsWith("video/")) {
-					videoView.setVisibility(View.VISIBLE);
-					videoView.setVideoPath(mFile.getPath());
-					videoView.start();
-				}
-			}
-		}
-	}
-
-	@Override
-	public View onCreateView(LayoutInflater inflater, ViewGroup container,
-			Bundle savedInstanceState) {
-		View view = null;
-
-		view = inflater.inflate(mLayout, container, false);
-		mIntent = getActivity().getIntent();
-		mView = view;
-
-		// make sure we are not using the empty layout
-		if (mEmptyLayout == false) {
-			updateFileDetails();
-		}
-
-		return view;
-	}
-
-	@Override
-	public View getView() {
-		return mView == null ? super.getView() : mView;
-	};
-
-	private void setFilename(String filename) {
-		TextView tv = (TextView) getView().findViewById(R.id.textView1);
-		if (tv != null)
-			tv.setText(filename);
-	}
-
-	private void setFiletype(String mimetype) {
-		TextView tv = (TextView) getView().findViewById(R.id.textView2);
-		if (tv != null)
-			tv.setText(mimetype);
-	}
-
-	private void setFilesize(long filesize) {
-		TextView tv = (TextView) getView().findViewById(R.id.textView3);
-		if (tv != null)
-			tv.setText(DisplayUtils.bitsToHumanReadable(filesize));
-	}
-
-	/**
-	 * Use this to check if the correct layout is loaded. When android
-	 * instanciates this class using the default constructor, the layout will be
-	 * empty.
-	 * 
-	 * Once a user touches a file for the first time, you must instanciate a new
-	 * Fragment with the new FileDetailFragment(true) to inflate the actual
-	 * details
-	 * 
-	 * @return If the layout is empty, this method will return true, otherwise
-	 *         false
-	 */
-	public boolean isEmptyLayout() {
-		return mEmptyLayout;
-	}
-
-	@Override
-	public void onClick(View v) {
-		Toast.makeText(getActivity(), "Downloading", Toast.LENGTH_LONG).show();
-		Intent i = new Intent(getActivity(), FileDownloader.class);
-		i.putExtra(FileDownloader.EXTRA_ACCOUNT,
-				mIntent.getParcelableExtra(FileDownloader.EXTRA_ACCOUNT));
-		i.putExtra(FileDownloader.EXTRA_FILE_PATH,
-				mIntent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
-		getActivity().startService(i);
-	}
-
-	private class DownloadFinishReceiver extends BroadcastReceiver {
-		@Override
-		public void onReceive(Context context, Intent intent) {
-			updateFileDetails();
-		}
-
-	}
+        OnClickListener {
+
+    public static final String FILE = "FILE";
+
+    private Intent mIntent;
+    private View mView;
+    private DownloadFinishReceiver mDownloadFinishReceiver;
+    private OCFile mFile;
+
+    private int mLayout;
+    private boolean mEmptyLayout;
+
+    /**
+     * Default constructor. When inflated by android -> display empty layout
+     */
+    public FileDetailFragment() {
+        mLayout = R.layout.file_details_empty;
+        mEmptyLayout = true;
+    }
+
+    /**
+     * Custom construtor. Use with a {@link FragmentTransaction}. The intent has
+     * to contain {@link FileDetailFragment#FILE} with an OCFile and also
+     * {@link FileDownloader#EXTRA_ACCOUNT} with the account.
+     * 
+     * @param nonEmptyFragment
+     *            True, to enable file detail rendering
+     */
+    public FileDetailFragment(Intent intent) {
+        mLayout = R.layout.file_details_fragment;
+        mIntent = intent;
+        mEmptyLayout = false;
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        mDownloadFinishReceiver = new DownloadFinishReceiver();
+        IntentFilter filter = new IntentFilter(
+                FileDownloader.DOWNLOAD_FINISH_MESSAGE);
+        getActivity().registerReceiver(mDownloadFinishReceiver, filter);
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        getActivity().unregisterReceiver(mDownloadFinishReceiver);
+        mDownloadFinishReceiver = null;
+    }
+
+    /**
+     * Use this method to signal this Activity that it shall update its view.
+     * 
+     * @param intent
+     *            The {@link Intent} that contains extra information about this
+     *            file The intent needs to have these extras:
+     *            <p>
+     * 
+     *            {@link FileDetailFragment#FILE}: An {@link OCFile}
+     *            {@link FileDownloader#EXTRA_ACCOUNT}: The Account that file
+     *            belongs to (required for downloading)
+     */
+    public void updateFileDetails(Intent intent) {
+        mIntent = intent;
+        updateFileDetails();
+    }
+
+    private void updateFileDetails() {
+        mFile = mIntent.getParcelableExtra(FILE);
+
+        if (mFile != null) {
+            // set file details
+            setFilename(mFile.getFileName());
+            setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
+                    .getMimetype()));
+            setFilesize(mFile.getFileLength());
+
+            // set file preview if available and possible
+            VideoView videoView = (VideoView) mView
+                    .findViewById(R.id.videoView1);
+            videoView.setVisibility(View.INVISIBLE);
+            if (mFile.getPath() == null) {
+                ImageView imageView = (ImageView) getView().findViewById(
+                        R.id.imageView2);
+                imageView.setImageResource(R.drawable.download);
+                imageView.setOnClickListener(this);
+            } else {
+                if (mFile.getMimetype().startsWith("image/")) {
+                    ImageView imageView = (ImageView) mView
+                            .findViewById(R.id.imageView2);
+                    Bitmap bmp = BitmapFactory.decodeFile(mFile.getPath());
+                    imageView.setImageBitmap(bmp);
+                } else if (mFile.getMimetype().startsWith("video/")) {
+                    videoView.setVisibility(View.VISIBLE);
+                    videoView.setVideoPath(mFile.getPath());
+                    videoView.start();
+                }
+            }
+        }
+    }
+
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+        View view = null;
+
+        view = inflater.inflate(mLayout, container, false);
+        mIntent = getActivity().getIntent();
+        mView = view;
+
+        // make sure we are not using the empty layout
+        if (mEmptyLayout == false) {
+            updateFileDetails();
+        }
+
+        return view;
+    }
+
+    @Override
+    public View getView() {
+        return mView == null ? super.getView() : mView;
+    };
+
+    private void setFilename(String filename) {
+        TextView tv = (TextView) getView().findViewById(R.id.textView1);
+        if (tv != null)
+            tv.setText(filename);
+    }
+
+    private void setFiletype(String mimetype) {
+        TextView tv = (TextView) getView().findViewById(R.id.textView2);
+        if (tv != null)
+            tv.setText(mimetype);
+    }
+
+    private void setFilesize(long filesize) {
+        TextView tv = (TextView) getView().findViewById(R.id.textView3);
+        if (tv != null)
+            tv.setText(DisplayUtils.bitsToHumanReadable(filesize));
+    }
+
+    /**
+     * Use this to check if the correct layout is loaded. When android
+     * instanciates this class using the default constructor, the layout will be
+     * empty.
+     * 
+     * Once a user touches a file for the first time, you must instanciate a new
+     * Fragment with the new FileDetailFragment(true) to inflate the actual
+     * details
+     * 
+     * @return If the layout is empty, this method will return true, otherwise
+     *         false
+     */
+    public boolean isEmptyLayout() {
+        return mEmptyLayout;
+    }
+
+    @Override
+    public void onClick(View v) {
+        Toast.makeText(getActivity(), "Downloading", Toast.LENGTH_LONG).show();
+        Intent i = new Intent(getActivity(), FileDownloader.class);
+        i.putExtra(FileDownloader.EXTRA_ACCOUNT,
+                mIntent.getParcelableExtra(FileDownloader.EXTRA_ACCOUNT));
+        i.putExtra(FileDownloader.EXTRA_FILE_PATH,
+                mIntent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
+        getActivity().startService(i);
+    }
+
+    private class DownloadFinishReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            updateFileDetails();
+        }
+
+    }
 
 }

+ 157 - 154
src/eu/alefzero/owncloud/ui/fragment/FileListFragment.java

@@ -48,159 +48,162 @@ import eu.alefzero.owncloud.ui.adapter.FileListListAdapter;
  * 
  */
 public class FileListFragment extends FragmentListView {
-	private Account mAccount;
-	private Stack<String> mDirNames;
-	private Vector<OCFile> mFiles;
-	private DataStorageManager mStorageManager;
-
-	public FileListFragment() {
-		mDirNames = new Stack<String>();
-	}
-
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-
-		mAccount = AccountUtils.getCurrentOwnCloudAccount(getActivity());
-		getListView().setDivider(
-				getResources().getDrawable(R.drawable.uploader_list_separator));
-		getListView().setDividerHeight(1);
-
-		populateFileList();
-	}
-
-	@Override
-	public void onItemClick(AdapterView<?> l, View v, int position, long id) {
-		if (mFiles.size() <= position) {
-			throw new IndexOutOfBoundsException("Incorrect item selected");
-		}
-		OCFile file = mFiles.get(position);
-
-		// Update ActionBarPath
-		if (file.getMimetype().equals("DIR")) {
-			String dirname = file.getFileName();
-
-			mDirNames.push(dirname);
-			((FileDisplayActivity) getActivity()).pushPath(dirname);
-
-			populateFileList();
-			return;
-		}
-
-		Intent showDetailsIntent = new Intent(getActivity(),
-				FileDetailActivity.class);
-		showDetailsIntent.putExtra(FileDetailFragment.FILE, file);
-		showDetailsIntent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
-		
-		// Try to find by tag first
-		FileDetailFragment fd = (FileDetailFragment) getFragmentManager()
-				.findFragmentByTag("FileDetails");
-		
-		// Could be the first time the user has touched a file. find by id
-		if(fd == null){
-			fd = (FileDetailFragment) getFragmentManager().findFragmentById(R.id.fileDetail);
-		}
-
-		// Tablets will have this fragment, phones not. Could still be null
-		if (fd != null) {
-			
-			if(fd.isEmptyLayout()){
-				// True, if this is the first time a user taps on a file
-				fd = new FileDetailFragment(showDetailsIntent);
-				FragmentTransaction transaction = getFragmentManager().beginTransaction();
-				transaction.replace(R.id.file_details_container, fd, "FileDetails");
-				transaction.commit();
-			} else {
-				fd.updateFileDetails(showDetailsIntent);
-			}
-			
-		} else {
-			startActivity(showDetailsIntent);
-		}
-	}
-
-	@Override
-	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
-			long arg3) {
-		ClipData.Item item = new ClipData.Item("ASD");
-		ClipDescription cd = new ClipDescription("ASD",
-				new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN });
-		ClipData dragData = new ClipData(cd, item);
-		arg1.startDrag(dragData,
-				new View.DragShadowBuilder(arg0.getChildAt(arg2)), null, 0);
-		return true;
-	}
-
-	/**
-	 * Call this, when the user presses the up button
-	 */
-	public void onNavigateUp() {
-		mDirNames.pop();
-		populateFileList();
-	}
-
-	/**
-	 * Lists the directory
-	 */
-	public void populateFileList() {
-		String s = "/";
-		for (String a : mDirNames)
-			s += a + "/";
-		Log.e("ASD", s);
-
-		mStorageManager = new FileDataStorageManager(mAccount, getActivity()
-				.getContentResolver());
-		OCFile file = mStorageManager.getFileByPath(s);
-		mFiles = mStorageManager.getDirectoryContent(file);
-		if (mFiles == null || mFiles.size() == 0) {
-			Toast.makeText(getActivity(), "There are no files here",
-					Toast.LENGTH_LONG).show();
-		}
-		setListAdapter(new FileListListAdapter(file, mStorageManager,
-				getActivity()));
-	}
-
-	// TODO: Delete this testing stuff.
-	/*
-	 * private void addContact(Account account, String name, String username) {
-	 * Log.i("ASD", "Adding contact: " + name);
-	 * ArrayList<ContentProviderOperation> operationList = new
-	 * ArrayList<ContentProviderOperation>();
-	 * 
-	 * //Create our RawContact ContentProviderOperation.Builder builder =
-	 * ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
-	 * builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
-	 * builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
-	 * builder.withValue(RawContacts.SYNC1, username);
-	 * operationList.add(builder.build());
-	 * 
-	 * //Create a Data record of common type 'StructuredName' for our RawContact
-	 * builder =
-	 * ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
-	 * builder
-	 * .withValueBackReference(ContactsContract.CommonDataKinds.StructuredName
-	 * .RAW_CONTACT_ID, 0); builder.withValue(ContactsContract.Data.MIMETYPE,
-	 * ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
-	 * builder
-	 * .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
-	 * name); operationList.add(builder.build());
-	 * 
-	 * //Create a Data record of custom type
-	 * "vnd.android.cursor.item/vnd.fm.last.android.profile" to display a link
-	 * to the Last.fm profile builder =
-	 * ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
-	 * builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
-	 * builder.withValue(ContactsContract.Data.MIMETYPE,
-	 * "vnd.android.cursor.item/vnd.owncloud.contact.profile");
-	 * builder.withValue(ContactsContract.Data.DATA1, username);
-	 * builder.withValue(ContactsContract.Data.DATA2, "Last.fm Profile");
-	 * builder.withValue(ContactsContract.Data.DATA3, "View profile");
-	 * operationList.add(builder.build());
-	 * 
-	 * try {
-	 * getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY,
-	 * operationList); } catch (Exception e) { Log.e("ASD",
-	 * "Something went wrong during creation! " + e); e.printStackTrace(); } }
-	 */
+    private Account mAccount;
+    private Stack<String> mDirNames;
+    private Vector<OCFile> mFiles;
+    private DataStorageManager mStorageManager;
+
+    public FileListFragment() {
+        mDirNames = new Stack<String>();
+    }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        mAccount = AccountUtils.getCurrentOwnCloudAccount(getActivity());
+        getListView().setDivider(
+                getResources().getDrawable(R.drawable.uploader_list_separator));
+        getListView().setDividerHeight(1);
+
+        populateFileList();
+    }
+
+    @Override
+    public void onItemClick(AdapterView<?> l, View v, int position, long id) {
+        if (mFiles.size() <= position) {
+            throw new IndexOutOfBoundsException("Incorrect item selected");
+        }
+        OCFile file = mFiles.get(position);
+
+        // Update ActionBarPath
+        if (file.getMimetype().equals("DIR")) {
+            String dirname = file.getFileName();
+
+            mDirNames.push(dirname);
+            ((FileDisplayActivity) getActivity()).pushPath(dirname);
+
+            populateFileList();
+            return;
+        }
+
+        Intent showDetailsIntent = new Intent(getActivity(),
+                FileDetailActivity.class);
+        showDetailsIntent.putExtra(FileDetailFragment.FILE, file);
+        showDetailsIntent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
+
+        // Try to find by tag first
+        FileDetailFragment fd = (FileDetailFragment) getFragmentManager()
+                .findFragmentByTag("FileDetails");
+
+        // Could be the first time the user has touched a file. find by id
+        if (fd == null) {
+            fd = (FileDetailFragment) getFragmentManager().findFragmentById(
+                    R.id.fileDetail);
+        }
+
+        // Tablets will have this fragment, phones not. Could still be null
+        if (fd != null) {
+
+            if (fd.isEmptyLayout()) {
+                // True, if this is the first time a user taps on a file
+                fd = new FileDetailFragment(showDetailsIntent);
+                FragmentTransaction transaction = getFragmentManager()
+                        .beginTransaction();
+                transaction.replace(R.id.file_details_container, fd,
+                        "FileDetails");
+                transaction.commit();
+            } else {
+                fd.updateFileDetails(showDetailsIntent);
+            }
+
+        } else {
+            startActivity(showDetailsIntent);
+        }
+    }
+
+    @Override
+    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
+            long arg3) {
+        ClipData.Item item = new ClipData.Item("ASD");
+        ClipDescription cd = new ClipDescription("ASD",
+                new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN });
+        ClipData dragData = new ClipData(cd, item);
+        arg1.startDrag(dragData,
+                new View.DragShadowBuilder(arg0.getChildAt(arg2)), null, 0);
+        return true;
+    }
+
+    /**
+     * Call this, when the user presses the up button
+     */
+    public void onNavigateUp() {
+        mDirNames.pop();
+        populateFileList();
+    }
+
+    /**
+     * Lists the directory
+     */
+    public void populateFileList() {
+        String s = "/";
+        for (String a : mDirNames)
+            s += a + "/";
+        Log.e("ASD", s);
+
+        mStorageManager = new FileDataStorageManager(mAccount, getActivity()
+                .getContentResolver());
+        OCFile file = mStorageManager.getFileByPath(s);
+        mFiles = mStorageManager.getDirectoryContent(file);
+        if (mFiles == null || mFiles.size() == 0) {
+            Toast.makeText(getActivity(), "There are no files here",
+                    Toast.LENGTH_LONG).show();
+        }
+        setListAdapter(new FileListListAdapter(file, mStorageManager,
+                getActivity()));
+    }
+
+    // TODO: Delete this testing stuff.
+    /*
+     * private void addContact(Account account, String name, String username) {
+     * Log.i("ASD", "Adding contact: " + name);
+     * ArrayList<ContentProviderOperation> operationList = new
+     * ArrayList<ContentProviderOperation>();
+     * 
+     * //Create our RawContact ContentProviderOperation.Builder builder =
+     * ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
+     * builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
+     * builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
+     * builder.withValue(RawContacts.SYNC1, username);
+     * operationList.add(builder.build());
+     * 
+     * //Create a Data record of common type 'StructuredName' for our RawContact
+     * builder =
+     * ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
+     * builder
+     * .withValueBackReference(ContactsContract.CommonDataKinds.StructuredName
+     * .RAW_CONTACT_ID, 0); builder.withValue(ContactsContract.Data.MIMETYPE,
+     * ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
+     * builder
+     * .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
+     * name); operationList.add(builder.build());
+     * 
+     * //Create a Data record of custom type
+     * "vnd.android.cursor.item/vnd.fm.last.android.profile" to display a link
+     * to the Last.fm profile builder =
+     * ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
+     * builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
+     * builder.withValue(ContactsContract.Data.MIMETYPE,
+     * "vnd.android.cursor.item/vnd.owncloud.contact.profile");
+     * builder.withValue(ContactsContract.Data.DATA1, username);
+     * builder.withValue(ContactsContract.Data.DATA2, "Last.fm Profile");
+     * builder.withValue(ContactsContract.Data.DATA3, "View profile");
+     * operationList.add(builder.build());
+     * 
+     * try {
+     * getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY,
+     * operationList); } catch (Exception e) { Log.e("ASD",
+     * "Something went wrong during creation! " + e); e.printStackTrace(); } }
+     */
 
 }

+ 19 - 19
src/eu/alefzero/owncloud/ui/fragment/LandingPageFragment.java

@@ -29,30 +29,30 @@ import eu.alefzero.owncloud.ui.activity.LandingActivity;
 import eu.alefzero.owncloud.ui.adapter.LandingScreenAdapter;
 
 /**
- * Used on the Landing page to display what Components of 
- * the ownCloud there are. Like Files, Music, Contacts, etc.
+ * Used on the Landing page to display what Components of the ownCloud there
+ * are. Like Files, Music, Contacts, etc.
  * 
  * @author Lennart Rosam
- *
+ * 
  */
 public class LandingPageFragment extends SherlockFragment {
 
-	@Override
-	public View onCreateView(LayoutInflater inflater, ViewGroup container,
-			Bundle savedInstanceState) {
-		View root = inflater.inflate(R.layout.landing_page_fragment, container);
-		return root;
-	}
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+        View root = inflater.inflate(R.layout.landing_page_fragment, container);
+        return root;
+    }
+
+    @Override
+    public void onActivityCreated(Bundle savedInstanceState) {
+        super.onActivityCreated(savedInstanceState);
 
+        ListView landingScreenItems = (ListView) getView().findViewById(
+                R.id.homeScreenList);
+        landingScreenItems.setAdapter(new LandingScreenAdapter(getActivity()));
+        landingScreenItems
+                .setOnItemClickListener((LandingActivity) getActivity());
+    }
 
-	@Override
-	public void onActivityCreated(Bundle savedInstanceState) {
-		super.onActivityCreated(savedInstanceState);
-		
-		ListView landingScreenItems = (ListView) getView().findViewById(R.id.homeScreenList);
-		landingScreenItems.setAdapter(new LandingScreenAdapter(getActivity()));
-		landingScreenItems.setOnItemClickListener((LandingActivity) getActivity());
-	}
-	
-		
 }

+ 59 - 56
src/eu/alefzero/owncloud/utils/OwnCloudVersion.java

@@ -19,62 +19,65 @@
 package eu.alefzero.owncloud.utils;
 
 public class OwnCloudVersion implements Comparable<OwnCloudVersion> {
-  public static final OwnCloudVersion owncloud_v1 = new OwnCloudVersion(0x010000);
-  public static final OwnCloudVersion owncloud_v2 = new OwnCloudVersion(0x020000);
-  public static final OwnCloudVersion owncloud_v3 = new OwnCloudVersion(0x030000);
-  public static final OwnCloudVersion owncloud_v4 = new OwnCloudVersion(0x040000);
-  
-  // format is in version
-  // 0xAABBCC
-  // for version AA.BB.CC
-  // ie version 3.0.3 will be stored as 0x030003
-  private int mVersion;
-  private boolean mIsValid;
-  
-  public OwnCloudVersion(int version) {
-    mVersion = version;
-    mIsValid = true;
-  }
+    public static final OwnCloudVersion owncloud_v1 = new OwnCloudVersion(
+            0x010000);
+    public static final OwnCloudVersion owncloud_v2 = new OwnCloudVersion(
+            0x020000);
+    public static final OwnCloudVersion owncloud_v3 = new OwnCloudVersion(
+            0x030000);
+    public static final OwnCloudVersion owncloud_v4 = new OwnCloudVersion(
+            0x040000);
 
-  public OwnCloudVersion(String version) {
-    mVersion = 0;
-    mIsValid = false;
-    parseVersionString(version);
-  }
-  
-  public String toString() {
-    return ((mVersion >> 16)%256) + "." +
-           ((mVersion >> 8)%256) + "." +
-           ((mVersion)%256);
-  }
-  
-  public boolean isVersionValid() {
-    return mIsValid;
-  }
-  
-  @Override
-  public int compareTo(OwnCloudVersion another) {
-    return another.mVersion == mVersion ? 0 :
-           another.mVersion < mVersion ? 1 : -1;
-  }
-  
-  private void parseVersionString(String version) {
-    try {
-      String[] nums = version.split("\\.");
-      if (nums.length > 0) {
-        mVersion += Integer.parseInt(nums[0]);
-      }
-      mVersion = mVersion << 8;
-      if (nums.length > 1) {
-        mVersion += Integer.parseInt(nums[1]);
-      }
-      mVersion = mVersion << 8;
-      if (nums.length > 2) {
-        mVersion += Integer.parseInt(nums[2]);
-      }
-      mIsValid = true;
-    } catch (Exception e) {
-      mIsValid = false;
+    // format is in version
+    // 0xAABBCC
+    // for version AA.BB.CC
+    // ie version 3.0.3 will be stored as 0x030003
+    private int mVersion;
+    private boolean mIsValid;
+
+    public OwnCloudVersion(int version) {
+        mVersion = version;
+        mIsValid = true;
+    }
+
+    public OwnCloudVersion(String version) {
+        mVersion = 0;
+        mIsValid = false;
+        parseVersionString(version);
+    }
+
+    public String toString() {
+        return ((mVersion >> 16) % 256) + "." + ((mVersion >> 8) % 256) + "."
+                + ((mVersion) % 256);
+    }
+
+    public boolean isVersionValid() {
+        return mIsValid;
+    }
+
+    @Override
+    public int compareTo(OwnCloudVersion another) {
+        return another.mVersion == mVersion ? 0
+                : another.mVersion < mVersion ? 1 : -1;
+    }
+
+    private void parseVersionString(String version) {
+        try {
+            String[] nums = version.split("\\.");
+            if (nums.length > 0) {
+                mVersion += Integer.parseInt(nums[0]);
+            }
+            mVersion = mVersion << 8;
+            if (nums.length > 1) {
+                mVersion += Integer.parseInt(nums[1]);
+            }
+            mVersion = mVersion << 8;
+            if (nums.length > 2) {
+                mVersion += Integer.parseInt(nums[2]);
+            }
+            mIsValid = true;
+        } catch (Exception e) {
+            mIsValid = false;
+        }
     }
-  }
 }

+ 107 - 97
src/eu/alefzero/owncloud/widgets/ActionEditText.java

@@ -15,103 +15,113 @@ import android.view.MotionEvent;
 import android.widget.EditText;
 
 public class ActionEditText extends EditText {
-  private String s;
-  private String optionOneString;
-  private int optionOneColor; 
-  private String optionTwoString;
-  private int optionTwoColor;
-  private Rect mTextBounds, mButtonRect;
-  
-  private String badgeClickCallback;
-  private Rect btn_rect;
-  
-  public ActionEditText(Context context, AttributeSet attrs) {
-    super(context, attrs);
-    getAttrs(attrs);
-    s = optionOneString;
-    mTextBounds = new Rect();
-    mButtonRect = new Rect();
-  }
-  
-  public ActionEditText(Context context, AttributeSet attrs, int defStyle) {
-    super(context, attrs, defStyle);
-    getAttrs(attrs);
-    s = optionOneString;
-    mTextBounds = new Rect();
-    mButtonRect = new Rect();
-  }
-  
-  @Override
-  protected void onDraw(Canvas canvas) {
-    super.onDraw(canvas);
-    
-    Paint p = getPaint();
-    
-    p.getTextBounds(s, 0, s.length(), mTextBounds);
-    
-    getDrawingRect(mButtonRect);
-    mButtonRect.top += 10;
-    mButtonRect.bottom -= 10;
-    mButtonRect.left = (int)(getWidth() - mTextBounds.width() - 18);
-    mButtonRect.right = getWidth() - 10;
-    btn_rect = mButtonRect;
-    
-    if (s.equals(optionOneString))
-      p.setColor(optionOneColor);
-    else
-      p.setColor(optionTwoColor);
-    canvas.drawRect(mButtonRect, p);
-    p.setColor(Color.GRAY);
-    
-    canvas.drawText(s, mButtonRect.left + 3, mButtonRect.bottom - (mTextBounds.height()/2), p);
-    
-    invalidate();
-  }
-
-  @Override
-  public boolean onTouchEvent(MotionEvent event) {
-    int touchX = (int) event.getX();
-    int touchY = (int) event.getY();
-    boolean r = super.onTouchEvent(event);
-    if (event.getAction() == MotionEvent.ACTION_UP) {
-      if (btn_rect.contains(touchX, touchY)) {
-        if (s.equals(optionTwoString)) s = optionOneString;
-        else s = optionTwoString;
-        if (badgeClickCallback != null) {
-          @SuppressWarnings("rawtypes")
-          Class[] paramtypes = new Class[2];
-          paramtypes[0] = android.view.View.class;
-          paramtypes[1] = String.class;
-          Method method;
-          try {
-
-            method = getContext().getClass().getMethod(badgeClickCallback, paramtypes);
-            method.invoke(getContext(), this, s);
-
-          } catch (NoSuchMethodException e) {
-            e.printStackTrace();
-          } catch (IllegalArgumentException e) {
-            e.printStackTrace();
-          } catch (IllegalAccessException e) {
-            e.printStackTrace();
-          } catch (InvocationTargetException e) {
-            e.printStackTrace();
-          }
-          
-          invalidate();
+    private String s;
+    private String optionOneString;
+    private int optionOneColor;
+    private String optionTwoString;
+    private int optionTwoColor;
+    private Rect mTextBounds, mButtonRect;
+
+    private String badgeClickCallback;
+    private Rect btn_rect;
+
+    public ActionEditText(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        getAttrs(attrs);
+        s = optionOneString;
+        mTextBounds = new Rect();
+        mButtonRect = new Rect();
+    }
+
+    public ActionEditText(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs, defStyle);
+        getAttrs(attrs);
+        s = optionOneString;
+        mTextBounds = new Rect();
+        mButtonRect = new Rect();
+    }
+
+    @Override
+    protected void onDraw(Canvas canvas) {
+        super.onDraw(canvas);
+
+        Paint p = getPaint();
+
+        p.getTextBounds(s, 0, s.length(), mTextBounds);
+
+        getDrawingRect(mButtonRect);
+        mButtonRect.top += 10;
+        mButtonRect.bottom -= 10;
+        mButtonRect.left = (int) (getWidth() - mTextBounds.width() - 18);
+        mButtonRect.right = getWidth() - 10;
+        btn_rect = mButtonRect;
+
+        if (s.equals(optionOneString))
+            p.setColor(optionOneColor);
+        else
+            p.setColor(optionTwoColor);
+        canvas.drawRect(mButtonRect, p);
+        p.setColor(Color.GRAY);
+
+        canvas.drawText(s, mButtonRect.left + 3, mButtonRect.bottom
+                - (mTextBounds.height() / 2), p);
+
+        invalidate();
+    }
+
+    @Override
+    public boolean onTouchEvent(MotionEvent event) {
+        int touchX = (int) event.getX();
+        int touchY = (int) event.getY();
+        boolean r = super.onTouchEvent(event);
+        if (event.getAction() == MotionEvent.ACTION_UP) {
+            if (btn_rect.contains(touchX, touchY)) {
+                if (s.equals(optionTwoString))
+                    s = optionOneString;
+                else
+                    s = optionTwoString;
+                if (badgeClickCallback != null) {
+                    @SuppressWarnings("rawtypes")
+                    Class[] paramtypes = new Class[2];
+                    paramtypes[0] = android.view.View.class;
+                    paramtypes[1] = String.class;
+                    Method method;
+                    try {
+
+                        method = getContext().getClass().getMethod(
+                                badgeClickCallback, paramtypes);
+                        method.invoke(getContext(), this, s);
+
+                    } catch (NoSuchMethodException e) {
+                        e.printStackTrace();
+                    } catch (IllegalArgumentException e) {
+                        e.printStackTrace();
+                    } catch (IllegalAccessException e) {
+                        e.printStackTrace();
+                    } catch (InvocationTargetException e) {
+                        e.printStackTrace();
+                    }
+
+                    invalidate();
+                }
+            }
         }
-      }
+        return r;
     }
-    return r;
-  }
-
-  private void getAttrs(AttributeSet attr) {
-    TypedArray a = getContext().obtainStyledAttributes(attr, R.styleable.ActionEditText);
-    optionOneString = a.getString(R.styleable.ActionEditText_optionOneString);
-    optionTwoString = a.getString(R.styleable.ActionEditText_optionTwoString);
-    optionOneColor = a.getColor(R.styleable.ActionEditText_optionOneColor, 0x00ff00);
-    optionTwoColor = a.getColor(R.styleable.ActionEditText_optionTwoColor, 0xff0000);
-    badgeClickCallback = a.getString(R.styleable.ActionEditText_onBadgeClick);
-  }
-  
+
+    private void getAttrs(AttributeSet attr) {
+        TypedArray a = getContext().obtainStyledAttributes(attr,
+                R.styleable.ActionEditText);
+        optionOneString = a
+                .getString(R.styleable.ActionEditText_optionOneString);
+        optionTwoString = a
+                .getString(R.styleable.ActionEditText_optionTwoString);
+        optionOneColor = a.getColor(R.styleable.ActionEditText_optionOneColor,
+                0x00ff00);
+        optionTwoColor = a.getColor(R.styleable.ActionEditText_optionTwoColor,
+                0xff0000);
+        badgeClickCallback = a
+                .getString(R.styleable.ActionEditText_onBadgeClick);
+    }
+
 }

+ 34 - 33
src/eu/alefzero/webdav/FileRequestEntity.java

@@ -10,44 +10,45 @@ import org.apache.commons.httpclient.methods.RequestEntity;
 
 /**
  * A RequestEntity that represents a File.
- *
+ * 
  */
 public class FileRequestEntity implements RequestEntity {
 
-  final File file;
-  final String contentType;
+    final File file;
+    final String contentType;
 
-  public FileRequestEntity(final File file, final String contentType) {
-    super();
-    if (file == null) {
-      throw new IllegalArgumentException("File may not be null");
+    public FileRequestEntity(final File file, final String contentType) {
+        super();
+        if (file == null) {
+            throw new IllegalArgumentException("File may not be null");
+        }
+        this.file = file;
+        this.contentType = contentType;
     }
-    this.file = file;
-    this.contentType = contentType;
-  }
-  public long getContentLength() {
-    return this.file.length();
-  }
-
-  public String getContentType() {
-    return this.contentType;
-  }
-
-  public boolean isRepeatable() {
-    return true;
-  }
-
-  public void writeRequest(final OutputStream out) throws IOException {
-    byte[] tmp = new byte[4096];
-    int i = 0;
-    InputStream instream = new FileInputStream(this.file);
-    try {
-      while ((i = instream.read(tmp)) >= 0) {
-        out.write(tmp, 0, i);
-      }
-    } finally {
-      instream.close();
+
+    public long getContentLength() {
+        return this.file.length();
+    }
+
+    public String getContentType() {
+        return this.contentType;
+    }
+
+    public boolean isRepeatable() {
+        return true;
+    }
+
+    public void writeRequest(final OutputStream out) throws IOException {
+        byte[] tmp = new byte[4096];
+        int i = 0;
+        InputStream instream = new FileInputStream(this.file);
+        try {
+            while ((i = instream.read(tmp)) >= 0) {
+                out.write(tmp, 0, i);
+            }
+        } finally {
+            instream.close();
+        }
     }
-  }
 
 }

+ 124 - 118
src/eu/alefzero/webdav/WebdavClient.java

@@ -15,15 +15,15 @@
  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */
-package eu.alefzero.webdav;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
+package eu.alefzero.webdav;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
 import java.net.URLDecoder;
 import java.net.URLEncoder;
-
+
 import org.apache.commons.httpclient.Credentials;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.UsernamePasswordCredentials;
@@ -33,118 +33,124 @@ import org.apache.commons.httpclient.methods.HeadMethod;
 import org.apache.commons.httpclient.methods.PutMethod;
 import org.apache.commons.httpclient.methods.RequestEntity;
 import org.apache.commons.httpclient.params.HttpMethodParams;
-import org.apache.commons.httpclient.protocol.Protocol;
+import org.apache.commons.httpclient.protocol.Protocol;
 import org.apache.http.HttpStatus;
 import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
-
-import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory;
-
+
+import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory;
+
 import android.net.Uri;
-import android.util.Log;
-
-public class WebdavClient extends HttpClient {
-  private Uri mUri;
-  private Credentials mCredentials;
-  final private static String TAG = "WebdavClient";
-  private static final String USER_AGENT = "Android-ownCloud";
-  
-  public WebdavClient(Uri uri) {
-    mUri = uri;
-    getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
-  }
-  
-  public void setCredentials(String username, String password) {
-    getParams().setAuthenticationPreemptive(true);
-    getState().setCredentials(AuthScope.ANY, getCredentials(username, password));
-  }
-  
-  private Credentials getCredentials(String username, String password) {
-    if (mCredentials == null)
-      mCredentials = new UsernamePasswordCredentials(username, password); 
-    return mCredentials;
-  }
-
-  public void allowUnsignedCertificates() {
-    // https
-    Protocol.registerProtocol("https", new Protocol("https", new EasySSLSocketFactory(), 443));
-  }
-  
-  public boolean downloadFile(String filepath, File targetPath) {
-    //HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ", "%20"));
-   
-    Log.e("ASD", mUri.toString() + URLDecoder.decode(filepath) + "");
-    GetMethod get = new GetMethod(mUri.toString() + URLEncoder.encode(filepath));
-    
-//    get.setHeader("Host", mUri.getHost());
-//    get.setHeader("User-Agent", "Android-ownCloud");
-    
-    try {
-      Log.e("ASD", get.toString());
-      int status = executeMethod(get);
-      if (status != HttpStatus.SC_OK) {
-        return false;
-      }
-      BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream());
-      FileOutputStream fos = new FileOutputStream(targetPath);
-      
-      byte[] bytes = new byte[512];
-      int readResult;
-      while ((readResult = bis.read(bytes)) != -1) fos.write(bytes, 0, readResult);
-      
-    } catch (IOException e) {
-      e.printStackTrace();
-      return false;
-    }
-    return true;
-  }
-  
-  public boolean putFile(String localFile,
-                  String remoteTarget,
-                  String contentType) {
-    boolean result = true;
-
-    try {
-      Log.e("ASD", contentType+"");
-      File f = new File(localFile);
-      RequestEntity entity = new FileRequestEntity(f, contentType);
-      Log.e("ASD", f.exists()+" " + entity.getContentLength());
-      PutMethod put = new PutMethod(mUri.toString() + remoteTarget);
-      put.setRequestEntity(entity);
-      Log.d(TAG, "" + put.getURI().toString());
-      int status = executeMethod(put);
-      Log.d(TAG, "PUT method return with status "+status);
-
-      Log.i(TAG, "Uploading, done");
-    } catch (final Exception e) {
-      Log.i(TAG, ""+e.getMessage());
-      result = false;
-    }
-    
-    return result;
-  }
-  
-  public int tryToLogin() {
-    int r = 0; 
-    HeadMethod head = new HeadMethod(mUri.toString());
-    try {
-      r = executeMethod(head);
-    } catch (Exception e) {
-      Log.e(TAG, "Error: " + e.getMessage());
+import android.util.Log;
+
+public class WebdavClient extends HttpClient {
+    private Uri mUri;
+    private Credentials mCredentials;
+    final private static String TAG = "WebdavClient";
+    private static final String USER_AGENT = "Android-ownCloud";
+
+    public WebdavClient(Uri uri) {
+        mUri = uri;
+        getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
+    }
+
+    public void setCredentials(String username, String password) {
+        getParams().setAuthenticationPreemptive(true);
+        getState().setCredentials(AuthScope.ANY,
+                getCredentials(username, password));
+    }
+
+    private Credentials getCredentials(String username, String password) {
+        if (mCredentials == null)
+            mCredentials = new UsernamePasswordCredentials(username, password);
+        return mCredentials;
+    }
+
+    public void allowUnsignedCertificates() {
+        // https
+        Protocol.registerProtocol("https", new Protocol("https",
+                new EasySSLSocketFactory(), 443));
+    }
+
+    public boolean downloadFile(String filepath, File targetPath) {
+        // HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ",
+        // "%20"));
+
+        Log.e("ASD", mUri.toString() + URLDecoder.decode(filepath) + "");
+        GetMethod get = new GetMethod(mUri.toString()
+                + URLEncoder.encode(filepath));
+
+        // get.setHeader("Host", mUri.getHost());
+        // get.setHeader("User-Agent", "Android-ownCloud");
+
+        try {
+            Log.e("ASD", get.toString());
+            int status = executeMethod(get);
+            if (status != HttpStatus.SC_OK) {
+                return false;
+            }
+            BufferedInputStream bis = new BufferedInputStream(
+                    get.getResponseBodyAsStream());
+            FileOutputStream fos = new FileOutputStream(targetPath);
+
+            byte[] bytes = new byte[512];
+            int readResult;
+            while ((readResult = bis.read(bytes)) != -1)
+                fos.write(bytes, 0, readResult);
+
+        } catch (IOException e) {
+            e.printStackTrace();
+            return false;
+        }
+        return true;
+    }
+
+    public boolean putFile(String localFile, String remoteTarget,
+            String contentType) {
+        boolean result = true;
+
+        try {
+            Log.e("ASD", contentType + "");
+            File f = new File(localFile);
+            RequestEntity entity = new FileRequestEntity(f, contentType);
+            Log.e("ASD", f.exists() + " " + entity.getContentLength());
+            PutMethod put = new PutMethod(mUri.toString() + remoteTarget);
+            put.setRequestEntity(entity);
+            Log.d(TAG, "" + put.getURI().toString());
+            int status = executeMethod(put);
+            Log.d(TAG, "PUT method return with status " + status);
+
+            Log.i(TAG, "Uploading, done");
+        } catch (final Exception e) {
+            Log.i(TAG, "" + e.getMessage());
+            result = false;
+        }
+
+        return result;
+    }
+
+    public int tryToLogin() {
+        int r = 0;
+        HeadMethod head = new HeadMethod(mUri.toString());
+        try {
+            r = executeMethod(head);
+        } catch (Exception e) {
+            Log.e(TAG, "Error: " + e.getMessage());
+        }
+        return r;
+    }
+
+    public boolean createDirectory(String path) {
+        try {
+            MkColMethod mkcol = new MkColMethod(mUri.toString() + "/" + path
+                    + "/");
+            int status = executeMethod(mkcol);
+            Log.d(TAG, "Status returned " + status);
+            Log.d(TAG, "uri: " + mkcol.getURI().toString());
+            Log.i(TAG, "Creating dir completed");
+        } catch (final Exception e) {
+            e.printStackTrace();
+            return false;
+        }
+        return true;
     }
-    return r;
-  }
-
-  public boolean createDirectory(String path) {
-    try {
-      MkColMethod mkcol = new MkColMethod(mUri.toString() + "/" + path + "/");
-      int status = executeMethod(mkcol);
-      Log.d(TAG, "Status returned " + status);
-      Log.d(TAG, "uri: " + mkcol.getURI().toString());
-      Log.i(TAG, "Creating dir completed");
-    } catch (final Exception e) {
-      e.printStackTrace();
-      return false;
-    }
-    return true;
-  }
-}
+}

+ 93 - 87
src/eu/alefzero/webdav/WebdavEntry.java

@@ -27,92 +27,98 @@ import org.apache.jackrabbit.webdav.property.DavPropertySet;
 import android.util.Log;
 
 public class WebdavEntry {
-  private String mName, mPath, mUri, mContentType;
-  private long mContentLength, mCreateTimestamp, mModifiedTimestamp;
-
-  public WebdavEntry(MultiStatusResponse ms) {
-    resetData();
-    if (ms.getStatus().length != 0) {
-      mUri = ms.getHref();
-      
-      mPath = mUri.split("webdav.php", 2)[1];
-
-      int status = ms.getStatus()[0].getStatusCode();
-      DavPropertySet propSet = ms.getProperties(status);
-      @SuppressWarnings("rawtypes")
-      DavProperty prop = propSet.get(DavPropertyName.DISPLAYNAME);
-      if (prop != null) mName = (String) prop.getName().toString();
-      else {
-        String[] tmp = mPath.split("/");
-        if (tmp.length > 0)
-          mName = tmp[tmp.length-1];
-      }
-
-      prop = propSet.get(DavPropertyName.GETCONTENTTYPE);
-      if (prop != null) {
-        mContentType = (String) prop.getValue();
-      } else {
-        mContentType = "DIR";
-        /*prop = propSet.get(DavPropertyName.ISCOLLECTION);
-        if (prop != null && Boolean.parseBoolean((String) prop.getValue()))
-            mContentType = "DIR";*/
-      }
-
-      prop = propSet.get(DavPropertyName.GETCONTENTLENGTH);
-      if (prop != null)
-        mContentLength = Long.parseLong((String) prop.getValue());
-      
-      prop = propSet.get(DavPropertyName.GETLASTMODIFIED);
-      if (prop != null) {
-        Date d = WebdavUtils.parseResponseDate((String)prop.getValue());
-        mModifiedTimestamp = (d != null) ? d.getTime() : 0;
-      }
-
-      prop = propSet.get(DavPropertyName.CREATIONDATE);
-      if (prop != null) {
-        Date d = WebdavUtils.parseResponseDate((String)prop.getValue());
-        mCreateTimestamp = (d != null) ? d.getTime() : 0;
-      }  
-
-    } else {
-      Log.e("WebdavEntry", "General fuckup, no status for webdav response");
+    private String mName, mPath, mUri, mContentType;
+    private long mContentLength, mCreateTimestamp, mModifiedTimestamp;
+
+    public WebdavEntry(MultiStatusResponse ms) {
+        resetData();
+        if (ms.getStatus().length != 0) {
+            mUri = ms.getHref();
+
+            mPath = mUri.split("webdav.php", 2)[1];
+
+            int status = ms.getStatus()[0].getStatusCode();
+            DavPropertySet propSet = ms.getProperties(status);
+            @SuppressWarnings("rawtypes")
+            DavProperty prop = propSet.get(DavPropertyName.DISPLAYNAME);
+            if (prop != null)
+                mName = (String) prop.getName().toString();
+            else {
+                String[] tmp = mPath.split("/");
+                if (tmp.length > 0)
+                    mName = tmp[tmp.length - 1];
+            }
+
+            prop = propSet.get(DavPropertyName.GETCONTENTTYPE);
+            if (prop != null) {
+                mContentType = (String) prop.getValue();
+            } else {
+                mContentType = "DIR";
+                /*
+                 * prop = propSet.get(DavPropertyName.ISCOLLECTION); if (prop !=
+                 * null && Boolean.parseBoolean((String) prop.getValue()))
+                 * mContentType = "DIR";
+                 */
+            }
+
+            prop = propSet.get(DavPropertyName.GETCONTENTLENGTH);
+            if (prop != null)
+                mContentLength = Long.parseLong((String) prop.getValue());
+
+            prop = propSet.get(DavPropertyName.GETLASTMODIFIED);
+            if (prop != null) {
+                Date d = WebdavUtils
+                        .parseResponseDate((String) prop.getValue());
+                mModifiedTimestamp = (d != null) ? d.getTime() : 0;
+            }
+
+            prop = propSet.get(DavPropertyName.CREATIONDATE);
+            if (prop != null) {
+                Date d = WebdavUtils
+                        .parseResponseDate((String) prop.getValue());
+                mCreateTimestamp = (d != null) ? d.getTime() : 0;
+            }
+
+        } else {
+            Log.e("WebdavEntry",
+                    "General fuckup, no status for webdav response");
+        }
+    }
+
+    public String path() {
+        return mPath;
+    }
+
+    public String name() {
+        return mName;
+    }
+
+    public boolean isDirectory() {
+        return mContentType.equals("DIR");
+    }
+
+    public String contentType() {
+        return mContentType;
+    }
+
+    public String uri() {
+        return mUri;
+    }
+
+    public long contentLength() {
+        return mContentLength;
+    }
+
+    public long createTimestamp() {
+        return mCreateTimestamp;
+    }
+
+    public long modifiedTimesamp() {
+        return mModifiedTimestamp;
+    }
+
+    private void resetData() {
+        mName = mUri = mContentType = null;
+        mContentLength = mCreateTimestamp = mModifiedTimestamp = 0;
     }
-  }
-
-  public String path() {
-    return mPath;
-  }
-  
-  public String name() {
-    return mName;
-  }
-  
-  public boolean isDirectory() {
-    return mContentType.equals("DIR");
-  }
-
-  public String contentType() {
-    return mContentType;
-  }
-
-  public String uri() {
-    return mUri;
-  }
-  
-  public long contentLength() {
-    return mContentLength;
-  }
-  
-  public long createTimestamp() {
-    return mCreateTimestamp;
-  }
-  
-  public long modifiedTimesamp() {
-    return mModifiedTimestamp;
-  }
-  
-  private void resetData() {
-    mName = mUri = mContentType = null;
-    mContentLength = mCreateTimestamp = mModifiedTimestamp = 0;
-  }
 }

+ 30 - 28
src/eu/alefzero/webdav/WebdavUtils.java

@@ -24,33 +24,35 @@ import java.util.Date;
 import java.util.Locale;
 
 public class WebdavUtils {
-  public static final SimpleDateFormat DISPLAY_DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy hh:mm");
-  private static final SimpleDateFormat DATETIME_FORMATS[] = {
-      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US),
-      new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
-      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.US),
-      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US),
-      new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US),
-      new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
-      new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US)};
-  
-  public static String prepareXmlForPropFind() {
-    String ret = "<?xml version=\"1.0\" ?><D:propfind xmlns:D=\"DAV:\"><D:allprop/></D:propfind>";
-    return ret;
-  }
-  
-  public static String prepareXmlForPatch() {
-    return "<?xml version=\"1.0\" ?><D:propertyupdate xmlns:D=\"DAV:\"></D:propertyupdate>";
-  }
-  
-  public static Date parseResponseDate(String date) {
-    Date returnDate = null;
-    for (int i = 0; i < DATETIME_FORMATS.length; ++i) {
-      try {
-        returnDate = DATETIME_FORMATS[i].parse(date);
-        return returnDate;
-      } catch (ParseException e) {}
+    public static final SimpleDateFormat DISPLAY_DATE_FORMAT = new SimpleDateFormat(
+            "dd.MM.yyyy hh:mm");
+    private static final SimpleDateFormat DATETIME_FORMATS[] = {
+            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US),
+            new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
+            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.US),
+            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US),
+            new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US),
+            new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
+            new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) };
+
+    public static String prepareXmlForPropFind() {
+        String ret = "<?xml version=\"1.0\" ?><D:propfind xmlns:D=\"DAV:\"><D:allprop/></D:propfind>";
+        return ret;
+    }
+
+    public static String prepareXmlForPatch() {
+        return "<?xml version=\"1.0\" ?><D:propertyupdate xmlns:D=\"DAV:\"></D:propertyupdate>";
+    }
+
+    public static Date parseResponseDate(String date) {
+        Date returnDate = null;
+        for (int i = 0; i < DATETIME_FORMATS.length; ++i) {
+            try {
+                returnDate = DATETIME_FORMATS[i].parse(date);
+                return returnDate;
+            } catch (ParseException e) {
+            }
+        }
+        return null;
     }
-    return null;
-  }
 }