]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksActivity.java
Switch to the new Day/Night theme. https://redmine.stoutner.com/issues/522
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / BookmarksActivity.java
1 /*
2  * Copyright © 2016-2020 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser.activities;
21
22 import android.annotation.SuppressLint;
23 import android.app.Activity;
24 import android.app.Dialog;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.res.Configuration;
29 import android.database.Cursor;
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.CursorAdapter;
46 import android.widget.EditText;
47 import android.widget.ImageView;
48 import android.widget.ListView;
49 import android.widget.RadioButton;
50 import android.widget.TextView;
51
52 import androidx.annotation.NonNull;
53 import androidx.appcompat.app.ActionBar;
54 import androidx.appcompat.app.AppCompatActivity;
55 import androidx.appcompat.widget.Toolbar;  // The AndroidX toolbar must be used until the minimum API is >= 21.
56 import androidx.core.app.NavUtils;
57 import androidx.fragment.app.DialogFragment;
58
59 import com.google.android.material.floatingactionbutton.FloatingActionButton;
60 import com.google.android.material.snackbar.Snackbar;
61
62 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
63 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
64 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
65 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
66 import com.stoutner.privacybrowser.dialogs.MoveToFolderDialog;
67 import com.stoutner.privacybrowser.R;
68 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
69
70 import java.io.ByteArrayOutputStream;
71
72 public class BookmarksActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, EditBookmarkDialog.EditBookmarkListener,
73         EditBookmarkFolderDialog.EditBookmarkFolderListener, MoveToFolderDialog.MoveToFolderListener {
74
75     // `currentFolder` is public static so it can be accessed from `MoveToFolderDialog` and `BookmarksDatabaseViewActivity`.
76     // It is used in `onCreate`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`,
77     // and `loadFolder()`.
78     public static String currentFolder;
79
80     // `checkedItemIds` is public static so it can be accessed from `MoveToFolderDialog`.  It is also used in `onCreate()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`,
81     // and `updateMoveIcons()`.
82     public static long[] checkedItemIds;
83
84     // `restartFromBookmarksDatabaseViewActivity` is public static so it can be accessed from `BookmarksDatabaseViewActivity`.  It is also used in `onRestart()`.
85     public static boolean restartFromBookmarksDatabaseViewActivity;
86
87
88     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`,
89     // `onMoveToFolder()`, `deleteBookmarkFolderContents()`, `loadFolder()`, and `onDestroy()`.
90     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
91
92     // `bookmarksListView` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`,
93     // `updateMoveIcons()`, `scrollBookmarks()`, and `loadFolder()`.
94     private ListView bookmarksListView;
95
96     // `bookmarksCursor` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, `deleteBookmarkFolderContents()`,
97     // `loadFolder()`, and `onDestroy()`.
98     private Cursor bookmarksCursor;
99
100     // `bookmarksCursorAdapter` is used in `onCreate(), `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, and `onLoadFolder()`.
101     private CursorAdapter bookmarksCursorAdapter;
102
103     // `contextualActionMode` is used in `onCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()` and `onMoveToFolder()`.
104     private ActionMode contextualActionMode;
105
106     // `appBar` is used in `onCreate()` and `loadFolder()`.
107     private ActionBar appBar;
108
109     // `oldFolderName` is used in `onCreate()` and `onSaveBookmarkFolder()`.
110     private String oldFolderNameString;
111
112     // `moveBookmarkUpMenuItem` is used in `onCreate()` and `updateMoveIcons()`.
113     private MenuItem moveBookmarkUpMenuItem;
114
115     // `moveBookmarkDownMenuItem` is used in `onCreate()` and `updateMoveIcons()`.
116     private MenuItem moveBookmarkDownMenuItem;
117
118     // `bookmarksDeletedSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
119     private Snackbar bookmarksDeletedSnackbar;
120
121     // `closeActivityAfterDismissingSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
122     private boolean closeActivityAfterDismissingSnackbar;
123
124     // The favorite icon byte array is populated in `onCreate()` and used in `onOptionsItemSelected()`.
125     private byte[] favoriteIconByteArray;
126
127     @Override
128     protected void onCreate(Bundle savedInstanceState) {
129         // Get a handle for the shared preferences.
130         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
131
132         // Get the screenshot preference.
133         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
134
135         // Disable screenshots if not allowed.
136         if (!allowScreenshots) {
137             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
138         }
139
140         // Set the theme.
141         setTheme(R.style.PrivacyBrowser);
142
143         // Run the default commands.
144         super.onCreate(savedInstanceState);
145
146         // Get the intent that launched the activity.
147         Intent launchingIntent = getIntent();
148
149         // Store the current URL and title.
150         String currentUrl = launchingIntent.getStringExtra("current_url");
151         String currentTitle = launchingIntent.getStringExtra("current_title");
152
153         // Set the current folder variable.
154         if (launchingIntent.getStringExtra("current_folder") != null) {  // Set the current folder from the intent.
155             currentFolder = launchingIntent.getStringExtra("current_folder");
156         } else {  // Set the current folder to be `""`, which is the home folder.
157             currentFolder = "";
158         }
159
160         // Get the favorite icon byte array.
161         favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
162
163         // Remove the incorrect lint warning that the favorite icon byte array might be null.
164         assert favoriteIconByteArray != null;
165
166         // Convert the favorite icon byte array to a bitmap.
167         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
168
169         // Set the content view.
170         setContentView(R.layout.bookmarks_coordinatorlayout);
171
172         // The AndroidX toolbar must be used until the minimum API is >= 21.
173         final Toolbar toolbar = findViewById(R.id.bookmarks_toolbar);
174         setSupportActionBar(toolbar);
175
176         // Get a handle for the activity, the app bar, and the ListView.
177         final Activity bookmarksActivity = this;
178         appBar = getSupportActionBar();
179         bookmarksListView = findViewById(R.id.bookmarks_listview);
180
181         // Remove the incorrect lint warning that `appBar` might be null.
182         assert appBar != null;
183
184         // Display the home arrow on the app bar.
185         appBar.setDisplayHomeAsUpEnabled(true);
186
187         // Initialize the database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
188         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
189         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
190
191         // Load the home folder.
192         loadFolder();
193
194         // Set a listener so that tapping a list item loads the URL or folder.
195         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
196             // Convert the id from long to int to match the format of the bookmarks database.
197             int databaseID = (int) id;
198
199             // Get the bookmark cursor for this ID and move it to the first row.
200             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
201             bookmarkCursor.moveToFirst();
202
203             // Act upon the bookmark according to the type.
204             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
205                 // Update the current folder.
206                 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
207
208                 // Load the new folder.
209                 loadFolder();
210             } else {  // The selected bookmark is not a folder.
211                 // Get the bookmark URL and assign it to `formattedUrlString`.
212                 MainWebViewActivity.urlToLoadOnRestart = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
213
214                 // Set `MainWebViewActivity` to load the new URL on restart.
215                 MainWebViewActivity.loadUrlOnRestart = true;
216
217                 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
218                 MainWebViewActivity.currentBookmarksFolder = currentFolder;
219
220                 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
221                 MainWebViewActivity.restartFromBookmarksActivity = true;
222
223                 // Return to `MainWebViewActivity`.
224                 NavUtils.navigateUpFromSameTask(bookmarksActivity);
225             }
226
227             // Close the `Cursor`.
228             bookmarkCursor.close();
229         });
230
231         // Handle long presses on the list view.
232         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
233             // Instantiate the common variables.
234             MenuItem editBookmarkMenuItem;
235             MenuItem deleteBookmarksMenuItem;
236             MenuItem selectAllBookmarksMenuItem;
237             boolean deletingBookmarks;
238
239             @Override
240             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
241                 // Inflate the menu for the contextual app bar.
242                 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
243
244                 // Set the title.
245                 if (currentFolder.isEmpty()) {  // Use `R.string.bookmarks` if in the home folder.
246                     mode.setTitle(R.string.bookmarks);
247                 } else {  // Use the current folder name as the title.
248                     mode.setTitle(currentFolder);
249                 }
250
251                 // Get handles for menu items that need to be selectively disabled.
252                 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
253                 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
254                 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
255                 deleteBookmarksMenuItem = menu.findItem(R.id.delete_bookmark);
256                 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
257
258                 // Disable the delete bookmarks menu item if a delete is pending.
259                 deleteBookmarksMenuItem.setEnabled(!deletingBookmarks);
260
261                 // Store a handle for the contextual action mode so it can be closed programatically.
262                 contextualActionMode = mode;
263
264                 // Make it so.
265                 return true;
266             }
267
268             @Override
269             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
270                 // Get a handle for the move to folder menu item.
271                 MenuItem moveToFolderMenuItem = menu.findItem(R.id.move_to_folder);
272
273                 // Get a Cursor with all of the folders.
274                 Cursor folderCursor = bookmarksDatabaseHelper.getAllFolders();
275
276                 // Enable the move to folder menu item if at least one folder exists.
277                 moveToFolderMenuItem.setVisible(folderCursor.getCount() > 0);
278
279                 // Make it so.
280                 return true;
281             }
282
283             @Override
284             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
285                 // Get the number of selected bookmarks.
286                 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
287
288                 // Adjust the ActionMode and the menu according to the number of selected bookmarks.
289                 if (numberOfSelectedBookmarks == 1) {  // One bookmark is selected.
290                     // List the number of selected bookmarks in the subtitle.
291                     mode.setSubtitle(getString(R.string.selected) + "  1");
292
293                     // Show the `Move Up`, `Move Down`, and  `Edit` options.
294                     moveBookmarkUpMenuItem.setVisible(true);
295                     moveBookmarkDownMenuItem.setVisible(true);
296                     editBookmarkMenuItem.setVisible(true);
297
298                     // Update the enabled status of the move icons.
299                     updateMoveIcons();
300                 } else {  // More than one bookmark is selected.
301                     // List the number of selected bookmarks in the subtitle.
302                     mode.setSubtitle(getString(R.string.selected) + "  " + numberOfSelectedBookmarks);
303
304                     // Hide non-applicable `MenuItems`.
305                     moveBookmarkUpMenuItem.setVisible(false);
306                     moveBookmarkDownMenuItem.setVisible(false);
307                     editBookmarkMenuItem.setVisible(false);
308                 }
309
310                 // Do not show the select all menu item if all the bookmarks are already checked.
311                 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
312                     selectAllBookmarksMenuItem.setVisible(false);
313                 } else {
314                     selectAllBookmarksMenuItem.setVisible(true);
315                 }
316             }
317
318             @Override
319             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
320                 // Instantiate the common variables.
321                 int selectedBookmarkPosition;
322                 int selectedBookmarkNewPosition;
323                 final SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray;
324
325                 switch (item.getItemId()) {
326                     case R.id.move_bookmark_up:
327                         // Get the array of checked bookmark positions.
328                         selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
329
330                         // Store the position of the selected bookmark.  Only one bookmark is selected when `move_bookmark_up` is enabled.
331                         selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
332
333                         // Calculate the new position of the selected bookmark.
334                         selectedBookmarkNewPosition = selectedBookmarkPosition - 1;
335
336                         // Iterate through the bookmarks.
337                         for (int i = 0; i < bookmarksListView.getCount(); i++) {
338                             // Get the database ID for the current bookmark.
339                             int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
340
341                             // Update the display order for the current bookmark.
342                             if (i == selectedBookmarkPosition) {  // The current bookmark is the selected bookmark.
343                                 // Move the current bookmark up one.
344                                 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
345                             } else if ((i + 1) == selectedBookmarkPosition){  // The current bookmark is immediately above the selected bookmark.
346                                 // Move the current bookmark down one.
347                                 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
348                             } else {  // The current bookmark is not changing positions.
349                                 // Move `bookmarksCursor` to the current bookmark position.
350                                 bookmarksCursor.moveToPosition(i);
351
352                                 // Update the display order only if it is not correct in the database.
353                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
354                                     bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
355                                 }
356                             }
357                         }
358
359                         // Update the bookmarks cursor with the current contents of the bookmarks database.
360                         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
361
362                         // Update the `ListView`.
363                         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
364
365                         // Scroll with the bookmark.
366                         scrollBookmarks(selectedBookmarkNewPosition);
367
368                         // Update the enabled status of the move icons.
369                         updateMoveIcons();
370                         break;
371
372                     case R.id.move_bookmark_down:
373                         // Get the array of checked bookmark positions.
374                         selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
375
376                         // Store the position of the selected bookmark.  Only one bookmark is selected when `move_bookmark_down` is enabled.
377                         selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
378
379                         // Calculate the new position of the selected bookmark.
380                         selectedBookmarkNewPosition = selectedBookmarkPosition + 1;
381
382                         // Iterate through the bookmarks.
383                         for (int i = 0; i <bookmarksListView.getCount(); i++) {
384                             // Get the database ID for the current bookmark.
385                             int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
386
387                             // Update the display order for the current bookmark.
388                             if (i == selectedBookmarkPosition) {  // The current bookmark is the selected bookmark.
389                                 // Move the current bookmark down one.
390                                 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
391                             } else if ((i - 1) == selectedBookmarkPosition) {  // The current bookmark is immediately below the selected bookmark.
392                                 // Move the bookmark below the selected bookmark up one.
393                                 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
394                             } else {  // The current bookmark is not changing positions.
395                                 // Move `bookmarksCursor` to the current bookmark position.
396                                 bookmarksCursor.moveToPosition(i);
397
398                                 // Update the display order only if it is not correct in the database.
399                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
400                                     bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
401                                 }
402                             }
403                         }
404
405                         // Update the bookmarks cursor with the current contents of the bookmarks database.
406                         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
407
408                         // Update the `ListView`.
409                         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
410
411                         // Scroll with the bookmark.
412                         scrollBookmarks(selectedBookmarkNewPosition);
413
414                         // Update the enabled status of the move icons.
415                         updateMoveIcons();
416                         break;
417
418                     case R.id.move_to_folder:
419                         // Store `checkedItemIds` for use by the `AlertDialog`.
420                         checkedItemIds = bookmarksListView.getCheckedItemIds();
421
422                         // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
423                         DialogFragment moveToFolderDialog = new MoveToFolderDialog();
424                         moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
425                         break;
426
427                     case R.id.edit_bookmark:
428                         // Get the array of checked bookmark positions.
429                         selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
430
431                         // Get the position of the selected bookmark.  Only one bookmark is selected when `edit_bookmark_down` is enabled.
432                         selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
433
434                         // Move the `Cursor` to the selected position and find out if it is a folder.
435                         bookmarksCursor.moveToPosition(selectedBookmarkPosition);
436                         boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
437
438                         // Get the selected bookmark database ID.
439                         int databaseId = bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
440
441                         // Show the edit bookmark or edit bookmark folder dialog.
442                         if (isFolder) {
443                             // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
444                             oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
445
446                             // Show the edit bookmark folder dialog.
447                             DialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
448                             editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
449                         } else {
450                             // Show the edit bookmark dialog.
451                             DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
452                             editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
453                         }
454                         break;
455
456                     case R.id.delete_bookmark:
457                         // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
458                         deletingBookmarks = true;
459
460                         // Get an array of the selected row IDs.
461                         final long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
462
463                         // 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.
464                         selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
465
466                         // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
467                         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolder);
468
469                         // Update the list view.
470                         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
471
472                         // Create a Snackbar with the number of deleted bookmarks.
473                         bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.bookmarks_deleted) + "  " + selectedBookmarksIdsLongArray.length,
474                                 Snackbar.LENGTH_LONG)
475                                 .setAction(R.string.undo, view -> {
476                                     // Do nothing because everything will be handled by `onDismissed()` below.
477                                 })
478                                 .addCallback(new Snackbar.Callback() {
479                                     @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
480                                     @Override
481                                     public void onDismissed(Snackbar snackbar, int event) {
482                                         if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The user pushed the undo button.
483                                             // Update the bookmarks cursor with the current contents of the bookmarks database, including the "deleted" bookmarks.
484                                             bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
485
486                                             // Update the list view.
487                                             bookmarksCursorAdapter.changeCursor(bookmarksCursor);
488
489                                             // Re-select the previously selected bookmarks.
490                                             for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
491                                                 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
492                                             }
493                                         } else {  // The snackbar was dismissed without the undo button being pushed.
494                                             // Delete each selected bookmark.
495                                             for (long databaseIdLong : selectedBookmarksIdsLongArray) {
496                                                 // Convert `databaseIdLong` to an int.
497                                                 int databaseIdInt = (int) databaseIdLong;
498
499                                                 // Delete the contents of the folder if the selected bookmark is a folder.
500                                                 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
501                                                     deleteBookmarkFolderContents(databaseIdInt);
502                                                 }
503
504                                                 // Delete the selected bookmark.
505                                                 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
506                                             }
507
508                                             // Update the display order.
509                                             for (int i = 0; i < bookmarksListView.getCount(); i++) {
510                                                 // Get the database ID for the current bookmark.
511                                                 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
512
513                                                 // Move `bookmarksCursor` to the current bookmark position.
514                                                 bookmarksCursor.moveToPosition(i);
515
516                                                 // Update the display order only if it is not correct in the database.
517                                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
518                                                     bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
519                                                 }
520                                             }
521                                         }
522
523                                         // Reset the deleting bookmarks flag.
524                                         deletingBookmarks = false;
525
526                                         // Enable the delete bookmarks menu item.
527                                         deleteBookmarksMenuItem.setEnabled(true);
528
529                                         // Close the activity if back has been pressed.
530                                         if (closeActivityAfterDismissingSnackbar) {
531                                             onBackPressed();
532                                         }
533                                     }
534                                 });
535
536                         //Show the Snackbar.
537                         bookmarksDeletedSnackbar.show();
538                         break;
539
540                     case R.id.context_menu_select_all_bookmarks:
541                         // Get the total number of bookmarks.
542                         int numberOfBookmarks = bookmarksListView.getCount();
543
544                         // Select them all.
545                         for (int i = 0; i < numberOfBookmarks; i++) {
546                             bookmarksListView.setItemChecked(i, true);
547                         }
548                         break;
549                 }
550
551                 // Consume the click.
552                 return true;
553             }
554
555             @Override
556             public void onDestroyActionMode(ActionMode mode) {
557                 // Do nothing.
558             }
559         });
560
561         // Get handles for the `FloatingActionButtons`.
562         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
563         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
564
565         // Set the create new bookmark folder FAB to display the `AlertDialog`.
566         createBookmarkFolderFab.setOnClickListener(v -> {
567             // Create a create bookmark folder dialog.
568             DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(favoriteIconBitmap);
569
570             // Show the create bookmark folder dialog.
571             createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
572         });
573
574         // Set the create new bookmark FAB to display the `AlertDialog`.
575         createBookmarkFab.setOnClickListener(view -> {
576             // Remove the incorrect lint warning below.
577             assert currentUrl != null;
578             assert currentTitle != null;
579
580             // Instantiate the create bookmark dialog.
581             DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentUrl, currentTitle, favoriteIconBitmap);
582
583             // Display the create bookmark dialog.
584             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
585         });
586     }
587
588     @Override
589     public void onRestart() {
590         // Run the default commands.
591         super.onRestart();
592
593         // Update the list view if returning from the bookmarks database view activity.
594         if (restartFromBookmarksDatabaseViewActivity) {
595             // Load the current folder in the list view.
596             loadFolder();
597
598             // Reset `restartFromBookmarksDatabaseViewActivity`.
599             restartFromBookmarksDatabaseViewActivity = false;
600         }
601     }
602
603     @Override
604     public boolean onCreateOptionsMenu(Menu menu) {
605         // Inflate the menu.
606         getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
607
608         // Success.
609         return true;
610     }
611
612     @Override
613     public boolean onOptionsItemSelected(MenuItem menuItem) {
614         switch (menuItem.getItemId()) {
615             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
616                 if (currentFolder.isEmpty()) {  // Currently in the home folder.
617                     // Run the back commands.
618                     onBackPressed();
619                 } else {  // Currently in a subfolder.
620                     // Place the former parent folder in `currentFolder`.
621                     currentFolder = bookmarksDatabaseHelper.getParentFolderName(currentFolder);
622
623                     // Load the new folder.
624                     loadFolder();
625                 }
626                 break;
627
628             case R.id.options_menu_select_all_bookmarks:
629                 // Get the total number of bookmarks.
630                 int numberOfBookmarks = bookmarksListView.getCount();
631
632                 // Select them all.
633                 for (int i = 0; i < numberOfBookmarks; i++) {
634                     bookmarksListView.setItemChecked(i, true);
635                 }
636                 break;
637
638             case R.id.bookmarks_database_view:
639                 // Create an intent to launch the bookmarks database view activity.
640                 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
641
642                 // Include the favorite icon byte array to the intent.
643                 bookmarksDatabaseViewIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
644
645                 // Make it so.
646                 startActivity(bookmarksDatabaseViewIntent);
647                 break;
648         }
649         return true;
650     }
651
652     @Override
653     public void onBackPressed() {
654         // Check to see if a snackbar is currently displayed.  If so, it must be closed before exiting so that a pending delete is completed before reloading the list view in the bookmarks drawer.
655         if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) {  // Close the bookmarks deleted snackbar before going home.
656             // Set the close flag.
657             closeActivityAfterDismissingSnackbar = true;
658
659             // Dismiss the snackbar.
660             bookmarksDeletedSnackbar.dismiss();
661         } else {  // Go home immediately.
662             // Update the bookmarks folder for the bookmarks drawer in the main WebView activity.
663             MainWebViewActivity.currentBookmarksFolder = currentFolder;
664
665             // Close the bookmarks drawer and reload the bookmarks ListView when returning to the main WebView activity.
666             MainWebViewActivity.restartFromBookmarksActivity = true;
667
668             // Exit the bookmarks activity.
669             super.onBackPressed();
670         }
671     }
672
673     @Override
674     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
675         // Get the alert dialog from the fragment.
676         Dialog dialog = dialogFragment.getDialog();
677
678         // Remove the incorrect lint warning below that the dialog might be null.
679         assert dialog != null;
680
681         // Get the views from the dialog fragment.
682         EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
683         EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
684
685         // Extract the strings from the edit texts.
686         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
687         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
688
689         // Create a favorite icon byte array output stream.
690         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
691
692         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
693         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
694
695         // Convert the favorite icon byte array stream to a byte array.
696         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
697
698         // Display the new bookmark below the current items in the (0 indexed) list.
699         int newBookmarkDisplayOrder = bookmarksListView.getCount();
700
701         // Create the bookmark.
702         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
703
704         // Update the bookmarks cursor with the current contents of this folder.
705         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
706
707         // Update the `ListView`.
708         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
709
710         // Scroll to the new bookmark.
711         bookmarksListView.setSelection(newBookmarkDisplayOrder);
712     }
713
714     @Override
715     public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
716         // Get the dialog from the dialog fragment.
717         Dialog dialog = dialogFragment.getDialog();
718
719         // Remove the incorrect lint warning below that the dialog might be null.
720         assert dialog != null;
721
722         // Get handles for the views in the dialog fragment.
723         EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
724         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
725         ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
726
727         // Get new folder name string.
728         String folderNameString = createFolderNameEditText.getText().toString();
729
730         // Create a folder icon bitmap.
731         Bitmap folderIconBitmap;
732
733         // Set the folder icon bitmap according to the dialog.
734         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
735             // Get the default folder icon drawable.
736             Drawable folderIconDrawable = folderIconImageView.getDrawable();
737
738             // Convert the folder icon drawable to a bitmap drawable.
739             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
740
741             // Convert the folder icon bitmap drawable to a bitmap.
742             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
743         } else {  // Use the WebView favorite icon.
744             // Copy the favorite icon bitmap to the folder icon bitmap.
745             folderIconBitmap = favoriteIconBitmap;
746         }
747
748         // Create a folder icon byte array output stream.
749         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
750
751         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
752         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
753
754         // Convert the folder icon byte array stream to a byte array.
755         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
756
757         // Move all the bookmarks down one in the display order.
758         for (int i = 0; i < bookmarksListView.getCount(); i++) {
759             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
760             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
761         }
762
763         // Create the folder, which will be placed at the top of the `ListView`.
764         bookmarksDatabaseHelper.createFolder(folderNameString, currentFolder, folderIconByteArray);
765
766         // Update the bookmarks cursor with the current contents of this folder.
767         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
768
769         // Update the `ListView`.
770         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
771
772         // Scroll to the new folder.
773         bookmarksListView.setSelection(0);
774     }
775
776     @Override
777     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
778         // Get the dialog from the dialog fragment.
779         Dialog dialog = dialogFragment.getDialog();
780
781         // Remove the incorrect lint warning below that the dialog might be null.
782         assert dialog != null;
783
784         // Get handles for the views from `dialogFragment`.
785         EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
786         EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
787         RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
788
789         // Store the bookmark strings.
790         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
791         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
792
793         // Update the bookmark.
794         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
795             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
796         } else {  // Update the bookmark using the WebView favorite icon.
797             // Create a favorite icon byte array output stream.
798             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
799
800             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
801             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
802
803             // Convert the favorite icon byte array stream to a byte array.
804             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
805
806             //  Update the bookmark and the favorite icon.
807             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
808         }
809
810         // Close the contextual action mode.
811         contextualActionMode.finish();
812
813         // Update the bookmarks cursor with the contents of the current folder.
814         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
815
816         // Update the `ListView`.
817         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
818     }
819
820     @Override
821     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
822         // Get the dialog from the dialog fragment.
823         Dialog dialog = dialogFragment.getDialog();
824
825         // Remove the incorrect lint warning below that the dialog might be null.
826         assert dialog != null;
827
828         // Get handles for the views from `dialogFragment`.
829         RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
830         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
831         ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
832         EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
833
834         // Get the new folder name.
835         String newFolderNameString = editFolderNameEditText.getText().toString();
836
837         // Check if the favorite icon has changed.
838         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
839             // Update the name in the database.
840             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
841         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
842             // Create the new folder icon Bitmap.
843             Bitmap folderIconBitmap;
844
845             // Populate the new folder icon bitmap.
846             if (defaultFolderIconRadioButton.isChecked()) {
847                 // Get the default folder icon drawable.
848                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
849
850                 // Convert the folder icon drawable to a bitmap drawable.
851                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
852
853                 // Convert the folder icon bitmap drawable to a bitmap.
854                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
855             } else {  // Use the WebView favorite icon.
856                 // Copy the favorite icon bitmap to the folder icon bitmap.
857                 folderIconBitmap = favoriteIconBitmap;
858             }
859
860             // Create a folder icon byte array output stream.
861             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
862
863             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
864             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
865
866             // Convert the folder icon byte array stream to a byte array.
867             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
868
869             // Update the folder icon in the database.
870             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
871         } else {  // The folder icon and the name have changed.
872             // Instantiate the new folder icon `Bitmap`.
873             Bitmap folderIconBitmap;
874
875             // Populate the new folder icon bitmap.
876             if (defaultFolderIconRadioButton.isChecked()) {
877                 // Get the default folder icon drawable.
878                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
879
880                 // Convert the folder icon drawable to a bitmap drawable.
881                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
882
883                 // Convert the folder icon bitmap drawable to a bitmap.
884                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
885             } else {  // Use the WebView favorite icon.
886                 // Copy the favorite icon bitmap to the folder icon bitmap.
887                 folderIconBitmap = favoriteIconBitmap;
888             }
889
890             // Create a folder icon byte array output stream.
891             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
892
893             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
894             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
895
896             // Convert the folder icon byte array stream to a byte array.
897             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
898
899             // Update the folder name and icon in the database.
900             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
901         }
902
903         // Update the bookmarks cursor with the current contents of this folder.
904         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
905
906         // Update the `ListView`.
907         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
908
909         // Close the contextual action mode.
910         contextualActionMode.finish();
911     }
912
913     @Override
914     public void onMoveToFolder(DialogFragment dialogFragment) {
915         // Get the dialog from the dialog fragment.
916         Dialog dialog = dialogFragment.getDialog();
917
918         // Remove the incorrect lint warning below that the dialog might be null.
919         assert dialog != null;
920
921         // Get a handle for the list view from the dialog.
922         ListView folderListView = dialog.findViewById(R.id.move_to_folder_listview);
923
924         // Store a long array of the selected folders.
925         long[] newFolderLongArray = folderListView.getCheckedItemIds();
926
927         // Get the new folder database ID.  Only one folder will be selected.
928         int newFolderDatabaseId = (int) newFolderLongArray[0];
929
930         // Instantiate `newFolderName`.
931         String newFolderName;
932
933         // Set the new folder name.
934         if (newFolderDatabaseId == 0) {
935             // The new folder is the home folder, represented as `""` in the database.
936             newFolderName = "";
937         } else {
938             // Get the new folder name from the database.
939             newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
940         }
941
942         // Get a long array with the the database ID of the selected bookmarks.
943         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
944
945         // Move each of the selected bookmarks to the new folder.
946         for (long databaseIdLong : selectedBookmarksLongArray) {
947             // Get `databaseIdInt` for each selected bookmark.
948             int databaseIdInt = (int) databaseIdLong;
949
950             // Move the selected bookmark to the new folder.
951             bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
952         }
953
954         // Update the bookmarks cursor with the current contents of this folder.
955         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
956
957         // Update the `ListView`.
958         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
959
960         // Close the contextual app bar.
961         contextualActionMode.finish();
962     }
963
964     private void deleteBookmarkFolderContents(int databaseId) {
965         // Get the name of the folder.
966         String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
967
968         // Get the contents of the folder.
969         Cursor folderCursor = bookmarksDatabaseHelper.getBookmarkIDs(folderName);
970
971         // Delete each of the bookmarks in the folder.
972         for (int i = 0; i < folderCursor.getCount(); i++) {
973             // Move `folderCursor` to the current row.
974             folderCursor.moveToPosition(i);
975
976             // Get the database ID of the item.
977             int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
978
979             // If this is a folder, recursively delete the contents first.
980             if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
981                 deleteBookmarkFolderContents(itemDatabaseId);
982             }
983
984             // Delete the bookmark.
985             bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
986         }
987     }
988
989     private void updateMoveIcons() {
990         // Get a long array of the selected bookmarks.
991         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
992
993         // Get the database IDs for the first, last, and selected bookmarks.
994         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
995         int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
996         // bookmarksListView is 0 indexed.
997         int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
998
999         // Get the current theme status.
1000         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1001
1002         // Update the move bookmark up `MenuItem`.
1003         if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {  // The selected bookmark is in the first position.
1004             // Disable the move bookmark up `MenuItem`.
1005             moveBookmarkUpMenuItem.setEnabled(false);
1006
1007             //  Set the move bookmark up icon to be ghosted.
1008             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
1009         } else {  // The selected bookmark is not in the first position.
1010             // Enable the move bookmark up menu item.
1011             moveBookmarkUpMenuItem.setEnabled(true);
1012
1013             // Set the icon according to the theme.
1014             if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
1015                 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_night);
1016             } else {
1017                 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_day);
1018             }
1019         }
1020
1021         // Update the move bookmark down `MenuItem`.
1022         if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {  // The selected bookmark is in the last position.
1023             // Disable the move bookmark down `MenuItem`.
1024             moveBookmarkDownMenuItem.setEnabled(false);
1025
1026             // Set the move bookmark down icon to be ghosted.
1027             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
1028         } else {  // The selected bookmark is not in the last position.
1029             // Enable the move bookmark down `MenuItem`.
1030             moveBookmarkDownMenuItem.setEnabled(true);
1031
1032             // Set the icon according to the theme.
1033             if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
1034                 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_night);
1035             } else {
1036                 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_day);
1037             }
1038         }
1039     }
1040
1041     private void scrollBookmarks(int selectedBookmarkPosition) {
1042         // Get the first and last visible bookmark positions.
1043         int firstVisibleBookmarkPosition = bookmarksListView.getFirstVisiblePosition();
1044         int lastVisibleBookmarkPosition = bookmarksListView.getLastVisiblePosition();
1045
1046         // Calculate the number of bookmarks per screen.
1047         int numberOfBookmarksPerScreen = lastVisibleBookmarkPosition - firstVisibleBookmarkPosition;
1048
1049         // Scroll with the moved bookmark if necessary.
1050         if (selectedBookmarkPosition <= firstVisibleBookmarkPosition) {  // The selected bookmark position is at or above the top of the screen.
1051             // Scroll to the selected bookmark position.
1052             bookmarksListView.setSelection(selectedBookmarkPosition);
1053         } else if (selectedBookmarkPosition >= (lastVisibleBookmarkPosition - 1)) {  // The selected bookmark is at or below the bottom of the screen.
1054             // The `-1` handles partial bookmarks displayed at the bottom of the list view.  This command scrolls to display the selected bookmark at the bottom of the screen.
1055             // `+1` assures that the entire bookmark will be displayed in situations where only a partial bookmark fits at the bottom of the list view.
1056             bookmarksListView.setSelection(selectedBookmarkPosition - numberOfBookmarksPerScreen + 1);
1057         }
1058     }
1059
1060     private void loadFolder() {
1061         // Update bookmarks cursor with the contents of the bookmarks database for the current folder.
1062         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolder);
1063
1064         // Setup a `CursorAdapter`.  `this` specifies the `Context`.  `false` disables `autoRequery`.
1065         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
1066             @Override
1067             public View newView(Context context, Cursor cursor, ViewGroup parent) {
1068                 // Inflate the individual item layout.  `false` does not attach it to the root.
1069                 return getLayoutInflater().inflate(R.layout.bookmarks_activity_item_linearlayout, parent, false);
1070             }
1071
1072             @Override
1073             public void bindView(View view, Context context, Cursor cursor) {
1074                 // Get handles for the views.
1075                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
1076                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
1077
1078                 // Get the favorite icon byte array from the `Cursor`.
1079                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
1080
1081                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
1082                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
1083
1084                 // Display the bitmap in `bookmarkFavoriteIcon`.
1085                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
1086
1087                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
1088                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1089                 bookmarkNameTextView.setText(bookmarkNameString);
1090
1091                 // Make the font bold for folders.
1092                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
1093                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
1094                 } else {  // Reset the font to default for normal bookmarks.
1095                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
1096                 }
1097             }
1098         };
1099
1100         // Populate the list view with the adapter.
1101         bookmarksListView.setAdapter(bookmarksCursorAdapter);
1102
1103         // Set the `AppBar` title.
1104         if (currentFolder.isEmpty()) {
1105             appBar.setTitle(R.string.bookmarks);
1106         } else {
1107             appBar.setTitle(currentFolder);
1108         }
1109     }
1110
1111     @Override
1112     public void onDestroy() {
1113         // Close the bookmarks cursor and database.
1114         bookmarksCursor.close();
1115         bookmarksDatabaseHelper.close();
1116
1117         // Run the default commands.
1118         super.onDestroy();
1119     }
1120 }