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