2 * Copyright © 2016-2021 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.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;
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.
64 import com.google.android.material.snackbar.Snackbar;
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;
71 import java.io.ByteArrayOutputStream;
72 import java.util.Arrays;
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;
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";
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;
97 public void onCreate(Bundle savedInstanceState) {
98 // Get a handle for the shared preferences.
99 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
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);
105 // Disable screenshots if not allowed.
106 if (!allowScreenshots) {
107 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
110 // Set the activity theme.
111 setTheme(R.style.PrivacyBrowser);
113 // Run the default commands.
114 super.onCreate(savedInstanceState);
116 // Get the intent that launched the activity.
117 Intent launchingIntent = getIntent();
119 // Get the favorite icon byte array.
120 byte[] favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
122 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
123 assert favoriteIconByteArray != null;
125 // Convert the favorite icon byte array to a bitmap and store it in a class variable.
126 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
128 // Set the view according to the theme.
130 // Set the content view.
131 setContentView(R.layout.bookmarks_databaseview_coordinatorlayout_bottom_appbar);
133 // `Window.FEATURE_ACTION_MODE_OVERLAY` makes the contextual action mode cover the support action bar. It must be requested before the content is set.
134 supportRequestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
136 // Set the content view.
137 setContentView(R.layout.bookmarks_databaseview_coordinatorlayout_top_appbar);
140 // Get a handle for the toolbar.
141 Toolbar toolbar = findViewById(R.id.bookmarks_databaseview_toolbar);
143 // Set the support action bar.
144 setSupportActionBar(toolbar);
146 // Get a handle for the action bar.
147 ActionBar actionBar = getSupportActionBar();
149 // Remove the incorrect lint warning that the action bar might be null.
150 assert actionBar != null;
152 // Display the spinner and the back arrow in the action bar.
153 actionBar.setCustomView(R.layout.spinner);
154 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
156 // Initialize the database handler. The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHelper`.
157 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
159 // Setup a matrix cursor for "All Folders" and "Home Folder".
160 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
161 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
162 matrixCursor.addRow(new Object[]{ALL_FOLDERS_DATABASE_ID, getString(R.string.all_folders)});
163 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
165 // Get a cursor with the list of all the folders.
166 Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
168 // Combine the matrix cursor and the folders cursor.
169 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
172 // Get the default folder bitmap. `ContextCompat` must be used until the minimum API >= 21.
173 Drawable defaultFolderDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_blue_bitmap);
175 // Cast the default folder drawable to a bitmap drawable.
176 BitmapDrawable defaultFolderBitmapDrawable = (BitmapDrawable) defaultFolderDrawable;
178 // Remove the incorrect lint warning that `.getBitmap()` might be null.
179 assert defaultFolderBitmapDrawable != null;
181 // Convert the default folder bitmap drawable to a bitmap.
182 Bitmap defaultFolderBitmap = defaultFolderBitmapDrawable.getBitmap();
185 // Create a resource cursor adapter for the spinner.
186 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(this, R.layout.appbar_spinner_item, foldersMergeCursor, 0) {
188 public void bindView(View view, Context context, Cursor cursor) {
189 // Get handles for the spinner views.
190 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
191 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
193 // Set the folder icon according to the type.
194 if (foldersMergeCursor.getPosition() > 1) { // Set a user folder icon.
195 // Initialize a default folder icon byte array output stream.
196 ByteArrayOutputStream defaultFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
198 // 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).
199 defaultFolderBitmap.compress(Bitmap.CompressFormat.PNG, 0, defaultFolderIconByteArrayOutputStream);
201 // Convert the default folder icon output stream to a byte array.
202 byte[] defaultFolderIconByteArray = defaultFolderIconByteArrayOutputStream.toByteArray();
205 // Get the folder icon byte array from the cursor.
206 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
208 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
209 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
212 // Set the icon according to the type.
213 if (Arrays.equals(folderIconByteArray, defaultFolderIconByteArray)) { // The default folder icon is used.
214 // Set a smaller and darker folder icon, which works well with the spinner.
215 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_dark_blue));
216 } else { // A custom folder icon is uses.
217 // Set the folder image stored in the cursor.
218 spinnerItemImageView.setImageBitmap(folderIconBitmap);
220 } else { // Set the `All Folders` or `Home Folder` icon.
221 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
222 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
225 // Set the text view to display the folder name.
226 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
230 // Set the resource cursor adapter drop drown view resource.
231 foldersCursorAdapter.setDropDownViewResource(R.layout.appbar_spinner_dropdown_item);
233 // Get a handle for the folder spinner and set the adapter.
234 Spinner folderSpinner = findViewById(R.id.spinner);
235 folderSpinner.setAdapter(foldersCursorAdapter);
237 // Wait to set the on item selected listener until the spinner has been inflated. Otherwise the activity will crash on restart.
238 folderSpinner.post(() -> {
239 // Handle taps on the spinner dropdown.
240 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
242 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
243 // Store the current folder database ID.
244 currentFolderDatabaseId = (int) id;
246 // Get a handle for the selected view.
247 TextView selectedFolderTextView = findViewById(R.id.spinner_item_textview);
249 // Store the current folder name.
250 currentFolderName = selectedFolderTextView.getText().toString();
252 // Update the list view.
253 updateBookmarksListView();
257 public void onNothingSelected(AdapterView<?> parent) {
264 // Get a handle for the bookmarks listview.
265 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
267 // Check to see if the activity was restarted.
268 if (savedInstanceState == null) { // The activity was not restarted.
269 // Set the default current folder database ID.
270 currentFolderDatabaseId = ALL_FOLDERS_DATABASE_ID;
271 } else { // The activity was restarted.
272 // Restore the class variables from the saved instance state.
273 currentFolderDatabaseId = savedInstanceState.getInt(CURRENT_FOLDER_DATABASE_ID);
274 currentFolderName = savedInstanceState.getString(CURRENT_FOLDER_NAME);
275 sortByDisplayOrder = savedInstanceState.getBoolean(SORT_BY_DISPLAY_ORDER);
277 // Update the spinner if the home folder is selected. Android handles this by default for the main cursor but not the matrix cursor.
278 if (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) {
279 folderSpinner.setSelection(1);
283 // Update the bookmarks listview.
284 updateBookmarksListView();
286 // Setup a `CursorAdapter` with `this` context. `false` disables autoRequery.
287 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
289 public View newView(Context context, Cursor cursor, ViewGroup parent) {
290 // Inflate the individual item layout. `false` does not attach it to the root.
291 return getLayoutInflater().inflate(R.layout.bookmarks_databaseview_item_linearlayout, parent, false);
295 public void bindView(View view, Context context, Cursor cursor) {
296 boolean isFolder = (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
298 // Get the database ID from the `Cursor` and display it in `bookmarkDatabaseIdTextView`.
299 int bookmarkDatabaseId = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper._ID));
300 TextView bookmarkDatabaseIdTextView = view.findViewById(R.id.bookmarks_databaseview_database_id);
301 bookmarkDatabaseIdTextView.setText(String.valueOf(bookmarkDatabaseId));
303 // Get the favorite icon byte array from the `Cursor`.
304 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
305 // Convert the byte array to a `Bitmap` beginning at the beginning at the first byte and ending at the last.
306 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
307 // Display the bitmap in `bookmarkFavoriteIcon`.
308 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmarks_databaseview_favorite_icon);
309 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
311 // Get the bookmark name from the `Cursor` and display it in `bookmarkNameTextView`.
312 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
313 TextView bookmarkNameTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_name);
314 bookmarkNameTextView.setText(bookmarkNameString);
316 // Make the font bold for folders.
318 // The first argument is `null` prevent changing of the font.
319 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
320 } else { // Reset the font to default.
321 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
324 // Get the bookmark URL form the `Cursor` and display it in `bookmarkUrlTextView`.
325 String bookmarkUrlString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
326 TextView bookmarkUrlTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_url);
327 bookmarkUrlTextView.setText(bookmarkUrlString);
329 // Hide the URL if the bookmark is a folder.
331 bookmarkUrlTextView.setVisibility(View.GONE);
333 bookmarkUrlTextView.setVisibility(View.VISIBLE);
336 // Get the display order from the `Cursor` and display it in `bookmarkDisplayOrderTextView`.
337 int bookmarkDisplayOrder = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
338 TextView bookmarkDisplayOrderTextView = view.findViewById(R.id.bookmarks_databaseview_display_order);
339 bookmarkDisplayOrderTextView.setText(String.valueOf(bookmarkDisplayOrder));
341 // Get the parent folder from the `Cursor` and display it in `bookmarkParentFolder`.
342 String bookmarkParentFolder = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
343 ImageView parentFolderImageView = view.findViewById(R.id.bookmarks_databaseview_parent_folder_icon);
344 TextView bookmarkParentFolderTextView = view.findViewById(R.id.bookmarks_databaseview_parent_folder);
346 // Make the folder name gray if it is the home folder.
347 if (bookmarkParentFolder.isEmpty()) {
348 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_gray));
349 bookmarkParentFolderTextView.setText(R.string.home_folder);
350 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_500));
352 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_dark_blue));
353 bookmarkParentFolderTextView.setText(bookmarkParentFolder);
355 // Get the current theme status.
356 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
358 // Set the text color according to the theme.
359 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
360 // This color is a little darker than the default night mode text. But the effect is rather nice.
361 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_300));
363 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
369 // Update the ListView.
370 bookmarksListView.setAdapter(bookmarksCursorAdapter);
372 // Set a listener to edit a bookmark when it is tapped.
373 bookmarksListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
374 // Convert the database ID to an int.
375 int databaseId = (int) id;
377 // Show the edit bookmark or edit bookmark folder dialog.
378 if (bookmarksDatabaseHelper.isFolder(databaseId)) {
379 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
380 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
382 // Show the edit bookmark folder dialog.
383 DialogFragment editBookmarkFolderDatabaseViewDialog = EditBookmarkFolderDatabaseViewDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
384 editBookmarkFolderDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
386 // Show the edit bookmark dialog.
387 DialogFragment editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
388 editBookmarkDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
392 // Handle long presses on the list view.
393 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
394 // Instantiate the common variables.
395 MenuItem selectAllMenuItem;
396 MenuItem deleteMenuItem;
397 boolean deletingBookmarks;
400 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
401 // Inflate the menu for the contextual app bar.
402 getMenuInflater().inflate(R.menu.bookmarks_databaseview_context_menu, menu);
405 mode.setTitle(R.string.bookmarks);
407 // Get handles for the menu items.
408 selectAllMenuItem = menu.findItem(R.id.select_all);
409 deleteMenuItem = menu.findItem(R.id.delete);
411 // Disable the delete menu item if a delete is pending.
412 deleteMenuItem.setEnabled(!deletingBookmarks);
414 // Get the number of currently selected bookmarks.
415 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
417 // 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.
418 mode.setSubtitle(getString(R.string.selected) + " " + numberOfSelectedBookmarks);
420 // Do not show the select all menu item if all the bookmarks are already checked.
421 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
422 selectAllMenuItem.setVisible(false);
430 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
436 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
437 // Calculate the number of selected bookmarks.
438 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
440 // Only run the commands if at least one bookmark is selected. Otherwise, a context menu with 0 selected bookmarks is briefly displayed.
441 if (numberOfSelectedBookmarks > 0) {
442 // Update the action mode subtitle according to the number of selected bookmarks.
443 mode.setSubtitle(getString(R.string.selected) + " " + numberOfSelectedBookmarks);
445 // Only show the select all menu item if all of the bookmarks are not already selected.
446 selectAllMenuItem.setVisible(bookmarksListView.getCheckedItemCount() != bookmarksListView.getCount());
448 // Convert the database ID to an int.
449 int databaseId = (int) id;
451 // If a folder was selected, also select all the contents.
452 if (checked && bookmarksDatabaseHelper.isFolder(databaseId)) {
453 selectAllBookmarksInFolder(databaseId);
456 // Do not allow a bookmark to be deselected if the folder is selected.
458 // Get the folder name.
459 String folderName = bookmarksDatabaseHelper.getParentFolderName((int) id);
461 // If the bookmark is not in the root folder, check to see if the folder is selected.
462 if (!folderName.isEmpty()) {
463 // Get the database ID of the folder.
464 int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderName);
466 // Move the bookmarks cursor to the first position.
467 bookmarksCursor.moveToFirst();
469 // Initialize the folder position variable.
470 int folderPosition = -1;
472 // Get the position of the folder in the bookmarks cursor.
473 while ((folderPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
474 // Check if the folder database ID matches the bookmark database ID.
475 if (folderDatabaseId == bookmarksCursor.getInt((bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID)))) {
476 // Get the folder position.
477 folderPosition = bookmarksCursor.getPosition();
479 // Check if the folder is selected.
480 if (bookmarksListView.isItemChecked(folderPosition)) {
481 // Reselect the bookmark.
482 bookmarksListView.setItemChecked(position, true);
484 // Display a snackbar explaining why the bookmark cannot be deselected.
485 Snackbar.make(bookmarksListView, R.string.cannot_deselect_bookmark, Snackbar.LENGTH_LONG).show();
489 // Increment the bookmarks cursor.
490 bookmarksCursor.moveToNext();
498 public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
499 // Get a the menu item ID.
500 int menuItemId = menuItem.getItemId();
502 // Run the command that corresponds to the selected menu item.
503 if (menuItemId == R.id.select_all) { // Select all the bookmarks.
504 // Get the total number of bookmarks.
505 int numberOfBookmarks = bookmarksListView.getCount();
508 for (int i = 0; i < numberOfBookmarks; i++) {
509 bookmarksListView.setItemChecked(i, true);
511 } else if (menuItemId == R.id.delete) { // Delete the selected bookmarks.
512 // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
513 deletingBookmarks = true;
515 // Get an array of the selected row IDs.
516 long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
518 // 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.
519 SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
521 // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
522 switch (currentFolderDatabaseId) {
523 // Get a cursor with all the folders.
524 case ALL_FOLDERS_DATABASE_ID:
525 if (sortByDisplayOrder) {
526 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray);
528 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksExcept(selectedBookmarksIdsLongArray);
532 // Get a cursor for the home folder.
533 case HOME_FOLDER_DATABASE_ID:
534 if (sortByDisplayOrder) {
535 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, "");
537 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, "");
541 // Display the selected folder.
543 // Get a cursor for the selected folder.
544 if (sortByDisplayOrder) {
545 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolderName);
547 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, currentFolderName);
551 // Update the list view.
552 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
554 // Create a Snackbar with the number of deleted bookmarks.
555 bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout),
556 getString(R.string.bookmarks_deleted) + " " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG)
557 .setAction(R.string.undo, view -> {
558 // Do nothing because everything will be handled by `onDismissed()` below.
560 .addCallback(new Snackbar.Callback() {
561 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
563 public void onDismissed(Snackbar snackbar, int event) {
564 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) { // The user pushed the undo button.
565 // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks.
566 updateBookmarksListView();
568 // Re-select the previously selected bookmarks.
569 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
570 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
572 } else { // The Snackbar was dismissed without the undo button being pushed.
573 // Delete each selected bookmark.
574 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
575 // Convert `databaseIdLong` to an int.
576 int databaseIdInt = (int) databaseIdLong;
578 // Delete the selected bookmark.
579 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
583 // Reset the deleting bookmarks flag.
584 deletingBookmarks = false;
586 // Enable the delete menu item.
587 deleteMenuItem.setEnabled(true);
589 // Close the activity if back has been pressed.
590 if (closeActivityAfterDismissingSnackbar) {
596 // Show the Snackbar.
597 bookmarksDeletedSnackbar.show();
600 // Consume the click.
605 public void onDestroyActionMode(ActionMode mode) {
612 public boolean onCreateOptionsMenu(Menu menu) {
614 getMenuInflater().inflate(R.menu.bookmarks_databaseview_options_menu, menu);
616 // Get the current theme status.
617 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
619 // Get a handle for the sort menu item.
620 MenuItem sortMenuItem = menu.findItem(R.id.sort);
622 // Change the sort menu item icon if the listview is sorted by display order, which restores the state after a restart.
623 if (sortByDisplayOrder) {
624 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
625 sortMenuItem.setIcon(R.drawable.sort_selected_day);
627 sortMenuItem.setIcon(R.drawable.sort_selected_night);
636 public boolean onOptionsItemSelected(MenuItem menuItem) {
637 // Get the menu item ID.
638 int menuItemId = menuItem.getItemId();
640 // Run the command that corresponds to the selected menu item.
641 if (menuItemId == android.R.id.home) { // Go Home. The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
642 // Exit the activity.
644 } else if (menuItemId == R.id.sort) { // Toggle the sort mode.
645 // Update the sort by display order tracker.
646 sortByDisplayOrder = !sortByDisplayOrder;
648 // Get a handle for the bookmarks list view.
649 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
651 // Get the current theme status.
652 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
654 // Update the icon and display a snackbar.
655 if (sortByDisplayOrder) { // Sort by display order.
656 // Update the icon according to the theme.
657 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
658 menuItem.setIcon(R.drawable.sort_selected_day);
660 menuItem.setIcon(R.drawable.sort_selected_night);
663 // Display a Snackbar indicating the current sort type.
664 Snackbar.make(bookmarksListView, R.string.sorted_by_display_order, Snackbar.LENGTH_SHORT).show();
665 } else { // Sort by database id.
666 // Update the icon according to the theme.
667 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
668 menuItem.setIcon(R.drawable.sort_day);
670 menuItem.setIcon(R.drawable.sort_night);
673 // Display a Snackbar indicating the current sort type.
674 Snackbar.make(bookmarksListView, R.string.sorted_by_database_id, Snackbar.LENGTH_SHORT).show();
677 // Update the list view.
678 updateBookmarksListView();
681 // Consume the event.
686 public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
687 // Run the default commands.
688 super.onSaveInstanceState(savedInstanceState);
690 // Store the class variables in the bundle.
691 savedInstanceState.putInt(CURRENT_FOLDER_DATABASE_ID, currentFolderDatabaseId);
692 savedInstanceState.putString(CURRENT_FOLDER_NAME, currentFolderName);
693 savedInstanceState.putBoolean(SORT_BY_DISPLAY_ORDER, sortByDisplayOrder);
697 public void onBackPressed() {
698 // 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.
699 if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks deleted snackbar before going home.
700 // Set the close flag.
701 closeActivityAfterDismissingSnackbar = true;
703 // Dismiss the snackbar.
704 bookmarksDeletedSnackbar.dismiss();
705 } else { // Go home immediately.
706 // Update the current folder in the bookmarks activity.
707 if ((currentFolderDatabaseId == ALL_FOLDERS_DATABASE_ID) || (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID)) { // All folders or the the home folder are currently displayed.
708 // Load the home folder.
709 BookmarksActivity.currentFolder = "";
710 } else { // A subfolder is currently displayed.
711 // Load the current folder.
712 BookmarksActivity.currentFolder = currentFolderName;
715 // Reload the bookmarks list view when returning to the bookmarks activity.
716 BookmarksActivity.restartFromBookmarksDatabaseViewActivity = true;
718 // Exit the bookmarks database view activity.
719 super.onBackPressed();
723 private void updateBookmarksListView() {
724 // Populate the bookmarks list view based on the spinner selection.
725 switch (currentFolderDatabaseId) {
726 // Get a cursor with all the folders.
727 case ALL_FOLDERS_DATABASE_ID:
728 if (sortByDisplayOrder) {
729 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrder();
731 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
735 // Get a cursor for the home folder.
736 case HOME_FOLDER_DATABASE_ID:
737 if (sortByDisplayOrder) {
738 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder("");
740 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks("");
744 // Display the selected folder.
746 // Get a cursor for the selected folder.
747 if (sortByDisplayOrder) {
748 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolderName);
750 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks(currentFolderName);
754 // Update the cursor adapter if it isn't null, which happens when the activity is restarted.
755 if (bookmarksCursorAdapter != null) {
756 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
760 private void selectAllBookmarksInFolder(int folderId) {
761 // Get a handle for the bookmarks list view.
762 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
764 // Get the folder name.
765 String folderName = bookmarksDatabaseHelper.getFolderName(folderId);
767 // Get a cursor with the contents of the folder.
768 Cursor folderCursor = bookmarksDatabaseHelper.getBookmarks(folderName);
770 // Move to the beginning of the cursor.
771 folderCursor.moveToFirst();
773 while (folderCursor.getPosition() < folderCursor.getCount()) {
774 // Get the bookmark database ID.
775 int bookmarkId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
777 // Move the bookmarks cursor to the first position.
778 bookmarksCursor.moveToFirst();
780 // Initialize the bookmark position variable.
781 int bookmarkPosition = -1;
783 // Get the position of this bookmark in the bookmarks cursor.
784 while ((bookmarkPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
785 // Check if the bookmark IDs match.
786 if (bookmarkId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID))) {
787 // Get the bookmark position.
788 bookmarkPosition = bookmarksCursor.getPosition();
790 // If this bookmark is a folder, select all the bookmarks inside it.
791 if (bookmarksDatabaseHelper.isFolder(bookmarkId)) {
792 selectAllBookmarksInFolder(bookmarkId);
795 // Select the bookmark.
796 bookmarksListView.setItemChecked(bookmarkPosition, true);
799 // Increment the bookmarks cursor position.
800 bookmarksCursor.moveToNext();
803 // Move to the next position.
804 folderCursor.moveToNext();
809 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
810 // Get the dialog from the dialog fragment.
811 Dialog dialog = dialogFragment.getDialog();
813 // Remove the incorrect lint warning below that the dialog might be null.
814 assert dialog != null;
816 // Get handles for the views from dialog fragment.
817 RadioButton currentIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
818 EditText bookmarkNameEditText = dialog.findViewById(R.id.bookmark_name_edittext);
819 EditText bookmarkUrlEditText = dialog.findViewById(R.id.bookmark_url_edittext);
820 Spinner folderSpinner = dialog.findViewById(R.id.bookmark_folder_spinner);
821 EditText displayOrderEditText = dialog.findViewById(R.id.bookmark_display_order_edittext);
823 // Extract the bookmark information.
824 String bookmarkNameString = bookmarkNameEditText.getText().toString();
825 String bookmarkUrlString = bookmarkUrlEditText.getText().toString();
826 int folderDatabaseId = (int) folderSpinner.getSelectedItemId();
827 int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
829 // Instantiate the parent folder name `String`.
830 String parentFolderNameString;
832 // Set the parent folder name.
833 if (folderDatabaseId == HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
834 parentFolderNameString = "";
835 } else { // Get the parent folder name from the database.
836 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(folderDatabaseId);
839 // Update the bookmark.
840 if (currentIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
841 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt);
842 } else { // Update the bookmark using the `WebView` favorite icon.
843 // Create a favorite icon byte array output stream.
844 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
846 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
847 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
849 // Convert the favorite icon byte array stream to a byte array.
850 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
852 // Update the bookmark and the favorite icon.
853 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt, newFavoriteIconByteArray);
856 // Update the list view.
857 updateBookmarksListView();
861 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
862 // Get the dialog from the dialog fragment.
863 Dialog dialog = dialogFragment.getDialog();
865 // Remove the incorrect lint warning below that the dialog might be null.
866 assert dialog != null;
868 // Get handles for the views from dialog fragment.
869 RadioButton currentIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
870 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
871 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
872 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
873 Spinner parentFolderSpinner = dialog.findViewById(R.id.parent_folder_spinner);
874 EditText displayOrderEditText = dialog.findViewById(R.id.display_order_edittext);
876 // Extract the folder information.
877 String newFolderNameString = folderNameEditText.getText().toString();
878 int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId();
879 int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
881 // Instantiate the parent folder name `String`.
882 String parentFolderNameString;
884 // Set the parent folder name.
885 if (parentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
886 parentFolderNameString = "";
887 } else { // Get the parent folder name from the database.
888 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(parentFolderDatabaseId);
891 // Update the folder.
892 if (currentIconRadioButton.isChecked()) { // Update the folder without changing the favorite icon.
893 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt);
894 } else { // Update the folder and the icon.
895 // Create the new folder icon Bitmap.
896 Bitmap folderIconBitmap;
898 // Populate the new folder icon bitmap.
899 if (defaultIconRadioButton.isChecked()) {
900 // Get the default folder icon drawable.
901 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
903 // Convert the folder icon drawable to a bitmap drawable.
904 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
906 // Convert the folder icon bitmap drawable to a bitmap.
907 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
908 } else { // Use the `WebView` favorite icon.
909 // Get a copy of the favorite icon bitmap.
910 folderIconBitmap = favoriteIconBitmap;
913 // Create a folder icon byte array output stream.
914 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
916 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
917 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
919 // Convert the folder icon byte array stream to a byte array.
920 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
922 // Update the folder and the icon.
923 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt, newFolderIconByteArray);
926 // Update the list view.
927 updateBookmarksListView();
931 public void onDestroy() {
932 // Close the bookmarks cursor and database.
933 bookmarksCursor.close();
934 bookmarksDatabaseHelper.close();
936 // Run the default commands.