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