Search in sources :

Example 1 with NoCurrentAccountSelectedException

use of com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException in project nextcloud-notes by stefan-niedermann.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
    categoryViewModel = new ViewModelProvider(this).get(CategoryViewModel.class);
    CapabilitiesWorker.update(this);
    binding = DrawerLayoutBinding.inflate(getLayoutInflater());
    activityBinding = ActivityNotesListViewBinding.bind(binding.activityNotesListView.getRoot());
    setContentView(binding.getRoot());
    this.coordinatorLayout = binding.activityNotesListView.activityNotesListView;
    this.swipeRefreshLayout = binding.activityNotesListView.swiperefreshlayout;
    this.fabCreate = binding.activityNotesListView.fabCreate;
    this.listView = binding.activityNotesListView.recyclerView;
    gridView = isGridViewEnabled();
    if (!gridView || isDarkThemeActive(this)) {
        activityBinding.activityNotesListView.setBackgroundColor(ContextCompat.getColor(this, R.color.primary));
    }
    setupToolbars();
    setupNavigationList();
    setupNotesList();
    mainViewModel.getAccountsCount().observe(this, (count) -> {
        if (count == 0) {
            startActivityForResult(new Intent(this, ImportAccountActivity.class), ImportAccountActivity.REQUEST_CODE_IMPORT_ACCOUNT);
        } else {
            executor.submit(() -> {
                try {
                    final var account = mainViewModel.getLocalAccountByAccountName(SingleAccountHelper.getCurrentSingleSignOnAccount(getApplicationContext()).name);
                    runOnUiThread(() -> mainViewModel.postCurrentAccount(account));
                } catch (NextcloudFilesAppAccountNotFoundException e) {
                    // Verbose log output for https://github.com/stefan-niedermann/nextcloud-notes/issues/1256
                    runOnUiThread(() -> new AlertDialog.Builder(this).setTitle(NextcloudFilesAppAccountNotFoundException.class.getSimpleName()).setMessage(R.string.backup).setPositiveButton(R.string.simple_backup, (a, b) -> executor.submit(() -> {
                        final var modifiedNotes = new LinkedList<Note>();
                        for (final var account : mainViewModel.getAccounts()) {
                            modifiedNotes.addAll(mainViewModel.getLocalModifiedNotes(account.getId()));
                        }
                        if (modifiedNotes.size() == 1) {
                            final var note = modifiedNotes.get(0);
                            ShareUtil.openShareDialog(this, note.getTitle(), note.getContent());
                        } else {
                            ShareUtil.openShareDialog(this, getResources().getQuantityString(R.plurals.share_multiple, modifiedNotes.size(), modifiedNotes.size()), mainViewModel.collectNoteContents(modifiedNotes.stream().map(Note::getId).collect(Collectors.toList())));
                        }
                    })).setNegativeButton(R.string.simple_error, (a, b) -> {
                        final var ssoPreferences = AccountImporter.getSharedPreferences(getApplicationContext());
                        final var ssoPreferencesString = new StringBuilder().append("Current SSO account: ").append(ssoPreferences.getString("PREF_CURRENT_ACCOUNT_STRING", null)).append("\n").append("\n").append("SSO SharedPreferences: ").append("\n");
                        for (final var entry : ssoPreferences.getAll().entrySet()) {
                            ssoPreferencesString.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
                        }
                        ssoPreferencesString.append("\n").append("Available accounts in DB: ").append(TextUtils.join(", ", mainViewModel.getAccounts().stream().map(Account::getAccountName).collect(Collectors.toList())));
                        runOnUiThread(() -> ExceptionDialogFragment.newInstance(new RuntimeException(e.getMessage(), new RuntimeException(ssoPreferencesString.toString(), e))).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
                    }).show());
                } catch (NoCurrentAccountSelectedException e) {
                    runOnUiThread(() -> ExceptionDialogFragment.newInstance(e).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
                }
            });
        }
    });
    mainViewModel.hasMultipleAccountsConfigured().observe(this, hasMultipleAccountsConfigured -> canMoveNoteToAnotherAccounts = hasMultipleAccountsConfigured);
    mainViewModel.getSyncStatus().observe(this, syncStatus -> swipeRefreshLayout.setRefreshing(syncStatus));
    mainViewModel.getSyncErrors().observe(this, exceptions -> {
        if (mainViewModel.containsNonInfrastructureRelatedItems(exceptions)) {
            BrandedSnackbar.make(coordinatorLayout, R.string.error_synchronization, Snackbar.LENGTH_LONG).setAction(R.string.simple_more, v -> ExceptionDialogFragment.newInstance(exceptions).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName())).show();
        }
    });
    mainViewModel.getSelectedCategory().observe(this, (selectedCategory) -> {
        binding.activityNotesListView.emptyContentView.getRoot().setVisibility(GONE);
        adapter.setShowCategory(selectedCategory.getType() == RECENT || selectedCategory.getType() == FAVORITES);
        fabCreate.show();
        switch(selectedCategory.getType()) {
            case RECENT:
                {
                    activityBinding.searchText.setText(getString(R.string.search_in_all));
                    break;
                }
            case FAVORITES:
                {
                    activityBinding.searchText.setText(getString(R.string.search_in_category, getString(R.string.label_favorites)));
                    break;
                }
            case UNCATEGORIZED:
                {
                    activityBinding.searchText.setText(getString(R.string.search_in_category, getString(R.string.action_uncategorized)));
                    break;
                }
            case DEFAULT_CATEGORY:
            default:
                {
                    final String category = selectedCategory.getCategory();
                    if (category == null) {
                        throw new IllegalStateException(NavigationCategory.class.getSimpleName() + " type is " + DEFAULT_CATEGORY + ", but category is null.");
                    }
                    activityBinding.searchText.setText(getString(R.string.search_in_category, NoteUtil.extendCategory(category)));
                    break;
                }
        }
        fabCreate.setOnClickListener((View view) -> {
            final var createIntent = new Intent(getApplicationContext(), EditNoteActivity.class);
            createIntent.putExtra(EditNoteActivity.PARAM_CATEGORY, selectedCategory);
            if (activityBinding.searchView.getQuery().length() > 0) {
                createIntent.putExtra(EditNoteActivity.PARAM_CONTENT, activityBinding.searchView.getQuery().toString());
                invalidateOptionsMenu();
            }
            startActivityForResult(createIntent, REQUEST_CODE_CREATE_NOTE);
        });
    });
    mainViewModel.getNotesListLiveData().observe(this, notes -> {
        // https://stackoverflow.com/a/37342327
        itemTouchHelper.attachToRecyclerView(null);
        itemTouchHelper.attachToRecyclerView(listView);
        adapter.setItemList(notes);
        binding.activityNotesListView.progressCircular.setVisibility(GONE);
        binding.activityNotesListView.emptyContentView.getRoot().setVisibility(notes.size() > 0 ? GONE : VISIBLE);
        // Remove deleted notes from the selection
        if (tracker.hasSelection()) {
            final var deletedNotes = new LinkedList<Long>();
            for (final var id : tracker.getSelection()) {
                if (notes.stream().filter(item -> !item.isSection()).map(item -> (Note) item).noneMatch(item -> item.getId() == id)) {
                    deletedNotes.add(id);
                }
            }
            for (final var id : deletedNotes) {
                tracker.deselect(id);
            }
        }
    });
    mainViewModel.getSearchTerm().observe(this, adapter::setHighlightSearchQuery);
    mainViewModel.getCategorySortingMethodOfSelectedCategory().observe(this, methodOfCategory -> {
        updateSortMethodIcon(methodOfCategory.second);
        activityBinding.sortingMethod.setOnClickListener((v) -> {
            if (methodOfCategory.first != null) {
                var newMethod = methodOfCategory.second;
                if (newMethod == CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC) {
                    newMethod = CategorySortingMethod.SORT_MODIFIED_DESC;
                } else {
                    newMethod = CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC;
                }
                final var modifyLiveData = mainViewModel.modifyCategoryOrder(methodOfCategory.first, newMethod);
                modifyLiveData.observe(this, (next) -> modifyLiveData.removeObservers(this));
            }
        });
    });
    mainViewModel.getNavigationCategories().observe(this, navigationItems -> this.adapterCategories.setItems(navigationItems));
    mainViewModel.getCurrentAccount().observe(this, (nextAccount) -> {
        fabCreate.hide();
        Glide.with(this).load(nextAccount.getUrl() + "/index.php/avatar/" + Uri.encode(nextAccount.getUserName()) + "/64").placeholder(R.drawable.ic_account_circle_grey_24dp).error(R.drawable.ic_account_circle_grey_24dp).apply(RequestOptions.circleCropTransform()).into(activityBinding.launchAccountSwitcher);
        mainViewModel.synchronizeNotes(nextAccount, new IResponseCallback<>() {

            @Override
            public void onSuccess(Void v) {
                Log.d(TAG, "Successfully synchronized notes for " + nextAccount.getAccountName());
            }

            @Override
            public void onError(@NonNull Throwable t) {
                runOnUiThread(() -> {
                    if (t instanceof IntendedOfflineException) {
                        Log.i(TAG, "Capabilities and notes not updated because " + nextAccount.getAccountName() + " is offline by intention.");
                    } else if (t instanceof NetworkErrorException) {
                        BrandedSnackbar.make(coordinatorLayout, getString(R.string.error_sync, getString(R.string.error_no_network)), Snackbar.LENGTH_LONG).show();
                    } else {
                        BrandedSnackbar.make(coordinatorLayout, R.string.error_synchronization, Snackbar.LENGTH_LONG).setAction(R.string.simple_more, v -> ExceptionDialogFragment.newInstance(t).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName())).show();
                    }
                });
            }
        });
        fabCreate.show();
        activityBinding.launchAccountSwitcher.setOnClickListener((v) -> AccountSwitcherDialog.newInstance(nextAccount.getId()).show(getSupportFragmentManager(), AccountSwitcherDialog.class.getSimpleName()));
        if (menuAdapter == null) {
            menuAdapter = new MenuAdapter(getApplicationContext(), nextAccount, REQUEST_CODE_SERVER_SETTINGS, (menuItem) -> {
                @Nullable Integer resultCode = menuItem.getResultCode();
                if (resultCode == null) {
                    startActivity(menuItem.getIntent());
                } else {
                    startActivityForResult(menuItem.getIntent(), resultCode);
                }
            });
            binding.navigationMenu.setAdapter(menuAdapter);
        } else {
            menuAdapter.updateAccount(this, nextAccount);
        }
    });
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) HttpURLConnection(java.net.HttpURLConnection) ImportAccountActivity(it.niedermann.owncloud.notes.importaccount.ImportAccountActivity) NotesApplication.isDarkThemeActive(it.niedermann.owncloud.notes.NotesApplication.isDarkThemeActive) Bundle(android.os.Bundle) BrandedSnackbar(it.niedermann.owncloud.notes.branding.BrandedSnackbar) NonNull(androidx.annotation.NonNull) NoteClickListener(it.niedermann.owncloud.notes.shared.model.NoteClickListener) Uri(android.net.Uri) NotesColorUtil.contrastRatioIsSufficient(it.niedermann.owncloud.notes.shared.util.NotesColorUtil.contrastRatioIsSufficient) AccountPickerListener(it.niedermann.owncloud.notes.accountpicker.AccountPickerListener) SDK_INT(android.os.Build.VERSION.SDK_INT) ItemSelectionTracker(it.niedermann.owncloud.notes.main.items.selection.ItemSelectionTracker) GridItemDecoration(it.niedermann.owncloud.notes.main.items.grid.GridItemDecoration) UNCATEGORIZED(it.niedermann.owncloud.notes.shared.model.ENavigationCategoryType.UNCATEGORIZED) IntendedOfflineException(it.niedermann.owncloud.notes.exception.IntendedOfflineException) ApiProvider(it.niedermann.owncloud.notes.persistence.ApiProvider) ActionBarDrawerToggle(androidx.appcompat.app.ActionBarDrawerToggle) ActivityNotesListViewBinding(it.niedermann.owncloud.notes.databinding.ActivityNotesListViewBinding) FloatingActionButton(com.google.android.material.floatingactionbutton.FloatingActionButton) ItemAdapter(it.niedermann.owncloud.notes.main.items.ItemAdapter) VISIBLE(android.view.View.VISIBLE) View(android.view.View) CategoryDialogFragment(it.niedermann.owncloud.notes.edit.category.CategoryDialogFragment) RecyclerView(androidx.recyclerview.widget.RecyclerView) ContextCompat(androidx.core.content.ContextCompat) TokenMismatchException(com.nextcloud.android.sso.exceptions.TokenMismatchException) Log(android.util.Log) AccountSwitcherDialog(it.niedermann.owncloud.notes.accountswitcher.AccountSwitcherDialog) NavigationAdapter(it.niedermann.owncloud.notes.main.navigation.NavigationAdapter) IResponseCallback(it.niedermann.owncloud.notes.shared.model.IResponseCallback) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) O(android.os.Build.VERSION_CODES.O) CategoryViewModel(it.niedermann.owncloud.notes.edit.category.CategoryViewModel) R(it.niedermann.owncloud.notes.R) SearchView(androidx.appcompat.widget.SearchView) PorterDuff(android.graphics.PorterDuff) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) NetworkErrorException(android.accounts.NetworkErrorException) AccountImporter(com.nextcloud.android.sso.AccountImporter) Nullable(androidx.annotation.Nullable) UnknownErrorException(com.nextcloud.android.sso.exceptions.UnknownErrorException) SingleAccountHelper(com.nextcloud.android.sso.helper.SingleAccountHelper) GONE(android.view.View.GONE) RECENT(it.niedermann.owncloud.notes.shared.model.ENavigationCategoryType.RECENT) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) SearchManager(android.app.SearchManager) Snackbar(com.google.android.material.snackbar.Snackbar) StaggeredGridLayoutManager(androidx.recyclerview.widget.StaggeredGridLayoutManager) Account(it.niedermann.owncloud.notes.persistence.entity.Account) Note(it.niedermann.owncloud.notes.persistence.entity.Note) AlertDialog(androidx.appcompat.app.AlertDialog) LockedActivity(it.niedermann.owncloud.notes.LockedActivity) CategorySortingMethod(it.niedermann.owncloud.notes.shared.model.CategorySortingMethod) NotesApplication.isGridViewEnabled(it.niedermann.owncloud.notes.NotesApplication.isGridViewEnabled) NavigationClickListener(it.niedermann.owncloud.notes.main.navigation.NavigationClickListener) Intent(android.content.Intent) CapabilitiesWorker(it.niedermann.owncloud.notes.persistence.CapabilitiesWorker) DEFAULT_CATEGORY(it.niedermann.owncloud.notes.shared.model.ENavigationCategoryType.DEFAULT_CATEGORY) DrawableCompat(androidx.core.graphics.drawable.DrawableCompat) NextcloudFilesAppAccountNotFoundException(com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException) BrandingUtil.getSecondaryForegroundColorDependingOnTheme(it.niedermann.owncloud.notes.branding.BrandingUtil.getSecondaryForegroundColorDependingOnTheme) NavigationCategory(it.niedermann.owncloud.notes.shared.model.NavigationCategory) CustomAppGlideModule(it.niedermann.owncloud.notes.shared.util.CustomAppGlideModule) NoteUtil(it.niedermann.owncloud.notes.shared.util.NoteUtil) MenuAdapter(it.niedermann.owncloud.notes.main.menu.MenuAdapter) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) RequestOptions(com.bumptech.glide.request.RequestOptions) ViewModelProvider(androidx.lifecycle.ViewModelProvider) ActivityCompat(androidx.core.app.ActivityCompat) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) FAVORITES(it.niedermann.owncloud.notes.shared.model.ENavigationCategoryType.FAVORITES) DrawerLayoutBinding(it.niedermann.owncloud.notes.databinding.DrawerLayoutBinding) NotesListViewItemTouchHelper(it.niedermann.owncloud.notes.main.items.list.NotesListViewItemTouchHelper) GravityCompat(androidx.core.view.GravityCompat) AccountImportCancelledException(com.nextcloud.android.sso.exceptions.AccountImportCancelledException) NextcloudHttpRequestFailedException(com.nextcloud.android.sso.exceptions.NextcloudHttpRequestFailedException) CapabilitiesClient(it.niedermann.owncloud.notes.persistence.CapabilitiesClient) NavigationItem(it.niedermann.owncloud.notes.main.navigation.NavigationItem) TextUtils(android.text.TextUtils) AccountSwitcherListener(it.niedermann.owncloud.notes.accountswitcher.AccountSwitcherListener) ShareUtil(it.niedermann.owncloud.notes.shared.util.ShareUtil) ActionMode(androidx.appcompat.view.ActionMode) AnimatorInflater(android.animation.AnimatorInflater) Color(android.graphics.Color) ExceptionDialogFragment(it.niedermann.owncloud.notes.exception.ExceptionDialogFragment) SelectionTracker(androidx.recyclerview.selection.SelectionTracker) NoCurrentAccountSelectedException(com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException) Observer(androidx.lifecycle.Observer) Glide(com.bumptech.glide.Glide) EditNoteActivity(it.niedermann.owncloud.notes.edit.EditNoteActivity) SectionItemDecoration(it.niedermann.owncloud.notes.main.items.section.SectionItemDecoration) SSOUtil.askForNewAccount(it.niedermann.owncloud.notes.shared.util.SSOUtil.askForNewAccount) Account(it.niedermann.owncloud.notes.persistence.entity.Account) SSOUtil.askForNewAccount(it.niedermann.owncloud.notes.shared.util.SSOUtil.askForNewAccount) NavigationCategory(it.niedermann.owncloud.notes.shared.model.NavigationCategory) ViewModelProvider(androidx.lifecycle.ViewModelProvider) NextcloudFilesAppAccountNotFoundException(com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException) CategoryViewModel(it.niedermann.owncloud.notes.edit.category.CategoryViewModel) MenuAdapter(it.niedermann.owncloud.notes.main.menu.MenuAdapter) Intent(android.content.Intent) NoCurrentAccountSelectedException(com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) SearchView(androidx.appcompat.widget.SearchView) ImportAccountActivity(it.niedermann.owncloud.notes.importaccount.ImportAccountActivity) LinkedList(java.util.LinkedList) NetworkErrorException(android.accounts.NetworkErrorException) ExceptionDialogFragment(it.niedermann.owncloud.notes.exception.ExceptionDialogFragment) IntendedOfflineException(it.niedermann.owncloud.notes.exception.IntendedOfflineException) Note(it.niedermann.owncloud.notes.persistence.entity.Note)

