]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksDatabaseViewActivity.java
7452b0bc4b53a1e6e70dd9fa6003a9a407c7e5ae
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / BookmarksDatabaseViewActivity.java
1 /*
2  * Copyright © 2016-2022 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
5  *
6  * Privacy Browser Android 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 Android 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 Android.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.activities;
21
22 import android.annotation.SuppressLint;
23 import android.app.Dialog;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.content.res.Configuration;
28 import android.database.Cursor;
29 import android.database.MatrixCursor;
30 import android.database.MergeCursor;
31 import android.graphics.Bitmap;
32 import android.graphics.BitmapFactory;
33 import android.graphics.Typeface;
34 import android.graphics.drawable.BitmapDrawable;
35 import android.graphics.drawable.Drawable;
36 import android.os.Bundle;
37 import android.preference.PreferenceManager;
38 import android.util.SparseBooleanArray;
39 import android.view.ActionMode;
40 import android.view.Menu;
41 import android.view.MenuItem;
42 import android.view.View;
43 import android.view.ViewGroup;
44 import android.view.Window;
45 import android.view.WindowManager;
46 import android.widget.AbsListView;
47 import android.widget.AdapterView;
48 import android.widget.EditText;
49 import android.widget.ImageView;
50 import android.widget.ListView;
51 import android.widget.RadioButton;
52 import android.widget.ResourceCursorAdapter;
53 import android.widget.Spinner;
54 import android.widget.TextView;
55
56 import androidx.annotation.NonNull;
57 import androidx.appcompat.app.ActionBar;
58 import androidx.appcompat.app.AppCompatActivity;
59 import androidx.appcompat.widget.Toolbar;  // The AndroidX toolbar must be used until the minimum API is >= 21.
60 import androidx.core.content.ContextCompat;
61 import androidx.cursoradapter.widget.CursorAdapter;
62 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
63
64 import com.google.android.material.snackbar.Snackbar;
65
66 import com.stoutner.privacybrowser.R;
67 import com.stoutner.privacybrowser.dialogs.EditBookmarkDatabaseViewDialog;
68 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDatabaseViewDialog;
69 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
70
71 import java.io.ByteArrayOutputStream;
72 import java.util.Arrays;
73
74 public class BookmarksDatabaseViewActivity extends AppCompatActivity implements EditBookmarkDatabaseViewDialog.EditBookmarkDatabaseViewListener,
75         EditBookmarkFolderDatabaseViewDialog.EditBookmarkFolderDatabaseViewListener {
76     // Define the class constants.
77     private static final int ALL_FOLDERS_DATABASE_ID = -2;
78     public static final int HOME_FOLDER_DATABASE_ID = -1;
79
80     // Define the saved instance state constants.
81     private final String CURRENT_FOLDER_DATABASE_ID = "current_folder_database_id";
82     private final String CURRENT_FOLDER_NAME = "current_folder_name";
83     private final String SORT_BY_DISPLAY_ORDER = "sort_by_display_order";
84
85     // Define the class variables.
86     private int currentFolderDatabaseId;
87     private String currentFolderName;
88     private boolean sortByDisplayOrder;
89     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
90     private Cursor bookmarksCursor;
91     private CursorAdapter bookmarksCursorAdapter;
92     private String oldFolderNameString;
93     private Snackbar bookmarksDeletedSnackbar;
94     private boolean closeActivityAfterDismissingSnackbar;
95
96     @Override
97     public void onCreate(Bundle savedInstanceState) {
98         // Get a handle for the shared preferences.
99         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
100
101         // Get the preferences.
102         boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
103         boolean bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
104
105         // Disable screenshots if not allowed.
106         if (!allowScreenshots) {
107             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
108         }
109
110         // Run the default commands.
111         super.onCreate(savedInstanceState);
112
113         // Get the intent that launched the activity.
114         Intent launchingIntent = getIntent();
115
116         // Get the favorite icon byte array.
117         byte[] favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
118
119         // Remove the incorrect lint warning below that the favorite icon byte array might be null.
120         assert favoriteIconByteArray != null;
121
122         // Convert the favorite icon byte array to a bitmap and store it in a class variable.
123         Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
124
125         // Set the view according to the theme.
126         if (bottomAppBar) {
127             // Set the content view.
128             setContentView(R.layout.bookmarks_databaseview_bottom_appbar);
129         } else {
130             // `Window.FEATURE_ACTION_MODE_OVERLAY` makes the contextual action mode cover the support action bar.  It must be requested before the content is set.
131             supportRequestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
132
133             // Set the content view.
134             setContentView(R.layout.bookmarks_databaseview_top_appbar);
135         }
136
137         // Get a handle for the toolbar.
138         Toolbar toolbar = findViewById(R.id.bookmarks_databaseview_toolbar);
139
140         // Set the support action bar.
141         setSupportActionBar(toolbar);
142
143         // Get a handle for the action bar.
144         ActionBar actionBar = getSupportActionBar();
145
146         // Remove the incorrect lint warning that the action bar might be null.
147         assert actionBar != null;
148
149         // Display the spinner and the back arrow in the action bar.
150         actionBar.setCustomView(R.layout.spinner);
151         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
152
153         // Initialize the database handler.
154         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
155
156         // Setup a matrix cursor for "All Folders" and "Home Folder".
157         String[] matrixCursorColumnNames = {BookmarksDatabaseHelper.ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
158         MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
159         matrixCursor.addRow(new Object[]{ALL_FOLDERS_DATABASE_ID, getString(R.string.all_folders)});
160         matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
161
162         // Get a cursor with the list of all the folders.
163         Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
164
165         // Combine the matrix cursor and the folders cursor.
166         MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
167
168
169         // Get the default folder bitmap.  `ContextCompat` must be used until the minimum API >= 21.
170         Drawable defaultFolderDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_blue_bitmap);
171
172         // Cast the default folder drawable to a bitmap drawable.
173         BitmapDrawable defaultFolderBitmapDrawable = (BitmapDrawable) defaultFolderDrawable;
174
175         // Remove the incorrect lint warning that `.getBitmap()` might be null.
176         assert defaultFolderBitmapDrawable != null;
177
178         // Convert the default folder bitmap drawable to a bitmap.
179         Bitmap defaultFolderBitmap = defaultFolderBitmapDrawable.getBitmap();
180
181
182         // Create a resource cursor adapter for the spinner.
183         ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(this, R.layout.appbar_spinner_item, foldersMergeCursor, 0) {
184             @Override
185             public void bindView(View view, Context context, Cursor cursor) {
186                 // Get handles for the spinner views.
187                 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
188                 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
189
190                 // Set the folder icon according to the type.
191                 if (foldersMergeCursor.getPosition() > 1) {  // Set a user folder icon.
192                     // Initialize a default folder icon byte array output stream.
193                     ByteArrayOutputStream defaultFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
194
195                     // Covert the default folder bitmap to a PNG and store it in the output stream.  `0` is for lossless compression (the only option for a PNG).
196                     defaultFolderBitmap.compress(Bitmap.CompressFormat.PNG, 0, defaultFolderIconByteArrayOutputStream);
197
198                     // Convert the default folder icon output stream to a byte array.
199                     byte[] defaultFolderIconByteArray = defaultFolderIconByteArrayOutputStream.toByteArray();
200
201
202                     // Get the folder icon byte array from the cursor.
203                     byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
204
205                     // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
206                     Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
207
208
209                     // Set the icon according to the type.
210                     if (Arrays.equals(folderIconByteArray, defaultFolderIconByteArray)) {  // The default folder icon is used.
211                         // Set a smaller and darker folder icon, which works well with the spinner.
212                         spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_dark_blue));
213                     } else {  // A custom folder icon is uses.
214                         // Set the folder image stored in the cursor.
215                         spinnerItemImageView.setImageBitmap(folderIconBitmap);
216                     }
217                 } else {  // Set the `All Folders` or `Home Folder` icon.
218                     // Set the gray folder image.  `ContextCompat` must be used until the minimum API >= 21.
219                     spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
220                 }
221
222                 // Set the text view to display the folder name.
223                 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME)));
224             }
225         };
226
227         // Set the resource cursor adapter drop drown view resource.
228         foldersCursorAdapter.setDropDownViewResource(R.layout.appbar_spinner_dropdown_item);
229
230         // Get a handle for the folder spinner and set the adapter.
231         Spinner folderSpinner = findViewById(R.id.spinner);
232         folderSpinner.setAdapter(foldersCursorAdapter);
233
234         // Wait to set the on item selected listener until the spinner has been inflated.  Otherwise the activity will crash on restart.
235         folderSpinner.post(() -> {
236             // Handle taps on the spinner dropdown.
237             folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
238                 @Override
239                 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
240                     // Store the current folder database ID.
241                     currentFolderDatabaseId = (int) id;
242
243                     // Get a handle for the selected view.
244                     TextView selectedFolderTextView = findViewById(R.id.spinner_item_textview);
245
246                     // Store the current folder name.
247                     currentFolderName = selectedFolderTextView.getText().toString();
248
249                     // Update the list view.
250                     updateBookmarksListView();
251                 }
252
253                 @Override
254                 public void onNothingSelected(AdapterView<?> parent) {
255                     // Do nothing.
256                 }
257             });
258         });
259
260
261         // Get a handle for the bookmarks listview.
262         ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
263
264         // Check to see if the activity was restarted.
265         if (savedInstanceState == null) {  // The activity was not restarted.
266             // Set the default current folder database ID.
267             currentFolderDatabaseId = ALL_FOLDERS_DATABASE_ID;
268         } else {  // The activity was restarted.
269             // Restore the class variables from the saved instance state.
270             currentFolderDatabaseId = savedInstanceState.getInt(CURRENT_FOLDER_DATABASE_ID);
271             currentFolderName = savedInstanceState.getString(CURRENT_FOLDER_NAME);
272             sortByDisplayOrder = savedInstanceState.getBoolean(SORT_BY_DISPLAY_ORDER);
273
274             // Update the spinner if the home folder is selected.  Android handles this by default for the main cursor but not the matrix cursor.
275             if (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) {
276                 folderSpinner.setSelection(1);
277             }
278         }
279
280         // Update the bookmarks listview.
281         updateBookmarksListView();
282
283         // Setup a `CursorAdapter` with `this` context.  `false` disables autoRequery.
284         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
285             @Override
286             public View newView(Context context, Cursor cursor, ViewGroup parent) {
287                 // Inflate the individual item layout.  `false` does not attach it to the root.
288                 return getLayoutInflater().inflate(R.layout.bookmarks_databaseview_item_linearlayout, parent, false);
289             }
290
291             @Override
292             public void bindView(View view, Context context, Cursor cursor) {
293                 boolean isFolder = (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
294
295                 // Get the database ID from the `Cursor` and display it in `bookmarkDatabaseIdTextView`.
296                 int bookmarkDatabaseId = cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID));
297                 TextView bookmarkDatabaseIdTextView = view.findViewById(R.id.bookmarks_databaseview_database_id);
298                 bookmarkDatabaseIdTextView.setText(String.valueOf(bookmarkDatabaseId));
299
300                 // Get the favorite icon byte array from the `Cursor`.
301                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
302                 // Convert the byte array to a `Bitmap` beginning at the beginning at the first byte and ending at the last.
303                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
304                 // Display the bitmap in `bookmarkFavoriteIcon`.
305                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmarks_databaseview_favorite_icon);
306                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
307
308                 // Get the bookmark name from the `Cursor` and display it in `bookmarkNameTextView`.
309                 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
310                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_name);
311                 bookmarkNameTextView.setText(bookmarkNameString);
312
313                 // Make the font bold for folders.
314                 if (isFolder) {
315                     // The first argument is `null` prevent changing of the font.
316                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
317                 } else {  // Reset the font to default.
318                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
319                 }
320
321                 // Get the bookmark URL form the `Cursor` and display it in `bookmarkUrlTextView`.
322                 String bookmarkUrlString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL));
323                 TextView bookmarkUrlTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_url);
324                 bookmarkUrlTextView.setText(bookmarkUrlString);
325
326                 // Hide the URL if the bookmark is a folder.
327                 if (isFolder) {
328                     bookmarkUrlTextView.setVisibility(View.GONE);
329                 } else {
330                     bookmarkUrlTextView.setVisibility(View.VISIBLE);
331                 }
332
333                 // Get the display order from the `Cursor` and display it in `bookmarkDisplayOrderTextView`.
334                 int bookmarkDisplayOrder = cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER));
335                 TextView bookmarkDisplayOrderTextView = view.findViewById(R.id.bookmarks_databaseview_display_order);
336                 bookmarkDisplayOrderTextView.setText(String.valueOf(bookmarkDisplayOrder));
337
338                 // Get the parent folder from the `Cursor` and display it in `bookmarkParentFolder`.
339                 String bookmarkParentFolder = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.PARENT_FOLDER));
340                 ImageView parentFolderImageView = view.findViewById(R.id.bookmarks_databaseview_parent_folder_icon);
341                 TextView bookmarkParentFolderTextView = view.findViewById(R.id.bookmarks_databaseview_parent_folder);
342
343                 // Make the folder name gray if it is the home folder.
344                 if (bookmarkParentFolder.isEmpty()) {
345                     parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_gray));
346                     bookmarkParentFolderTextView.setText(R.string.home_folder);
347                     bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_500));
348                 } else {
349                     parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_dark_blue));
350                     bookmarkParentFolderTextView.setText(bookmarkParentFolder);
351
352                     // Get the current theme status.
353                     int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
354
355                     // Set the text color according to the theme.
356                     if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
357                         // This color is a little darker than the default night mode text.  But the effect is rather nice.
358                         bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_300));
359                     } else {
360                         bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
361                     }
362                 }
363             }
364         };
365
366         // Update the ListView.
367         bookmarksListView.setAdapter(bookmarksCursorAdapter);
368
369         // Set a listener to edit a bookmark when it is tapped.
370         bookmarksListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
371             // Convert the database ID to an int.
372             int databaseId = (int) id;
373
374             // Show the edit bookmark or edit bookmark folder dialog.
375             if (bookmarksDatabaseHelper.isFolder(databaseId)) {
376                 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
377                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
378
379                 // Show the edit bookmark folder dialog.
380                 DialogFragment editBookmarkFolderDatabaseViewDialog = EditBookmarkFolderDatabaseViewDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
381                 editBookmarkFolderDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
382             } else {
383                 // Show the edit bookmark dialog.
384                 DialogFragment editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
385                 editBookmarkDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
386             }
387         });
388
389         // Handle long presses on the list view.
390         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
391             // Instantiate the common variables.
392             MenuItem selectAllMenuItem;
393             MenuItem deleteMenuItem;
394             boolean deletingBookmarks;
395
396             @Override
397             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
398                 // Inflate the menu for the contextual app bar.
399                 getMenuInflater().inflate(R.menu.bookmarks_databaseview_context_menu, menu);
400
401                 // Set the title.
402                 mode.setTitle(R.string.bookmarks);
403
404                 // Get handles for the menu items.
405                 selectAllMenuItem = menu.findItem(R.id.select_all);
406                 deleteMenuItem = menu.findItem(R.id.delete);
407
408                 // Disable the delete menu item if a delete is pending.
409                 deleteMenuItem.setEnabled(!deletingBookmarks);
410
411                 // Get the number of currently selected bookmarks.
412                 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
413
414                 // Set the action mode subtitle according to the number of selected bookmarks.  This must be set here or it will be missing if the activity is restarted.
415                 mode.setSubtitle(getString(R.string.selected) + "  " + numberOfSelectedBookmarks);
416
417                 // Do not show the select all menu item if all the bookmarks are already checked.
418                 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
419                     selectAllMenuItem.setVisible(false);
420                 }
421
422                 // Make it so.
423                 return true;
424             }
425
426             @Override
427             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
428                 // Do nothing.
429                 return false;
430             }
431
432             @Override
433             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
434                 // Calculate the number of selected bookmarks.
435                 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
436
437                 // Only run the commands if at least one bookmark is selected.  Otherwise, a context menu with 0 selected bookmarks is briefly displayed.
438                 if (numberOfSelectedBookmarks > 0) {
439                     // Update the action mode subtitle according to the number of selected bookmarks.
440                     mode.setSubtitle(getString(R.string.selected) + "  " + numberOfSelectedBookmarks);
441
442                     // Only show the select all menu item if all of the bookmarks are not already selected.
443                     selectAllMenuItem.setVisible(bookmarksListView.getCheckedItemCount() != bookmarksListView.getCount());
444
445                     // Convert the database ID to an int.
446                     int databaseId = (int) id;
447
448                     // If a folder was selected, also select all the contents.
449                     if (checked && bookmarksDatabaseHelper.isFolder(databaseId)) {
450                         selectAllBookmarksInFolder(databaseId);
451                     }
452
453                     // Do not allow a bookmark to be deselected if the folder is selected.
454                     if (!checked) {
455                         // Get the folder name.
456                         String folderName = bookmarksDatabaseHelper.getParentFolderName((int) id);
457
458                         // If the bookmark is not in the root folder, check to see if the folder is selected.
459                         if (!folderName.isEmpty()) {
460                             // Get the database ID of the folder.
461                             int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderName);
462
463                             // Move the bookmarks cursor to the first position.
464                             bookmarksCursor.moveToFirst();
465
466                             // Initialize the folder position variable.
467                             int folderPosition = -1;
468
469                             // Get the position of the folder in the bookmarks cursor.
470                             while ((folderPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
471                                 // Check if the folder database ID matches the bookmark database ID.
472                                 if (folderDatabaseId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID))) {
473                                     // Get the folder position.
474                                     folderPosition = bookmarksCursor.getPosition();
475
476                                     // Check if the folder is selected.
477                                     if (bookmarksListView.isItemChecked(folderPosition)) {
478                                         // Reselect the bookmark.
479                                         bookmarksListView.setItemChecked(position, true);
480
481                                         // Display a snackbar explaining why the bookmark cannot be deselected.
482                                         Snackbar.make(bookmarksListView, R.string.cannot_deselect_bookmark, Snackbar.LENGTH_LONG).show();
483                                     }
484                                 }
485
486                                 // Increment the bookmarks cursor.
487                                 bookmarksCursor.moveToNext();
488                             }
489                         }
490                     }
491                 }
492             }
493
494             @Override
495             public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
496                 // Get a the menu item ID.
497                 int menuItemId = menuItem.getItemId();
498
499                 // Run the command that corresponds to the selected menu item.
500                 if (menuItemId == R.id.select_all) {  // Select all the bookmarks.
501                     // Get the total number of bookmarks.
502                     int numberOfBookmarks = bookmarksListView.getCount();
503
504                     // Select them all.
505                     for (int i = 0; i < numberOfBookmarks; i++) {
506                         bookmarksListView.setItemChecked(i, true);
507                     }
508                 } else if (menuItemId == R.id.delete) {  // Delete the selected bookmarks.
509                     // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
510                     deletingBookmarks = true;
511
512                     // Get an array of the selected row IDs.
513                     long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
514
515                     // 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.
516                     SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
517
518                     // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
519                     switch (currentFolderDatabaseId) {
520                         // Get a cursor with all the folders.
521                         case ALL_FOLDERS_DATABASE_ID:
522                             if (sortByDisplayOrder) {
523                                 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray);
524                             } else {
525                                 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksExcept(selectedBookmarksIdsLongArray);
526                             }
527                             break;
528
529                         // Get a cursor for the home folder.
530                         case HOME_FOLDER_DATABASE_ID:
531                             if (sortByDisplayOrder) {
532                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, "");
533                             } else {
534                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, "");
535                             }
536                             break;
537
538                         // Display the selected folder.
539                         default:
540                             // Get a cursor for the selected folder.
541                             if (sortByDisplayOrder) {
542                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolderName);
543                             } else {
544                                 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, currentFolderName);
545                             }
546                     }
547
548                     // Update the list view.
549                     bookmarksCursorAdapter.changeCursor(bookmarksCursor);
550
551                     // Create a Snackbar with the number of deleted bookmarks.
552                     bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout),
553                             getString(R.string.bookmarks_deleted) + "  " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG)
554                             .setAction(R.string.undo, view -> {
555                                 // Do nothing because everything will be handled by `onDismissed()` below.
556                             })
557                             .addCallback(new Snackbar.Callback() {
558                                 @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
559                                 @Override
560                                 public void onDismissed(Snackbar snackbar, int event) {
561                                     if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The user pushed the undo button.
562                                         // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks.
563                                         updateBookmarksListView();
564
565                                         // Re-select the previously selected bookmarks.
566                                         for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
567                                             bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
568                                         }
569                                     } else {  // The Snackbar was dismissed without the undo button being pushed.
570                                         // Delete each selected bookmark.
571                                         for (long databaseIdLong : selectedBookmarksIdsLongArray) {
572                                             // Convert `databaseIdLong` to an int.
573                                             int databaseIdInt = (int) databaseIdLong;
574
575                                             // Delete the selected bookmark.
576                                             bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
577                                         }
578                                     }
579
580                                     // Reset the deleting bookmarks flag.
581                                     deletingBookmarks = false;
582
583                                     // Enable the delete menu item.
584                                     deleteMenuItem.setEnabled(true);
585
586                                     // Close the activity if back has been pressed.
587                                     if (closeActivityAfterDismissingSnackbar) {
588                                         onBackPressed();
589                                     }
590                                 }
591                             });
592
593                     // Show the Snackbar.
594                     bookmarksDeletedSnackbar.show();
595                 }
596
597                 // Consume the click.
598                 return false;
599             }
600
601             @Override
602             public void onDestroyActionMode(ActionMode mode) {
603                 // Do nothing.
604             }
605         });
606     }
607
608     @Override
609     public boolean onCreateOptionsMenu(Menu menu) {
610         // Inflate the menu.
611         getMenuInflater().inflate(R.menu.bookmarks_databaseview_options_menu, menu);
612
613         // Get a handle for the sort menu item.
614         MenuItem sortMenuItem = menu.findItem(R.id.sort);
615
616         // Change the sort menu item icon if the listview is sorted by display order, which restores the state after a restart.
617         if (sortByDisplayOrder) {
618             sortMenuItem.setIcon(R.drawable.sort_selected);
619         }
620
621         // Success.
622         return true;
623     }
624
625     @Override
626     public boolean onOptionsItemSelected(MenuItem menuItem) {
627         // Get the menu item ID.
628         int menuItemId = menuItem.getItemId();
629
630         // Run the command that corresponds to the selected menu item.
631         if (menuItemId == android.R.id.home) {  // Go Home.  The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
632             // Exit the activity.
633             onBackPressed();
634         } else if (menuItemId == R.id.sort) {  // Toggle the sort mode.
635             // Update the sort by display order tracker.
636             sortByDisplayOrder = !sortByDisplayOrder;
637
638             // Get a handle for the bookmarks list view.
639             ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
640
641             // Update the icon and display a snackbar.
642             if (sortByDisplayOrder) {  // Sort by display order.
643                 // Update the icon.
644                 menuItem.setIcon(R.drawable.sort_selected);
645
646                 // Display a Snackbar indicating the current sort type.
647                 Snackbar.make(bookmarksListView, R.string.sorted_by_display_order, Snackbar.LENGTH_SHORT).show();
648             } else {  // Sort by database id.
649                 // Update the icon.
650                 menuItem.setIcon(R.drawable.sort);
651
652                 // Display a Snackbar indicating the current sort type.
653                 Snackbar.make(bookmarksListView, R.string.sorted_by_database_id, Snackbar.LENGTH_SHORT).show();
654             }
655
656             // Update the list view.
657             updateBookmarksListView();
658         }
659
660         // Consume the event.
661         return true;
662     }
663
664     @Override
665     public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
666         // Run the default commands.
667         super.onSaveInstanceState(savedInstanceState);
668
669         // Store the class variables in the bundle.
670         savedInstanceState.putInt(CURRENT_FOLDER_DATABASE_ID, currentFolderDatabaseId);
671         savedInstanceState.putString(CURRENT_FOLDER_NAME, currentFolderName);
672         savedInstanceState.putBoolean(SORT_BY_DISPLAY_ORDER, sortByDisplayOrder);
673     }
674
675     @Override
676     public void onBackPressed() {
677         // Check to see if a snackbar is currently displayed.  If so, it must be closed before existing so that a pending delete is completed before reloading the list view in the bookmarks activity.
678         if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks deleted snackbar before going home.
679             // Set the close flag.
680             closeActivityAfterDismissingSnackbar = true;
681
682             // Dismiss the snackbar.
683             bookmarksDeletedSnackbar.dismiss();
684         } else {  // Go home immediately.
685             // Update the current folder in the bookmarks activity.
686             if ((currentFolderDatabaseId == ALL_FOLDERS_DATABASE_ID) || (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID)) {  // All folders or the the home folder are currently displayed.
687                 // Load the home folder.
688                 BookmarksActivity.currentFolder = "";
689             } else {  // A subfolder is currently displayed.
690                 // Load the current folder.
691                 BookmarksActivity.currentFolder = currentFolderName;
692             }
693
694             // Reload the bookmarks list view when returning to the bookmarks activity.
695             BookmarksActivity.restartFromBookmarksDatabaseViewActivity = true;
696
697             // Exit the bookmarks database view activity.
698             super.onBackPressed();
699         }
700     }
701
702     private void updateBookmarksListView() {
703         // Populate the bookmarks list view based on the spinner selection.
704         switch (currentFolderDatabaseId) {
705             // Get a cursor with all the folders.
706             case ALL_FOLDERS_DATABASE_ID:
707                 if (sortByDisplayOrder) {
708                     bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrder();
709                 } else {
710                     bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
711                 }
712                 break;
713
714             // Get a cursor for the home folder.
715             case HOME_FOLDER_DATABASE_ID:
716                 if (sortByDisplayOrder) {
717                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder("");
718                 } else {
719                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarks("");
720                 }
721                 break;
722
723             // Display the selected folder.
724             default:
725                 // Get a cursor for the selected folder.
726                 if (sortByDisplayOrder) {
727                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolderName);
728                 } else {
729                     bookmarksCursor = bookmarksDatabaseHelper.getBookmarks(currentFolderName);
730                 }
731         }
732
733         // Update the cursor adapter if it isn't null, which happens when the activity is restarted.
734         if (bookmarksCursorAdapter != null) {
735             bookmarksCursorAdapter.changeCursor(bookmarksCursor);
736         }
737     }
738
739     private void selectAllBookmarksInFolder(int folderId) {
740         // Get a handle for the bookmarks list view.
741         ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
742
743         // Get the folder name.
744         String folderName = bookmarksDatabaseHelper.getFolderName(folderId);
745
746         // Get a cursor with the contents of the folder.
747         Cursor folderCursor = bookmarksDatabaseHelper.getBookmarks(folderName);
748
749         // Move to the beginning of the cursor.
750         folderCursor.moveToFirst();
751
752         while (folderCursor.getPosition() < folderCursor.getCount()) {
753             // Get the bookmark database ID.
754             int bookmarkId = folderCursor.getInt(folderCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID));
755
756             // Move the bookmarks cursor to the first position.
757             bookmarksCursor.moveToFirst();
758
759             // Initialize the bookmark position variable.
760             int bookmarkPosition = -1;
761
762             // Get the position of this bookmark in the bookmarks cursor.
763             while ((bookmarkPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
764                 // Check if the bookmark IDs match.
765                 if (bookmarkId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID))) {
766                     // Get the bookmark position.
767                     bookmarkPosition = bookmarksCursor.getPosition();
768
769                     // If this bookmark is a folder, select all the bookmarks inside it.
770                     if (bookmarksDatabaseHelper.isFolder(bookmarkId)) {
771                         selectAllBookmarksInFolder(bookmarkId);
772                     }
773
774                     // Select the bookmark.
775                     bookmarksListView.setItemChecked(bookmarkPosition, true);
776                 }
777
778                 // Increment the bookmarks cursor position.
779                 bookmarksCursor.moveToNext();
780             }
781
782             // Move to the next position.
783             folderCursor.moveToNext();
784         }
785     }
786
787     @Override
788     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
789         // Get the dialog from the dialog fragment.
790         Dialog dialog = dialogFragment.getDialog();
791
792         // Remove the incorrect lint warning below that the dialog might be null.
793         assert dialog != null;
794
795         // Get handles for the views from dialog fragment.
796         RadioButton currentIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
797         EditText bookmarkNameEditText = dialog.findViewById(R.id.bookmark_name_edittext);
798         EditText bookmarkUrlEditText = dialog.findViewById(R.id.bookmark_url_edittext);
799         Spinner folderSpinner = dialog.findViewById(R.id.bookmark_folder_spinner);
800         EditText displayOrderEditText = dialog.findViewById(R.id.bookmark_display_order_edittext);
801
802         // Extract the bookmark information.
803         String bookmarkNameString = bookmarkNameEditText.getText().toString();
804         String bookmarkUrlString = bookmarkUrlEditText.getText().toString();
805         int folderDatabaseId = (int) folderSpinner.getSelectedItemId();
806         int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
807
808         // Instantiate the parent folder name `String`.
809         String parentFolderNameString;
810
811         // Set the parent folder name.
812         if (folderDatabaseId == HOME_FOLDER_DATABASE_ID) {  // The home folder is selected.  Use `""`.
813             parentFolderNameString = "";
814         } else {  // Get the parent folder name from the database.
815             parentFolderNameString = bookmarksDatabaseHelper.getFolderName(folderDatabaseId);
816         }
817
818         // Update the bookmark.
819         if (currentIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
820             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt);
821         } else {  // Update the bookmark using the `WebView` favorite icon.
822             // Create a favorite icon byte array output stream.
823             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
824
825             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
826             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
827
828             // Convert the favorite icon byte array stream to a byte array.
829             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
830
831             //  Update the bookmark and the favorite icon.
832             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt, newFavoriteIconByteArray);
833         }
834
835         // Update the list view.
836         updateBookmarksListView();
837     }
838
839     @Override
840     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
841         // Get the dialog from the dialog fragment.
842         Dialog dialog = dialogFragment.getDialog();
843
844         // Remove the incorrect lint warning below that the dialog might be null.
845         assert dialog != null;
846
847         // Get handles for the views from dialog fragment.
848         RadioButton currentIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
849         RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
850         ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
851         EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
852         Spinner parentFolderSpinner = dialog.findViewById(R.id.parent_folder_spinner);
853         EditText displayOrderEditText = dialog.findViewById(R.id.display_order_edittext);
854
855         // Extract the folder information.
856         String newFolderNameString = folderNameEditText.getText().toString();
857         int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId();
858         int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
859
860         // Instantiate the parent folder name `String`.
861         String parentFolderNameString;
862
863         // Set the parent folder name.
864         if (parentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) {  // The home folder is selected.  Use `""`.
865             parentFolderNameString = "";
866         } else {  // Get the parent folder name from the database.
867             parentFolderNameString = bookmarksDatabaseHelper.getFolderName(parentFolderDatabaseId);
868         }
869
870         // Update the folder.
871         if (currentIconRadioButton.isChecked()) {  // Update the folder without changing the favorite icon.
872             bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt);
873         } else {  // Update the folder and the icon.
874             // Create the new folder icon Bitmap.
875             Bitmap folderIconBitmap;
876
877             // Populate the new folder icon bitmap.
878             if (defaultIconRadioButton.isChecked()) {
879                 // Get the default folder icon drawable.
880                 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
881
882                 // Convert the folder icon drawable to a bitmap drawable.
883                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
884
885                 // Convert the folder icon bitmap drawable to a bitmap.
886                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
887             } else {  // Use the `WebView` favorite icon.
888                 // Get a copy of the favorite icon bitmap.
889                 folderIconBitmap = favoriteIconBitmap;
890             }
891
892             // Create a folder icon byte array output stream.
893             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
894
895             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
896             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
897
898             // Convert the folder icon byte array stream to a byte array.
899             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
900
901             //  Update the folder and the icon.
902             bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt, newFolderIconByteArray);
903         }
904
905         // Update the list view.
906         updateBookmarksListView();
907     }
908
909     @Override
910     public void onDestroy() {
911         // Close the bookmarks cursor and database.
912         bookmarksCursor.close();
913         bookmarksDatabaseHelper.close();
914
915         // Run the default commands.
916         super.onDestroy();
917     }
918 }