Esempio n. 1
0
  /**
   * Delete {@code books} from Realm, along with any {@link RBookListItem}s which may exist for
   * them, and their cover images if they have them. Optionally delete the real files they were
   * imported from as well.
   *
   * @param realm Instance of Realm to use.
   * @param books Books to delete.
   * @param deleteRealFiles If true, also delete the books' corresponding files.
   */
  public static void deleteBooks(Realm realm, Collection<RBook> books, boolean deleteRealFiles) {
    // Null checks.
    if (books == null || books.isEmpty()) return;

    // If deleteRealFiles is true, check permissions before doing anything.
    if (deleteRealFiles
        && !Util.checkForStoragePermAndFireEventIfNeeded(R.id.action_execute_deferred)) {
      //noinspection unchecked    Defer this action while we ask for permission.
      setDeferredAction(params -> deleteBooks(realm, (Collection<RBook>) params[0], true), books);
      return;
    }

    List<String> relPaths = new ArrayList<>(books.size());
    // Delete what we created.
    realm.executeTransaction(
        tRealm -> {
          for (RBook book : books) {
            // Delete any RBookListItems which may exist for these books.
            tRealm
                .where(RBookListItem.class)
                .contains("book.relPath", book.relPath)
                .findAll()
                .deleteAllFromRealm();
            // Get the relative path of the book, in case we wish to delete the real files too.
            String relPath = book.relPath;
            relPaths.add(relPath);
            // Be sure to delete the cover file, if we have one.
            if (book.hasCoverImage) DataUtils.deleteCoverImage(relPath);
            // Delete the actual RBook from Realm.
            book.deleteFromRealm();
          }
        });

    // If the user wants us to, also try to delete the corresponding files from the device.
    if (deleteRealFiles) {
      for (String relPath : relPaths) {
        File file = Util.getFileFromRelPath(relPath);
        if (file != null) // noinspection ResultOfMethodCallIgnored
        file.delete();
      }
    }
  }