Example 2 with NoCurrentAccountSelectedException

use of com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException in project nextcloud-notes by stefan-niedermann.

the class NoteListWidgetConfigurationActivity method onCreate.

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);
    repo = NotesRepository.getInstance(this);
    final var args = getIntent().getExtras();
    if (args != null) {
        appWidgetId = args.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
        Log.d(TAG, "INVALID_APPWIDGET_ID");
        finish();
    }
    viewModel = new ViewModelProvider(this).get(NoteListViewModel.class);
    binding = ActivityNoteListConfigurationBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    adapterCategories = new NavigationAdapter(this, new NavigationClickListener() {

        @Override
        public void onItemClick(NavigationItem item) {
            final var data = new NotesListWidgetData();
            data.setId(appWidgetId);
            if (item.type != null) {
                switch(item.type) {
                    case RECENT:
                        {
                            data.setMode(MODE_DISPLAY_ALL);
                            break;
                        }
                    case FAVORITES:
                        {
                            data.setMode(MODE_DISPLAY_STARRED);
                            break;
                        }
                    case UNCATEGORIZED:
                        {
                            data.setMode(MODE_DISPLAY_CATEGORY);
                            data.setCategory(null);
                        }
                    case DEFAULT_CATEGORY:
                    default:
                        {
                            if (item.getClass() == NavigationItem.CategoryNavigationItem.class) {
                                data.setMode(MODE_DISPLAY_CATEGORY);
                                data.setCategory(((NavigationItem.CategoryNavigationItem) item).category);
                            } else {
                                data.setMode(MODE_DISPLAY_ALL);
                                Log.e(TAG, "Unknown item navigation type. Fallback to show " + RECENT);
                            }
                        }
                }
            } else {
                data.setMode(MODE_DISPLAY_ALL);
                Log.e(TAG, "Unknown item navigation type. Fallback to show " + RECENT);
            }
            data.setAccountId(localAccount.getId());
            data.setThemeMode(NotesApplication.getAppTheme(getApplicationContext()).getModeId());
            executor.submit(() -> {
                repo.createOrUpdateNoteListWidgetData(data);
                final var updateIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, getApplicationContext(), NoteListWidget.class).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                setResult(RESULT_OK, updateIntent);
                getApplicationContext().sendBroadcast(updateIntent);
                finish();
            });
        }

        public void onIconClick(NavigationItem item) {
            onItemClick(item);
        }
    });
    binding.recyclerView.setAdapter(adapterCategories);
    executor.submit(() -> {
        try {
            this.localAccount = repo.getAccountByName(SingleAccountHelper.getCurrentSingleSignOnAccount(this).name);
        } catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.widget_not_logged_in, Toast.LENGTH_LONG).show();
            // TODO Present user with app login screen
            Log.w(TAG, "onCreate: user not logged in");
            finish();
        }
        runOnUiThread(() -> viewModel.getAdapterCategories(localAccount.getId()).observe(this, (navigationItems) -> adapterCategories.setItems(navigationItems)));
    });
}
Also used : NavigationAdapter(it.niedermann.owncloud.notes.main.navigation.NavigationAdapter) Bundle(android.os.Bundle) LockedActivity(it.niedermann.owncloud.notes.LockedActivity) NavigationClickListener(it.niedermann.owncloud.notes.main.navigation.NavigationClickListener) Intent(android.content.Intent) NextcloudFilesAppAccountNotFoundException(com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException) MODE_DISPLAY_STARRED(it.niedermann.owncloud.notes.persistence.entity.NotesListWidgetData.MODE_DISPLAY_STARRED) MODE_DISPLAY_CATEGORY(it.niedermann.owncloud.notes.persistence.entity.NotesListWidgetData.MODE_DISPLAY_CATEGORY) NotesApplication(it.niedermann.owncloud.notes.NotesApplication) Toast(android.widget.Toast) Log(android.util.Log) ExecutorService(java.util.concurrent.ExecutorService) NavigationAdapter(it.niedermann.owncloud.notes.main.navigation.NavigationAdapter) ViewModelProvider(androidx.lifecycle.ViewModelProvider) R(it.niedermann.owncloud.notes.R) NavigationItem(it.niedermann.owncloud.notes.main.navigation.NavigationItem) MODE_DISPLAY_ALL(it.niedermann.owncloud.notes.persistence.entity.NotesListWidgetData.MODE_DISPLAY_ALL) Executors(java.util.concurrent.Executors) AppWidgetManager(android.appwidget.AppWidgetManager) NotesRepository(it.niedermann.owncloud.notes.persistence.NotesRepository) NoCurrentAccountSelectedException(com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException) ActivityNoteListConfigurationBinding(it.niedermann.owncloud.notes.databinding.ActivityNoteListConfigurationBinding) Nullable(androidx.annotation.Nullable) SingleAccountHelper(com.nextcloud.android.sso.helper.SingleAccountHelper) RECENT(it.niedermann.owncloud.notes.shared.model.ENavigationCategoryType.RECENT) Activity(android.app.Activity) Account(it.niedermann.owncloud.notes.persistence.entity.Account) NotesListWidgetData(it.niedermann.owncloud.notes.persistence.entity.NotesListWidgetData) Intent(android.content.Intent) NoCurrentAccountSelectedException(com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException) NotesListWidgetData(it.niedermann.owncloud.notes.persistence.entity.NotesListWidgetData) NavigationItem(it.niedermann.owncloud.notes.main.navigation.NavigationItem) NavigationClickListener(it.niedermann.owncloud.notes.main.navigation.NavigationClickListener) ViewModelProvider(androidx.lifecycle.ViewModelProvider) NextcloudFilesAppAccountNotFoundException(com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException)

