2 * Copyright © 2016-2018 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.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;
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;
63 import java.io.ByteArrayOutputStream;
65 public class BookmarksActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, EditBookmarkDialog.EditBookmarkListener,
66 EditBookmarkFolderDialog.EditBookmarkFolderListener, MoveToFolderDialog.MoveToFolderListener {
68 // `currentFolder` is public static so it can be accessed from `MoveToFolderDialog`.
69 // It is used in `onCreate`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`,
70 // and `loadFolder()`.
71 public static String currentFolder;
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;
78 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onOptionsItemSelected()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`,
79 // `onMoveToFolder()`, `deleteBookmarkFolderContents()`, `loadFolder()`, and `onDestroy()`.
80 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
82 // `bookmarksListView` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`,
83 // `updateMoveIcons()`, `scrollBookmarks()`, and `loadFolder()`.
84 private ListView bookmarksListView;
86 // `bookmarksCursor` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, `deleteBookmarkFolderContents()`,
87 // `loadFolder()`, and `onDestroy()`.
88 private Cursor bookmarksCursor;
90 // `bookmarksCursorAdapter` is used in `onCreate(), `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, `onMoveToFolder()`, and `onLoadFolder()`.
91 private CursorAdapter bookmarksCursorAdapter;
93 // `contextualActionMode` is used in `onCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()` and `onMoveToFolder()`.
94 private ActionMode contextualActionMode;
96 // `appBar` is used in `onCreate()` and `loadFolder()`.
97 private ActionBar appBar;
99 // `oldFolderName` is used in `onCreate()` and `onSaveBookmarkFolder()`.
100 private String oldFolderNameString;
102 // `moveBookmarkUpMenuItem` is used in `onCreate()` and `updateMoveIcons()`.
103 private MenuItem moveBookmarkUpMenuItem;
105 // `moveBookmarkDownMenuItem` is used in `onCreate()` and `updateMoveIcons()`.
106 private MenuItem moveBookmarkDownMenuItem;
108 // `bookmarksDeletedSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
109 private Snackbar bookmarksDeletedSnackbar;
111 // `closeActivityAfterDismissingSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
112 private boolean closeActivityAfterDismissingSnackbar;
115 protected void onCreate(Bundle savedInstanceState) {
116 // Disable screenshots if not allowed.
117 if (!MainWebViewActivity.allowScreenshots) {
118 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
121 // Set the activity theme.
122 if (MainWebViewActivity.darkTheme) {
123 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
125 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
128 // Run the default commands.
129 super.onCreate(savedInstanceState);
131 // Get the intent that launched the activity.
132 Intent launchingIntent = getIntent();
134 // Set the current folder variable.
135 if (launchingIntent.getStringExtra("Current Folder") != null) { // Set the current folder from the intent.
136 currentFolder = launchingIntent.getStringExtra("Current Folder");
137 } else { // Set the current folder to be `""`, which is the home folder.
141 // Set the content view.
142 setContentView(R.layout.bookmarks_coordinatorlayout);
144 // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
145 final Toolbar bookmarksAppBar = findViewById(R.id.bookmarks_toolbar);
146 setSupportActionBar(bookmarksAppBar);
148 // Get a handle for the activity, the app bar, and the ListView.
149 final Activity bookmarksActivity = this;
150 appBar = getSupportActionBar();
151 bookmarksListView = findViewById(R.id.bookmarks_listview);
153 // Remove the incorrect lint warning that `appBar` might be null.
154 assert appBar != null;
156 // Display the home arrow on the app bar.
157 appBar.setDisplayHomeAsUpEnabled(true);
159 // Initialize the database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
160 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
161 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
163 // Load the home folder.
166 // Set a listener so that tapping a list item loads the URL or folder.
167 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
168 // Convert the id from long to int to match the format of the bookmarks database.
169 int databaseID = (int) id;
171 // Get the bookmark cursor for this ID and move it to the first row.
172 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
173 bookmarkCursor.moveToFirst();
175 // Act upon the bookmark according to the type.
176 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
177 // Update the current folder.
178 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
180 // Load the new folder.
182 } else { // The selected bookmark is not a folder.
183 // Get the bookmark URL and assign it to `formattedUrlString`.
184 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
186 // Set `MainWebViewActivity` to load the new URL on restart.
187 MainWebViewActivity.loadUrlOnRestart = true;
189 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
190 MainWebViewActivity.currentBookmarksFolder = currentFolder;
192 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
193 MainWebViewActivity.restartFromBookmarksActivity = true;
195 // Return to `MainWebViewActivity`.
196 NavUtils.navigateUpFromSameTask(bookmarksActivity);
199 // Close the `Cursor`.
200 bookmarkCursor.close();
203 // Get a handle for the activity.
204 Activity activity = this;
206 // `MultiChoiceModeListener` handles long clicks.
207 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
208 // Instantiate the common variables.
209 MenuItem editBookmarkMenuItem;
210 MenuItem deleteBookmarksMenuItem;
211 MenuItem selectAllBookmarksMenuItem;
212 boolean deletingBookmarks;
215 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
216 // Inflate the menu for the contextual app bar and set the title.
217 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
220 if (currentFolder.isEmpty()) {
221 // Use `R.string.bookmarks` if we are in the home folder.
222 mode.setTitle(R.string.bookmarks);
223 } else { // Use the current folder name as the title.
224 mode.setTitle(currentFolder);
227 // Get a handle for `MenuItems` that need to be selectively disabled.
228 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
229 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
230 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
231 deleteBookmarksMenuItem = menu.findItem(R.id.delete_bookmark);
232 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
234 // Disable the delete bookmarks menu item if a delete is pending.
235 if (deletingBookmarks) {
236 deleteBookmarksMenuItem.setEnabled(false);
239 // Store `contextualActionMode` so it can be closed programatically.
240 contextualActionMode = mode;
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);
251 // Get a `Cursor` with all of the folders.
252 Cursor folderCursor = bookmarksDatabaseHelper.getAllFoldersCursor();
254 // Enable the move to folder menu item if at least one folder exists.
255 moveToFolderMenuItem.setVisible(folderCursor.getCount() > 0);
262 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
263 // Get a long array of the selected bookmarks.
264 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
266 // Calculate the number of selected bookmarks.
267 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
269 // Adjust the `ActionMode` and the `Menu` according to the number of selected bookmarks.
270 if (numberOfSelectedBookmarks == 0) { // No bookmarks are selected.
271 // Close the `ActionMode`.
273 } else if (numberOfSelectedBookmarks == 1) { // One bookmark is selected.
274 // List the number of selected bookmarks in the subtitle.
275 mode.setSubtitle(getString(R.string.one_selected));
277 // Show the `Move Up`, `Move Down`, and `Edit` options.
278 moveBookmarkUpMenuItem.setVisible(true);
279 moveBookmarkDownMenuItem.setVisible(true);
280 editBookmarkMenuItem.setVisible(true);
282 // Update the enabled status of the move icons.
284 } else { // More than one bookmark is selected.
285 // List the number of selected bookmarks according to the language.
286 if (getString(R.string.android_asset_path).equals("ru")) { // The Russian translation is used.
287 // Convert the number of selected bookmarks to a string.
288 String numberOfSelectedBookmarksString = String.valueOf(numberOfSelectedBookmarks);
290 // Russian follows rule #7 at <https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals>.
291 if (numberOfSelectedBookmarksString.endsWith("1") && !numberOfSelectedBookmarksString.equals("11")) { // Ends in 1.
292 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected_russian_ends_in_1));
293 } else if ((numberOfSelectedBookmarksString.endsWith("2") || numberOfSelectedBookmarksString.endsWith("3") || numberOfSelectedBookmarksString.endsWith("4")) &&
294 !numberOfSelectedBookmarksString.equals("12") && !numberOfSelectedBookmarksString.equals("13") && !numberOfSelectedBookmarksString.equals("14")) { // Ends in 2-4.
295 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected_russian_ends_in_2));
296 } else { // Everything else.
297 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected_russian_everything_else));
299 } else { // Another language is used.
300 // List the number of selected bookmarks in the subtitle.
301 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
304 // Hide non-applicable `MenuItems`.
305 moveBookmarkUpMenuItem.setVisible(false);
306 moveBookmarkDownMenuItem.setVisible(false);
307 editBookmarkMenuItem.setVisible(false);
310 // Do not show `Select All` if all the bookmarks are already checked.
311 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
312 selectAllBookmarksMenuItem.setVisible(false);
314 selectAllBookmarksMenuItem.setVisible(true);
319 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
320 // Get the menu item ID.
321 int menuItemId = item.getItemId();
323 // Instantiate the common variables.
324 int selectedBookmarkPosition;
325 int selectedBookmarkNewPosition;
326 final SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray;
328 switch (menuItemId) {
329 case R.id.move_bookmark_up:
330 // Get the array of checked bookmark positions.
331 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
333 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_up` is enabled.
334 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
336 // Calculate the new position of the selected bookmark.
337 selectedBookmarkNewPosition = selectedBookmarkPosition - 1;
339 // Iterate through the bookmarks.
340 for (int i = 0; i < bookmarksListView.getCount(); i++) {
341 // Get the database ID for the current bookmark.
342 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
344 // Update the display order for the current bookmark.
345 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
346 // Move the current bookmark up one.
347 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
348 } else if ((i + 1) == selectedBookmarkPosition){ // The current bookmark is immediately above the selected bookmark.
349 // Move the current bookmark down one.
350 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
351 } else { // The current bookmark is not changing positions.
352 // Move `bookmarksCursor` to the current bookmark position.
353 bookmarksCursor.moveToPosition(i);
355 // Update the display order only if it is not correct in the database.
356 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
357 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
362 // Update `bookmarksCursor` with the current contents of the bookmarks database.
363 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
365 // Update the `ListView`.
366 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
368 // Scroll with the bookmark.
369 scrollBookmarks(selectedBookmarkNewPosition);
371 // Update the enabled status of the move icons.
375 case R.id.move_bookmark_down:
376 // Get the array of checked bookmark positions.
377 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
379 // Store the position of the selected bookmark. Only one bookmark is selected when `move_bookmark_down` is enabled.
380 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
382 // Calculate the new position of the selected bookmark.
383 selectedBookmarkNewPosition = selectedBookmarkPosition + 1;
385 // Iterate through the bookmarks.
386 for (int i = 0; i <bookmarksListView.getCount(); i++) {
387 // Get the database ID for the current bookmark.
388 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
390 // Update the display order for the current bookmark.
391 if (i == selectedBookmarkPosition) { // The current bookmark is the selected bookmark.
392 // Move the current bookmark down one.
393 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i + 1);
394 } else if ((i - 1) == selectedBookmarkPosition) { // The current bookmark is immediately below the selected bookmark.
395 // Move the bookmark below the selected bookmark up one.
396 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i - 1);
397 } else { // The current bookmark is not changing positions.
398 // Move `bookmarksCursor` to the current bookmark position.
399 bookmarksCursor.moveToPosition(i);
401 // Update the display order only if it is not correct in the database.
402 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
403 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
408 // Update `bookmarksCursor` with the current contents of the bookmarks database.
409 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
411 // Update the `ListView`.
412 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
414 // Scroll with the bookmark.
415 scrollBookmarks(selectedBookmarkNewPosition);
417 // Update the enabled status of the move icons.
421 case R.id.move_to_folder:
422 // Store `checkedItemIds` for use by the `AlertDialog`.
423 checkedItemIds = bookmarksListView.getCheckedItemIds();
425 // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
426 AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
427 moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
430 case R.id.edit_bookmark:
431 // Get the array of checked bookmark positions.
432 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
434 // Get the position of the selected bookmark. Only one bookmark is selected when `edit_bookmark_down` is enabled.
435 selectedBookmarkPosition = selectedBookmarksPositionsSparseBooleanArray.keyAt(0);
437 // Move the `Cursor` to the selected position and find out if it is a folder.
438 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
439 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
441 // Get the selected bookmark database ID.
442 int databaseId = bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
444 // Show the edit bookmark or edit bookmark folder dialog.
446 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
447 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
449 // Show the edit bookmark folder dialog.
450 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
451 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
453 // Show the edit bookmark dialog.
454 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
455 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
459 case R.id.delete_bookmark:
460 // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
461 deletingBookmarks = true;
463 // Get an array of the selected row IDs.
464 final long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
466 // Get the array of checked bookmarks. `.clone()` makes a copy that won't change if `bookmarksListView` is reloaded, which is needed for re-selecting the bookmarks on undelete.
467 selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
469 // Update `bookmarksCursor` with the current contents of the bookmarks database except for the specified database IDs.
470 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(selectedBookmarksIdsLongArray, currentFolder);
472 // Update the `ListView`.
473 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
475 // Instantiate `snackbarMessage`.
476 String snackbarMessage;
478 // Determine how many items are in the array and prepare an appropriate snackbar message.
479 if (selectedBookmarksIdsLongArray.length == 1) {
480 snackbarMessage = getString(R.string.one_bookmark_deleted);
482 // Prepare a snackbar according to the language.
483 if (getString(R.string.android_asset_path).equals("ru")) { // The Russian translation is used.
484 // Convert the number of selected bookmarks to a string.
485 String numberOfBookmarksString = String.valueOf(selectedBookmarksIdsLongArray.length);
487 // Russian follows rule #7 at <https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals>.
488 if (numberOfBookmarksString.endsWith("1") && !numberOfBookmarksString.equals("11")) { // Ends in 1.
489 snackbarMessage = numberOfBookmarksString + " " + getString(R.string.bookmarks_deleted_russian_ends_in_1);
490 } else if ((numberOfBookmarksString.endsWith("2") || numberOfBookmarksString.endsWith("3") || numberOfBookmarksString.endsWith("4")) &&
491 !numberOfBookmarksString.equals("12") && !numberOfBookmarksString.equals("13") && !numberOfBookmarksString.equals("14")) { // Ends in 2-4.
492 snackbarMessage = numberOfBookmarksString + " " + getString(R.string.bookmarks_deleted_russian_ends_in_2);
493 } else { // Everything else.
494 snackbarMessage = numberOfBookmarksString + " " + getString(R.string.bookmarks_deleted_russian_everything_else);
496 } else { // Another language is used.
497 snackbarMessage = selectedBookmarksIdsLongArray.length + " " + getString(R.string.bookmarks_deleted);
502 bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
503 .setAction(R.string.undo, view -> {
504 // Do nothing because everything will be handled by `onDismissed()` below.
506 .addCallback(new Snackbar.Callback() {
508 public void onDismissed(Snackbar snackbar, int event) {
510 // The user pushed the `Undo` button.
511 case Snackbar.Callback.DISMISS_EVENT_ACTION:
512 // Update `bookmarksCursor` with the current contents of the bookmarks database, including the "deleted" bookmarks.
513 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
515 // Update the `ListView`.
516 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
518 // Re-select the previously selected bookmarks.
519 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
520 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
525 // The `Snackbar` was dismissed without the `Undo` button being pushed.
527 // Delete each selected bookmark.
528 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
529 // Convert `databaseIdLong` to an int.
530 int databaseIdInt = (int) databaseIdLong;
532 // Delete the contents of the folder if the selected bookmark is a folder.
533 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
534 deleteBookmarkFolderContents(databaseIdInt);
537 // Delete the selected bookmark.
538 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
541 // Update the display order.
542 for (int i = 0; i < bookmarksListView.getCount(); i++) {
543 // Get the database ID for the current bookmark.
544 int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
546 // Move `bookmarksCursor` to the current bookmark position.
547 bookmarksCursor.moveToPosition(i);
549 // Update the display order only if it is not correct in the database.
550 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
551 bookmarksDatabaseHelper.updateDisplayOrder(currentBookmarkDatabaseId, i);
556 // Enable the delete bookmarks menu item.
557 deleteBookmarksMenuItem.setEnabled(true);
559 // Reset the deleting bookmarks flag.
560 deletingBookmarks = false;
562 // Close the activity if back has been pressed.
563 if (closeActivityAfterDismissingSnackbar) {
564 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
565 MainWebViewActivity.currentBookmarksFolder = "";
567 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
568 MainWebViewActivity.restartFromBookmarksActivity = true;
570 // Return to `MainWebViewActivity`.
571 NavUtils.navigateUpFromSameTask(activity);
576 //Show the `SnackBar`.
577 bookmarksDeletedSnackbar.show();
579 // Close the `ActionBar`.
583 case R.id.context_menu_select_all_bookmarks:
584 // Get the total number of bookmarks.
585 int numberOfBookmarks = bookmarksListView.getCount();
588 for (int i = 0; i < numberOfBookmarks; i++) {
589 bookmarksListView.setItemChecked(i, true);
594 // Consume the click.
599 public void onDestroyActionMode(ActionMode mode) {
604 // Get handles for the `FloatingActionButtons`.
605 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
606 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
608 // Set the create new bookmark folder FAB to display the `AlertDialog`.
609 createBookmarkFolderFab.setOnClickListener(v -> {
610 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
611 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
612 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
615 // Set the create new bookmark FAB to display the `AlertDialog`.
616 createBookmarkFab.setOnClickListener(view -> {
617 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
618 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
619 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
624 public boolean onCreateOptionsMenu(Menu menu) {
626 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
633 public boolean onOptionsItemSelected(MenuItem menuItem) {
634 // Get the ID of the `MenuItem` that was selected.
635 int menuItemId = menuItem.getItemId();
637 switch (menuItemId) {
638 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
639 if (currentFolder.isEmpty()) { // Currently in the home folder.
641 if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks delete snackbar before going home.
642 // Set the close flag.
643 closeActivityAfterDismissingSnackbar = true;
645 // Dismiss the snackbar.
646 bookmarksDeletedSnackbar.dismiss();
647 } else { // Go home immediately.
648 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
649 MainWebViewActivity.currentBookmarksFolder = "";
651 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
652 MainWebViewActivity.restartFromBookmarksActivity = true;
654 // Return to `MainWebViewActivity`.
655 NavUtils.navigateUpFromSameTask(this);
657 } else { // Currently in a subfolder.
658 // Place the former parent folder in `currentFolder`.
659 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
661 // Load the new folder.
666 case R.id.options_menu_select_all_bookmarks:
667 // Get the total number of bookmarks.
668 int numberOfBookmarks = bookmarksListView.getCount();
671 for (int i = 0; i < numberOfBookmarks; i++) {
672 bookmarksListView.setItemChecked(i, true);
676 case R.id.bookmarks_database_view:
677 // Launch `BookmarksDatabaseViewActivity`.
678 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
679 startActivity(bookmarksDatabaseViewIntent);
686 public void onBackPressed() {
687 if (currentFolder.isEmpty()) { // Currently in the home folder.
689 if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks delete snackbar before going home.
690 // Set the close flag.
691 closeActivityAfterDismissingSnackbar = true;
693 // Dismiss the snackbar.
694 bookmarksDeletedSnackbar.dismiss();
695 } else { // Go home immediately.
696 // Update the bookmarks folder for the bookmarks drawer in `MainWebViewActivity`.
697 MainWebViewActivity.currentBookmarksFolder = "";
699 // Close the bookmarks drawer and reload the bookmarks `ListView` when returning to `MainWebViewActivity`.
700 MainWebViewActivity.restartFromBookmarksActivity = true;
702 // Exit `BookmarksActivity`.
703 super.onBackPressed();
705 } else { // Currently in a subfolder.
706 // Place the former parent folder in `currentFolder`.
707 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
709 // Load the new folder.
715 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
716 // Get the `EditTexts` from the `dialogFragment`.
717 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
718 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
720 // Extract the strings from the `EditTexts`.
721 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
722 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
724 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
725 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
726 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
727 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
729 // Display the new bookmark below the current items in the (0 indexed) list.
730 int newBookmarkDisplayOrder = bookmarksListView.getCount();
732 // Create the bookmark.
733 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
735 // Update `bookmarksCursor` with the current contents of this folder.
736 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
738 // Update the `ListView`.
739 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
741 // Scroll to the new bookmark.
742 bookmarksListView.setSelection(newBookmarkDisplayOrder);
746 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
747 // Get handles for the views in `dialogFragment`.
748 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
749 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
750 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
752 // Get new folder name string.
753 String folderNameString = createFolderNameEditText.getText().toString();
755 // Get the new folder icon `Bitmap`.
756 Bitmap folderIconBitmap;
757 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
758 // Get the default folder icon and convert it to a `Bitmap`.
759 Drawable folderIconDrawable = folderIconImageView.getDrawable();
760 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
761 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
762 } else { // Use the `WebView` favorite icon.
763 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
766 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
767 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
768 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
769 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
771 // Move all the bookmarks down one in the display order.
772 for (int i = 0; i < bookmarksListView.getCount(); i++) {
773 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
774 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
777 // Create the folder, which will be placed at the top of the `ListView`.
778 bookmarksDatabaseHelper.createFolder(folderNameString, currentFolder, folderIconByteArray);
780 // Update `bookmarksCursor` with the current contents of this folder.
781 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
783 // Update the `ListView`.
784 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
786 // Scroll to the new folder.
787 bookmarksListView.setSelection(0);
791 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
792 // Get handles for the views from `dialogFragment`.
793 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
794 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
795 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
797 // Store the bookmark strings.
798 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
799 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
801 // Update the bookmark.
802 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
803 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
804 } else { // Update the bookmark using the `WebView` favorite icon.
805 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
806 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
807 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
808 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
810 // Update the bookmark and the favorite icon.
811 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
814 // Close the contextual action mode.
815 contextualActionMode.finish();
817 // Update `bookmarksCursor` with the contents of the current folder.
818 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
820 // Update the `ListView`.
821 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
825 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
826 // Get handles for the views from `dialogFragment`.
827 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
828 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
829 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
830 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
832 // Get the new folder name.
833 String newFolderNameString = editFolderNameEditText.getText().toString();
835 // Check if the favorite icon has changed.
836 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
837 // Update the name in the database.
838 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
839 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
840 // Get the new folder icon `Bitmap`.
841 Bitmap folderIconBitmap;
842 if (defaultFolderIconRadioButton.isChecked()) {
843 // Get the default folder icon and convert it to a `Bitmap`.
844 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
845 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
846 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
847 } else { // Use the `WebView` favorite icon.
848 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
851 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
852 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
853 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
854 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
856 // Update the folder icon in the database.
857 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
858 } else { // The folder icon and the name have changed.
859 // Instantiate the new folder icon `Bitmap`.
860 Bitmap folderIconBitmap;
862 // Populate the new folder icon bitmap.
863 if (defaultFolderIconRadioButton.isChecked()) {
864 // Get the default folder icon and convert it to a `Bitmap`.
865 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
866 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
867 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
868 } else { // Use the `WebView` favorite icon.
869 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
872 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
873 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
874 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
875 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
877 // Update the folder name and icon in the database.
878 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
881 // Update `bookmarksCursor` with the current contents of this folder.
882 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
884 // Update the `ListView`.
885 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
887 // Close the contextual action mode.
888 contextualActionMode.finish();
892 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
893 // Get a handle for the `ListView` from `dialogFragment`.
894 ListView folderListView = dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
896 // Store a long array of the selected folders.
897 long[] newFolderLongArray = folderListView.getCheckedItemIds();
899 // Get the new folder database ID. Only one folder will be selected.
900 int newFolderDatabaseId = (int) newFolderLongArray[0];
902 // Instantiate `newFolderName`.
903 String newFolderName;
905 // Set the new folder name.
906 if (newFolderDatabaseId == 0) {
907 // The new folder is the home folder, represented as `""` in the database.
910 // Get the new folder name from the database.
911 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
914 // Get a long array with the the database ID of the selected bookmarks.
915 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
917 // Move each of the selected bookmarks to the new folder.
918 for (long databaseIdLong : selectedBookmarksLongArray) {
919 // Get `databaseIdInt` for each selected bookmark.
920 int databaseIdInt = (int) databaseIdLong;
922 // Move the selected bookmark to the new folder.
923 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
926 // Update `bookmarksCursor` with the current contents of this folder.
927 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
929 // Update the `ListView`.
930 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
932 // Close the contextual app bar.
933 contextualActionMode.finish();
936 private void deleteBookmarkFolderContents(int databaseId) {
937 // Get the name of the folder.
938 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
940 // Get the contents of the folder.
941 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
943 // Delete each of the bookmarks in the folder.
944 for (int i = 0; i < folderCursor.getCount(); i++) {
945 // Move `folderCursor` to the current row.
946 folderCursor.moveToPosition(i);
948 // Get the database ID of the item.
949 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
951 // If this is a folder, recursively delete the contents first.
952 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
953 deleteBookmarkFolderContents(itemDatabaseId);
956 // Delete the bookmark.
957 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
961 private void updateMoveIcons() {
962 // Get a long array of the selected bookmarks.
963 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
965 // Get the database IDs for the first, last, and selected bookmarks.
966 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
967 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
968 // bookmarksListView is 0 indexed.
969 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
971 // Update the move bookmark up `MenuItem`.
972 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) { // The selected bookmark is in the first position.
973 // Disable the move bookmark up `MenuItem`.
974 moveBookmarkUpMenuItem.setEnabled(false);
976 // Set the move bookmark up icon to be ghosted.
977 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
978 } else { // The selected bookmark is not in the first position.
979 // Enable the move bookmark up `MenuItem`.
980 moveBookmarkUpMenuItem.setEnabled(true);
982 // Set the icon according to the theme.
983 if (MainWebViewActivity.darkTheme) {
984 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
986 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
990 // Update the move bookmark down `MenuItem`.
991 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) { // The selected bookmark is in the last position.
992 // Disable the move bookmark down `MenuItem`.
993 moveBookmarkDownMenuItem.setEnabled(false);
995 // Set the move bookmark down icon to be ghosted.
996 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
997 } else { // The selected bookmark is not in the last position.
998 // Enable the move bookmark down `MenuItem`.
999 moveBookmarkDownMenuItem.setEnabled(true);
1001 // Set the icon according to the theme.
1002 if (MainWebViewActivity.darkTheme) {
1003 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
1005 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
1010 private void scrollBookmarks(int selectedBookmarkPosition) {
1011 // Get the first and last visible bookmark positions.
1012 int firstVisibleBookmarkPosition = bookmarksListView.getFirstVisiblePosition();
1013 int lastVisibleBookmarkPosition = bookmarksListView.getLastVisiblePosition();
1015 // Calculate the number of bookmarks per screen.
1016 int numberOfBookmarksPerScreen = lastVisibleBookmarkPosition - firstVisibleBookmarkPosition;
1018 // Scroll with the moved bookmark if necessary.
1019 if (selectedBookmarkPosition <= firstVisibleBookmarkPosition) { // The selected bookmark position is at or above the top of the screen.
1020 // Scroll to the selected bookmark position.
1021 bookmarksListView.setSelection(selectedBookmarkPosition);
1022 } else if (selectedBookmarkPosition >= (lastVisibleBookmarkPosition - 1)) { // The selected bookmark is at or below the bottom of the screen. The `-1` handles partial bookmarks displayed at the bottom of the `ListView`.
1023 // Scroll to display the selected bookmark at the bottom of the screen. `+1` assured that the entire bookmark will be displayed in situations where only a partial bookmark fits at the bottom of the `ListView`.
1024 bookmarksListView.setSelection(selectedBookmarkPosition - numberOfBookmarksPerScreen + 1);
1028 private void loadFolder() {
1029 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
1030 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentFolder);
1032 // Setup a `CursorAdapter`. `this` specifies the `Context`. `false` disables `autoRequery`.
1033 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
1035 public View newView(Context context, Cursor cursor, ViewGroup parent) {
1036 // Inflate the individual item layout. `false` does not attach it to the root.
1037 return getLayoutInflater().inflate(R.layout.bookmarks_activity_item_linearlayout, parent, false);
1041 public void bindView(View view, Context context, Cursor cursor) {
1042 // Get handles for the views.
1043 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
1044 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
1046 // Get the favorite icon byte array from the `Cursor`.
1047 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
1049 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
1050 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
1052 // Display the bitmap in `bookmarkFavoriteIcon`.
1053 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
1055 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
1056 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1057 bookmarkNameTextView.setText(bookmarkNameString);
1059 // Make the font bold for folders.
1060 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
1061 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
1062 } else { // Reset the font to default for normal bookmarks.
1063 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
1068 // Populate the `ListView` with the adapter.
1069 bookmarksListView.setAdapter(bookmarksCursorAdapter);
1071 // Set the `AppBar` title.
1072 if (currentFolder.isEmpty()) {
1073 appBar.setTitle(R.string.bookmarks);
1075 appBar.setTitle(currentFolder);
1080 public void onDestroy() {
1081 // Close the bookmarks cursor and database.
1082 bookmarksCursor.close();
1083 bookmarksDatabaseHelper.close();
1085 // Run the default commands.