2 * Copyright © 2016-2020 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.annotation.SuppressLint;
23 import android.app.Dialog;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.database.Cursor;
28 import android.database.MatrixCursor;
29 import android.database.MergeCursor;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.graphics.Typeface;
33 import android.graphics.drawable.BitmapDrawable;
34 import android.graphics.drawable.Drawable;
35 import android.os.Bundle;
36 import android.preference.PreferenceManager;
37 import android.util.SparseBooleanArray;
38 import android.view.ActionMode;
39 import android.view.Menu;
40 import android.view.MenuItem;
41 import android.view.View;
42 import android.view.ViewGroup;
43 import android.view.WindowManager;
44 import android.widget.AbsListView;
45 import android.widget.AdapterView;
46 import android.widget.EditText;
47 import android.widget.ImageView;
48 import android.widget.ListView;
49 import android.widget.RadioButton;
50 import android.widget.ResourceCursorAdapter;
51 import android.widget.Spinner;
52 import android.widget.TextView;
54 import androidx.annotation.NonNull;
55 import androidx.appcompat.app.ActionBar;
56 import androidx.appcompat.app.AppCompatActivity;
57 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
58 import androidx.core.content.ContextCompat;
59 import androidx.cursoradapter.widget.CursorAdapter;
60 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
62 import com.google.android.material.snackbar.Snackbar;
64 import com.stoutner.privacybrowser.R;
65 import com.stoutner.privacybrowser.dialogs.EditBookmarkDatabaseViewDialog;
66 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDatabaseViewDialog;
67 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
69 import java.io.ByteArrayOutputStream;
70 import java.util.Arrays;
72 public class BookmarksDatabaseViewActivity extends AppCompatActivity implements EditBookmarkDatabaseViewDialog.EditBookmarkDatabaseViewListener,
73 EditBookmarkFolderDatabaseViewDialog.EditBookmarkFolderDatabaseViewListener {
74 // Instantiate the constants.
75 private static final int ALL_FOLDERS_DATABASE_ID = -2;
76 public static final int HOME_FOLDER_DATABASE_ID = -1;
78 // `bookmarksDatabaseHelper` is used in `onCreate()`, `updateBookmarksListView()`, `selectAllBookmarksInFolder()`, and `onDestroy()`.
79 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
81 // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, and `onDestroy()`.
82 private Cursor bookmarksCursor;
84 // `bookmarksCursorAdapter` is used in `onCreate()`, `selectAllBookmarksInFolder()`, and `updateBookmarksListView()`.
85 private CursorAdapter bookmarksCursorAdapter;
87 // `oldFolderNameString` is used in `onCreate()` and `onSaveBookmarkFolder()`.
88 private String oldFolderNameString;
90 // `currentFolderDatabaseId` is used in `onCreate()`, `updateBookmarksListView()`, `onSaveBookmark()`, and `onSaveBookmarkFolder()`.
91 private int currentFolderDatabaseId;
93 // `currentFolder` is used in `onCreate()`, `onSaveBookmark()`, and `onSaveBookmarkFolder()`.
94 private String currentFolderName;
96 // `sortByDisplayOrder` is used in `onCreate()`, `onOptionsItemSelected()`, and `updateBookmarksListView()`.
97 private boolean sortByDisplayOrder;
99 // `bookmarksDeletedSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
100 private Snackbar bookmarksDeletedSnackbar;
102 // `closeActivityAfterDismissingSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
103 private boolean closeActivityAfterDismissingSnackbar;
106 public void onCreate(Bundle savedInstanceState) {
107 // Get a handle for the shared preferences.
108 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
110 // Get the theme and screenshot preferences.
111 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
112 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
114 // Disable screenshots if not allowed.
115 if (!allowScreenshots) {
116 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
119 // Set the activity theme.
121 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
123 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
126 // Run the default commands.
127 super.onCreate(savedInstanceState);
129 // Get the intent that launched the activity.
130 Intent launchingIntent = getIntent();
132 // Get the favorite icon byte array.
133 byte[] favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
135 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
136 assert favoriteIconByteArray != null;
138 // Convert the favorite icon byte array to a bitmap and store it in a class variable.
139 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
141 // Set the content view.
142 setContentView(R.layout.bookmarks_databaseview_coordinatorlayout);
144 // The AndroidX toolbar must be used until the minimum API is >= 21.
145 Toolbar toolbar = findViewById(R.id.bookmarks_databaseview_toolbar);
146 setSupportActionBar(toolbar);
148 // Get a handle for the action bar.
149 ActionBar actionBar = getSupportActionBar();
151 // Remove the incorrect lint warning that the action bar might be null.
152 assert actionBar != null;
154 // Display the spinner and the back arrow in the action bar.
155 actionBar.setCustomView(R.layout.spinner);
156 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
158 // Initialize the database handler. The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHelper`.
159 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
161 // Setup a matrix cursor for "All Folders" and "Home Folder".
162 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
163 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
164 matrixCursor.addRow(new Object[]{ALL_FOLDERS_DATABASE_ID, getString(R.string.all_folders)});
165 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
167 // Get a cursor with the list of all the folders.
168 Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
170 // Combine `matrixCursor` and `foldersCursor`.
171 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
174 // Get the default folder bitmap. `ContextCompat` must be used until the minimum API >= 21.
175 Drawable defaultFolderDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_blue_bitmap);
177 // Cast the default folder drawable to a `BitmapDrawable`.
178 BitmapDrawable defaultFolderBitmapDrawable = (BitmapDrawable) defaultFolderDrawable;
180 // Remove the incorrect lint warning that `.getBitmap()` might be null.
181 assert defaultFolderBitmapDrawable != null;
183 // Convert the default folder `BitmapDrawable` to a bitmap.
184 Bitmap defaultFolderBitmap = defaultFolderBitmapDrawable.getBitmap();
187 // Create a resource cursor adapter for the spinner.
188 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(this, R.layout.appbar_spinner_item, foldersMergeCursor, 0) {
190 public void bindView(View view, Context context, Cursor cursor) {
191 // Get handles for the spinner views.
192 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
193 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
195 // Set the folder icon according to the type.
196 if (foldersMergeCursor.getPosition() > 1) { // Set a user folder icon.
197 // Initialize a default folder icon byte array output stream.
198 ByteArrayOutputStream defaultFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
200 // Covert the default folder bitmap to a PNG and store it in the output stream. `0` is for lossless compression (the only option for a PNG).
201 defaultFolderBitmap.compress(Bitmap.CompressFormat.PNG, 0, defaultFolderIconByteArrayOutputStream);
203 // Convert the default folder icon output stream to a byte array.
204 byte[] defaultFolderIconByteArray = defaultFolderIconByteArrayOutputStream.toByteArray();
207 // Get the folder icon byte array from the cursor.
208 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
210 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
211 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
214 // Set the icon according to the type.
215 if (Arrays.equals(folderIconByteArray, defaultFolderIconByteArray)) { // The default folder icon is used.
216 // Set a smaller and darker folder icon, which works well with the spinner.
217 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_dark_blue));
218 } else { // A custom folder icon is uses.
219 // Set the folder image stored in the cursor.
220 spinnerItemImageView.setImageBitmap(folderIconBitmap);
222 } else { // Set the `All Folders` or `Home Folder` icon.
223 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
224 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
227 // Set the text view to display the folder name.
228 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
232 // Set the resource cursor adapter drop drown view resource.
233 foldersCursorAdapter.setDropDownViewResource(R.layout.appbar_spinner_dropdown_item);
235 // Get a handle for the folder spinner and set the adapter.
236 Spinner folderSpinner = findViewById(R.id.spinner);
237 folderSpinner.setAdapter(foldersCursorAdapter);
239 // Handle taps on the spinner dropdown.
240 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
242 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
243 // Store the current folder database ID.
244 currentFolderDatabaseId = (int) id;
246 // Get a handle for the selected view.
247 TextView selectedFolderTextView = findViewById(R.id.spinner_item_textview);
249 // Store the current folder name.
250 currentFolderName = selectedFolderTextView.getText().toString();
252 // Update the list view.
253 updateBookmarksListView();
257 public void onNothingSelected(AdapterView<?> parent) {
262 // Get a handle for the bookmarks `ListView`.
263 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
265 // Get a `Cursor` with the current contents of the bookmarks database.
266 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
268 // Setup a `CursorAdapter` with `this` context. `false` disables autoRequery.
269 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
271 public View newView(Context context, Cursor cursor, ViewGroup parent) {
272 // Inflate the individual item layout. `false` does not attach it to the root.
273 return getLayoutInflater().inflate(R.layout.bookmarks_databaseview_item_linearlayout, parent, false);
277 public void bindView(View view, Context context, Cursor cursor) {
278 boolean isFolder = (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
280 // Get the database ID from the `Cursor` and display it in `bookmarkDatabaseIdTextView`.
281 int bookmarkDatabaseId = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper._ID));
282 TextView bookmarkDatabaseIdTextView = view.findViewById(R.id.bookmarks_databaseview_database_id);
283 bookmarkDatabaseIdTextView.setText(String.valueOf(bookmarkDatabaseId));
285 // Get the favorite icon byte array from the `Cursor`.
286 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
287 // Convert the byte array to a `Bitmap` beginning at the beginning at the first byte and ending at the last.
288 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
289 // Display the bitmap in `bookmarkFavoriteIcon`.
290 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmarks_databaseview_favorite_icon);
291 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
293 // Get the bookmark name from the `Cursor` and display it in `bookmarkNameTextView`.
294 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
295 TextView bookmarkNameTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_name);
296 bookmarkNameTextView.setText(bookmarkNameString);
298 // Make the font bold for folders.
300 // The first argument is `null` prevent changing of the font.
301 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
302 } else { // Reset the font to default.
303 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
306 // Get the bookmark URL form the `Cursor` and display it in `bookmarkUrlTextView`.
307 String bookmarkUrlString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
308 TextView bookmarkUrlTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_url);
309 bookmarkUrlTextView.setText(bookmarkUrlString);
311 // Hide the URL if the bookmark is a folder.
313 bookmarkUrlTextView.setVisibility(View.GONE);
315 bookmarkUrlTextView.setVisibility(View.VISIBLE);
318 // Get the display order from the `Cursor` and display it in `bookmarkDisplayOrderTextView`.
319 int bookmarkDisplayOrder = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
320 TextView bookmarkDisplayOrderTextView = view.findViewById(R.id.bookmarks_databaseview_display_order);
321 bookmarkDisplayOrderTextView.setText(String.valueOf(bookmarkDisplayOrder));
323 // Get the parent folder from the `Cursor` and display it in `bookmarkParentFolder`.
324 String bookmarkParentFolder = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
325 ImageView parentFolderImageView = view.findViewById(R.id.bookmarks_databaseview_parent_folder_icon);
326 TextView bookmarkParentFolderTextView = view.findViewById(R.id.bookmarks_databaseview_parent_folder);
328 // Make the folder name gray if it is the home folder.
329 if (bookmarkParentFolder.isEmpty()) {
330 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_gray));
331 bookmarkParentFolderTextView.setText(R.string.home_folder);
332 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_500));
334 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_dark_blue));
335 bookmarkParentFolderTextView.setText(bookmarkParentFolder);
337 // Set the text color according to the theme.
339 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_300));
341 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
347 // Update the ListView.
348 bookmarksListView.setAdapter(bookmarksCursorAdapter);
350 // Set the current folder database ID.
351 currentFolderDatabaseId = ALL_FOLDERS_DATABASE_ID;
353 // Set a listener to edit a bookmark when it is tapped.
354 bookmarksListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
355 // Convert the database ID to an int.
356 int databaseId = (int) id;
358 // Show the edit bookmark or edit bookmark folder dialog.
359 if (bookmarksDatabaseHelper.isFolder(databaseId)) {
360 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
361 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
363 // Show the edit bookmark folder dialog.
364 DialogFragment editBookmarkFolderDatabaseViewDialog = EditBookmarkFolderDatabaseViewDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
365 editBookmarkFolderDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
367 // Show the edit bookmark dialog.
368 DialogFragment editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
369 editBookmarkDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
373 // Handle long presses on the list view.
374 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
375 // Instantiate the common variables.
376 MenuItem selectAllMenuItem;
377 MenuItem deleteMenuItem;
378 boolean deletingBookmarks;
381 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
382 // Inflate the menu for the contextual app bar.
383 getMenuInflater().inflate(R.menu.bookmarks_databaseview_context_menu, menu);
386 mode.setTitle(R.string.bookmarks);
388 // Get handles for the menu items.
389 selectAllMenuItem = menu.findItem(R.id.select_all);
390 deleteMenuItem = menu.findItem(R.id.delete);
392 // Disable the delete menu item if a delete is pending.
393 deleteMenuItem.setEnabled(!deletingBookmarks);
400 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
406 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
407 // Calculate the number of selected bookmarks.
408 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
410 // Adjust the ActionMode according to the number of selected bookmarks.
411 mode.setSubtitle(getString(R.string.selected) + " " + numberOfSelectedBookmarks);
413 // Do not show the select all menu item if all the bookmarks are already checked.
414 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
415 selectAllMenuItem.setVisible(false);
417 selectAllMenuItem.setVisible(true);
420 // Convert the database ID to an int.
421 int databaseId = (int) id;
423 // If a folder was selected, also select all the contents.
424 if (checked && bookmarksDatabaseHelper.isFolder(databaseId)) {
425 selectAllBookmarksInFolder(databaseId);
428 // Do not allow a bookmark to be deselected if the folder is selected.
430 // Get the folder name.
431 String folderName = bookmarksDatabaseHelper.getParentFolderName((int) id);
433 // If the bookmark is not in the root folder, check to see if the folder is selected.
434 if (!folderName.isEmpty()) {
435 // Get the database ID of the folder.
436 int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderName);
438 // Move the bookmarks cursor to the first position.
439 bookmarksCursor.moveToFirst();
441 // Initialize the folder position variable.
442 int folderPosition = -1;
444 // Get the position of the folder in the bookmarks cursor.
445 while ((folderPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
446 // Check if the folder database ID matches the bookmark database ID.
447 if (folderDatabaseId == bookmarksCursor.getInt((bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID)))) {
448 // Get the folder position.
449 folderPosition = bookmarksCursor.getPosition();
451 // Check if the folder is selected.
452 if (bookmarksListView.isItemChecked(folderPosition)) {
453 // Reselect the bookmark.
454 bookmarksListView.setItemChecked(position, true);
456 // Display a snackbar explaining why the bookmark cannot be deselected.
457 Snackbar.make(bookmarksListView, R.string.cannot_deselect_bookmark, Snackbar.LENGTH_LONG).show();
461 // Increment the bookmarks cursor.
462 bookmarksCursor.moveToNext();
469 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
470 switch (item.getItemId()) {
471 case R.id.select_all:
472 // Get the total number of bookmarks.
473 int numberOfBookmarks = bookmarksListView.getCount();
476 for (int i = 0; i < numberOfBookmarks; i++) {
477 bookmarksListView.setItemChecked(i, true);
482 // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
483 deletingBookmarks = true;
485 // Get an array of the selected row IDs.
486 long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
488 // Get an array of checked bookmarks. `.clone()` makes a copy that won't change if the list view is reloaded, which is needed for re-selecting the bookmarks on undelete.
489 SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
491 // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
492 switch (currentFolderDatabaseId) {
493 // Get a cursor with all the folders.
494 case ALL_FOLDERS_DATABASE_ID:
495 if (sortByDisplayOrder) {
496 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray);
498 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksExcept(selectedBookmarksIdsLongArray);
502 // Get a cursor for the home folder.
503 case HOME_FOLDER_DATABASE_ID:
504 if (sortByDisplayOrder) {
505 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, "");
507 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, "");
511 // Display the selected folder.
513 // Get a cursor for the selected folder.
514 if (sortByDisplayOrder) {
515 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolderName);
517 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, currentFolderName);
521 // Update the list view.
522 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
524 // Create a Snackbar with the number of deleted bookmarks.
525 bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout),
526 getString(R.string.bookmarks_deleted) + " " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG)
527 .setAction(R.string.undo, view -> {
528 // Do nothing because everything will be handled by `onDismissed()` below.
530 .addCallback(new Snackbar.Callback() {
531 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
533 public void onDismissed(Snackbar snackbar, int event) {
534 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) { // The user pushed the undo button.
535 // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks.
536 updateBookmarksListView();
538 // Re-select the previously selected bookmarks.
539 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
540 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
542 } else { // The Snackbar was dismissed without the undo button being pushed.
543 // Delete each selected bookmark.
544 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
545 // Convert `databaseIdLong` to an int.
546 int databaseIdInt = (int) databaseIdLong;
548 // Delete the selected bookmark.
549 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
553 // Reset the deleting bookmarks flag.
554 deletingBookmarks = false;
556 // Enable the delete menu item.
557 deleteMenuItem.setEnabled(true);
559 // Close the activity if back has been pressed.
560 if (closeActivityAfterDismissingSnackbar) {
566 // Show the Snackbar.
567 bookmarksDeletedSnackbar.show();
571 // Consume the click.
576 public void onDestroyActionMode(ActionMode mode) {
583 public boolean onCreateOptionsMenu(Menu menu) {
585 getMenuInflater().inflate(R.menu.bookmarks_databaseview_options_menu, menu);
592 public boolean onOptionsItemSelected(MenuItem menuItem) {
593 // Get a handle for the shared preferences.
594 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
596 // Get the theme preferences.
597 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
599 // Get the ID of the menu item that was selected.
600 int menuItemId = menuItem.getItemId();
602 // Run the command that corresponds to the selected menu item.
603 switch (menuItemId) {
604 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
605 // Exit the activity.
609 case R.id.options_menu_sort:
610 // Update the sort by display order tracker.
611 sortByDisplayOrder = !sortByDisplayOrder;
613 // Get a handle for the bookmarks `ListView`.
614 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
616 // Update the icon and display a snackbar.
617 if (sortByDisplayOrder) { // Sort by display order.
618 // Update the icon according to the theme.
620 menuItem.setIcon(R.drawable.sort_selected_dark);
622 menuItem.setIcon(R.drawable.sort_selected_light);
625 // Display a Snackbar indicating the current sort type.
626 Snackbar.make(bookmarksListView, R.string.sorted_by_display_order, Snackbar.LENGTH_SHORT).show();
627 } else { // Sort by database id.
628 // Update the icon according to the theme.
630 menuItem.setIcon(R.drawable.sort_dark);
632 menuItem.setIcon(R.drawable.sort_light);
635 // Display a Snackbar indicating the current sort type.
636 Snackbar.make(bookmarksListView, R.string.sorted_by_database_id, Snackbar.LENGTH_SHORT).show();
639 // Update the list view.
640 updateBookmarksListView();
647 public void onBackPressed() {
648 // Check to see if a snackbar is currently displayed. If so, it must be closed before existing so that a pending delete is completed before reloading the list view in the bookmarks activity.
649 if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks deleted snackbar before going home.
650 // Set the close flag.
651 closeActivityAfterDismissingSnackbar = true;
653 // Dismiss the snackbar.
654 bookmarksDeletedSnackbar.dismiss();
655 } else { // Go home immediately.
656 // Update the current folder in the bookmarks activity.
657 if ((currentFolderDatabaseId == ALL_FOLDERS_DATABASE_ID) || (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID)) { // All folders or the the home folder are currently displayed.
658 // Load the home folder.
659 BookmarksActivity.currentFolder = "";
660 } else { // A subfolder is currently displayed.
661 // Load the current folder.
662 BookmarksActivity.currentFolder = currentFolderName;
665 // Reload the bookmarks list view when returning to the bookmarks activity.
666 BookmarksActivity.restartFromBookmarksDatabaseViewActivity = true;
668 // Exit the bookmarks database view activity.
669 super.onBackPressed();
673 private void updateBookmarksListView() {
674 // Populate the bookmarks list view based on the spinner selection.
675 switch (currentFolderDatabaseId) {
676 // Get a cursor with all the folders.
677 case ALL_FOLDERS_DATABASE_ID:
678 if (sortByDisplayOrder) {
679 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrder();
681 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
685 // Get a cursor for the home folder.
686 case HOME_FOLDER_DATABASE_ID:
687 if (sortByDisplayOrder) {
688 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder("");
690 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks("");
694 // Display the selected folder.
696 // Get a cursor for the selected folder.
697 if (sortByDisplayOrder) {
698 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolderName);
700 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks(currentFolderName);
704 // Update the list view.
705 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
708 private void selectAllBookmarksInFolder(int folderId) {
709 // Get a handle for the bookmarks list view.
710 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
712 // Get the folder name.
713 String folderName = bookmarksDatabaseHelper.getFolderName(folderId);
715 // Get a cursor with the contents of the folder.
716 Cursor folderCursor = bookmarksDatabaseHelper.getBookmarks(folderName);
718 // Move to the beginning of the cursor.
719 folderCursor.moveToFirst();
721 while (folderCursor.getPosition() < folderCursor.getCount()) {
722 // Get the bookmark database ID.
723 int bookmarkId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
725 // Move the bookmarks cursor to the first position.
726 bookmarksCursor.moveToFirst();
728 // Initialize the bookmark position variable.
729 int bookmarkPosition = -1;
731 // Get the position of this bookmark in the bookmarks cursor.
732 while ((bookmarkPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
733 // Check if the bookmark IDs match.
734 if (bookmarkId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID))) {
735 // Get the bookmark position.
736 bookmarkPosition = bookmarksCursor.getPosition();
738 // If this bookmark is a folder, select all the bookmarks inside it.
739 if (bookmarksDatabaseHelper.isFolder(bookmarkId)) {
740 selectAllBookmarksInFolder(bookmarkId);
743 // Select the bookmark.
744 bookmarksListView.setItemChecked(bookmarkPosition, true);
747 // Increment the bookmarks cursor position.
748 bookmarksCursor.moveToNext();
751 // Move to the next position.
752 folderCursor.moveToNext();
757 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
758 // Get the dialog from the dialog fragment.
759 Dialog dialog = dialogFragment.getDialog();
761 // Remove the incorrect lint warning below that the dialog might be null.
762 assert dialog != null;
764 // Get handles for the views from dialog fragment.
765 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
766 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
767 EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
768 Spinner folderSpinner = dialog.findViewById(R.id.edit_bookmark_folder_spinner);
769 EditText displayOrderEditText = dialog.findViewById(R.id.edit_bookmark_display_order_edittext);
771 // Extract the bookmark information.
772 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
773 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
774 int folderDatabaseId = (int) folderSpinner.getSelectedItemId();
775 int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
777 // Instantiate the parent folder name `String`.
778 String parentFolderNameString;
780 // Set the parent folder name.
781 if (folderDatabaseId == HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
782 parentFolderNameString = "";
783 } else { // Get the parent folder name from the database.
784 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(folderDatabaseId);
787 // Update the bookmark.
788 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
789 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt);
790 } else { // Update the bookmark using the `WebView` favorite icon.
791 // Create a favorite icon byte array output stream.
792 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
794 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
795 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
797 // Convert the favorite icon byte array stream to a byte array.
798 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
800 // Update the bookmark and the favorite icon.
801 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt, newFavoriteIconByteArray);
804 // Update the list view.
805 updateBookmarksListView();
809 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
810 // Get the dialog from the dialog fragment.
811 Dialog dialog = dialogFragment.getDialog();
813 // Remove the incorrect lint warning below that the dialog might be null.
814 assert dialog != null;
816 // Get handles for the views from dialog fragment.
817 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
818 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
819 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
820 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
821 Spinner parentFolderSpinner = dialog.findViewById(R.id.edit_folder_parent_folder_spinner);
822 EditText displayOrderEditText = dialog.findViewById(R.id.edit_folder_display_order_edittext);
824 // Extract the folder information.
825 String newFolderNameString = editBookmarkNameEditText.getText().toString();
826 int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId();
827 int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
829 // Instantiate the parent folder name `String`.
830 String parentFolderNameString;
832 // Set the parent folder name.
833 if (parentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
834 parentFolderNameString = "";
835 } else { // Get the parent folder name from the database.
836 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(parentFolderDatabaseId);
839 // Update the folder.
840 if (currentBookmarkIconRadioButton.isChecked()) { // Update the folder without changing the favorite icon.
841 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt);
842 } else { // Update the folder and the icon.
843 // Create the new folder icon Bitmap.
844 Bitmap folderIconBitmap;
846 // Populate the new folder icon bitmap.
847 if (defaultFolderIconRadioButton.isChecked()) {
848 // Get the default folder icon drawable.
849 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
851 // Convert the folder icon drawable to a bitmap drawable.
852 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
854 // Convert the folder icon bitmap drawable to a bitmap.
855 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
856 } else { // Use the `WebView` favorite icon.
857 // Get a copy of the favorite icon bitmap.
858 folderIconBitmap = favoriteIconBitmap;
861 // Create a folder icon byte array output stream.
862 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
864 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
865 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
867 // Convert the folder icon byte array stream to a byte array.
868 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
870 // Update the folder and the icon.
871 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt, newFolderIconByteArray);
874 // Update the list view.
875 updateBookmarksListView();
879 public void onDestroy() {
880 // Close the bookmarks cursor and database.
881 bookmarksCursor.close();
882 bookmarksDatabaseHelper.close();
884 // Run the default commands.