Example 3 with NoCurrentAccountSelectedException

use of com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException in project nextcloud-notes by stefan-niedermann.

the class BaseNoteFragment method onViewCreated.

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    executor.submit(() -> {
        try {
            final var ssoAccount = SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext().getApplicationContext());
            this.localAccount = repo.getAccountByName(ssoAccount.name);
            if (savedInstanceState == null) {
                final long id = requireArguments().getLong(PARAM_NOTE_ID);
                if (id > 0) {
                    final long accountId = requireArguments().getLong(PARAM_ACCOUNT_ID);
                    if (accountId > 0) {
                        /* Switch account if account id has been provided */
                        this.localAccount = repo.getAccountById(accountId);
                        SingleAccountHelper.setCurrentAccount(requireContext().getApplicationContext(), localAccount.getAccountName());
                    }
                    isNew = false;
                    note = originalNote = repo.getNoteById(id);
                    requireActivity().runOnUiThread(() -> onNoteLoaded(note));
                    requireActivity().invalidateOptionsMenu();
                } else {
                    final var paramNote = (Note) requireArguments().getSerializable(PARAM_NEWNOTE);
                    final var content = requireArguments().getString(PARAM_CONTENT);
                    if (paramNote == null) {
                        if (content == null) {
                            throw new IllegalArgumentException(PARAM_NOTE_ID + " is not given, argument " + PARAM_NEWNOTE + " is missing and " + PARAM_CONTENT + " is missing.");
                        } else {
                            note = new Note(-1, null, Calendar.getInstance(), NoteUtil.generateNoteTitle(content), content, getString(R.string.category_readonly), false, null, DBStatus.VOID, -1, "", 0);
                            requireActivity().runOnUiThread(() -> onNoteLoaded(note));
                            requireActivity().invalidateOptionsMenu();
                        }
                    } else {
                        paramNote.setStatus(DBStatus.LOCAL_EDITED);
                        note = repo.addNote(localAccount.getId(), paramNote);
                        originalNote = null;
                        requireActivity().runOnUiThread(() -> onNoteLoaded(note));
                        requireActivity().invalidateOptionsMenu();
                    }
                }
            } else {
                note = (Note) savedInstanceState.getSerializable(SAVEDKEY_NOTE);
                originalNote = (Note) savedInstanceState.getSerializable(SAVEDKEY_ORIGINAL_NOTE);
                requireActivity().runOnUiThread(() -> onNoteLoaded(note));
                requireActivity().invalidateOptionsMenu();
            }
        } catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
            e.printStackTrace();
        }
    });
    setHasOptionsMenu(true);
}
Also used : Note(it.niedermann.owncloud.notes.persistence.entity.Note) NoCurrentAccountSelectedException(com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException) NextcloudFilesAppAccountNotFoundException(com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException)

Aggregations

NextcloudFilesAppAccountNotFoundException (com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundException)3 NoCurrentAccountSelectedException (com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException)3 Intent (android.content.Intent)2 Bundle (android.os.Bundle)2 Log (android.util.Log)2 Nullable (androidx.annotation.Nullable)2 ViewModelProvider (androidx.lifecycle.ViewModelProvider)2 SingleAccountHelper (com.nextcloud.android.sso.helper.SingleAccountHelper)2 LockedActivity (it.niedermann.owncloud.notes.LockedActivity)2 R (it.niedermann.owncloud.notes.R)2 NavigationAdapter (it.niedermann.owncloud.notes.main.navigation.NavigationAdapter)2 NavigationClickListener (it.niedermann.owncloud.notes.main.navigation.NavigationClickListener)2 NavigationItem (it.niedermann.owncloud.notes.main.navigation.NavigationItem)2 Account (it.niedermann.owncloud.notes.persistence.entity.Account)2 RECENT (it.niedermann.owncloud.notes.shared.model.ENavigationCategoryType.RECENT)2 ExecutorService (java.util.concurrent.ExecutorService)2 Executors (java.util.concurrent.Executors)2 NetworkErrorException (android.accounts.NetworkErrorException)1 AnimatorInflater (android.animation.AnimatorInflater)1 Activity (android.app.Activity)1