2 * Copyright 2016-2022 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
6 * Privacy Browser Android is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser Android is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
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.activity.OnBackPressedCallback;
57 import androidx.annotation.NonNull;
58 import androidx.appcompat.app.ActionBar;
59 import androidx.appcompat.app.AppCompatActivity;
60 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
61 import androidx.core.content.ContextCompat;
62 import androidx.cursoradapter.widget.CursorAdapter;
63 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
65 import com.google.android.material.snackbar.Snackbar;
67 import com.stoutner.privacybrowser.R;
68 import com.stoutner.privacybrowser.dialogs.EditBookmarkDatabaseViewDialog;
69 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDatabaseViewDialog;
70 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
72 import java.io.ByteArrayOutputStream;
73 import java.util.Arrays;
75 public class BookmarksDatabaseViewActivity extends AppCompatActivity implements EditBookmarkDatabaseViewDialog.EditBookmarkDatabaseViewListener,
76 EditBookmarkFolderDatabaseViewDialog.EditBookmarkFolderDatabaseViewListener {
77 // Define the class constants.
78 private static final int ALL_FOLDERS_DATABASE_ID = -2;
79 public static final int HOME_FOLDER_DATABASE_ID = -1;
81 // Define the saved instance state constants.
82 private final String CURRENT_FOLDER_DATABASE_ID = "current_folder_database_id";
83 private final String CURRENT_FOLDER_NAME = "current_folder_name";
84 private final String SORT_BY_DISPLAY_ORDER = "sort_by_display_order";
86 // Define the class variables.
87 private int currentFolderDatabaseId;
88 private String currentFolderName;
89 private boolean sortByDisplayOrder;
90 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
91 private Cursor bookmarksCursor;
92 private CursorAdapter bookmarksCursorAdapter;
93 private String oldFolderNameString;
94 private Snackbar bookmarksDeletedSnackbar;
95 private boolean closeActivityAfterDismissingSnackbar;
98 public void onCreate(Bundle savedInstanceState) {
99 // Get a handle for the shared preferences.
100 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
102 // Get the preferences.
103 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
104 boolean bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
106 // Disable screenshots if not allowed.
107 if (!allowScreenshots) {
108 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
111 // Run the default commands.
112 super.onCreate(savedInstanceState);
114 // Get the intent that launched the activity.
115 Intent launchingIntent = getIntent();
117 // Get the favorite icon byte array.
118 byte[] favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
120 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
121 assert favoriteIconByteArray != null;
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);
126 // Set the view according to the theme.
128 // Set the content view.
129 setContentView(R.layout.bookmarks_databaseview_bottom_appbar);
131 // `Window.FEATURE_ACTION_MODE_OVERLAY` makes the contextual action mode cover the support action bar. It must be requested before the content is set.
132 supportRequestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
134 // Set the content view.
135 setContentView(R.layout.bookmarks_databaseview_top_appbar);
138 // Get a handle for the toolbar.
139 Toolbar toolbar = findViewById(R.id.bookmarks_databaseview_toolbar);
141 // Set the support action bar.
142 setSupportActionBar(toolbar);
144 // Get a handle for the action bar.
145 ActionBar actionBar = getSupportActionBar();
147 // Remove the incorrect lint warning that the action bar might be null.
148 assert actionBar != null;
150 // Display the spinner and the back arrow in the action bar.
151 actionBar.setCustomView(R.layout.spinner);
152 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
154 // Control what the system back command does.
155 OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
157 public void handleOnBackPressed() {
158 // Prepare to finish the activity.
163 // Register the on back pressed callback.
164 getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
166 // Initialize the database handler.
167 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
169 // Setup a matrix cursor for "All Folders" and "Home Folder".
170 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper.ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
171 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
172 matrixCursor.addRow(new Object[]{ALL_FOLDERS_DATABASE_ID, getString(R.string.all_folders)});
173 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
175 // Get a cursor with the list of all the folders.
176 Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
178 // Combine the matrix cursor and the folders cursor.
179 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
182 // Get the default folder bitmap. `ContextCompat` must be used until the minimum API >= 21.
183 Drawable defaultFolderDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_blue_bitmap);
185 // Cast the default folder drawable to a bitmap drawable.
186 BitmapDrawable defaultFolderBitmapDrawable = (BitmapDrawable) defaultFolderDrawable;
188 // Remove the incorrect lint warning that `.getBitmap()` might be null.
189 assert defaultFolderBitmapDrawable != null;
191 // Convert the default folder bitmap drawable to a bitmap.
192 Bitmap defaultFolderBitmap = defaultFolderBitmapDrawable.getBitmap();
195 // Create a resource cursor adapter for the spinner.
196 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(this, R.layout.appbar_spinner_item, foldersMergeCursor, 0) {
198 public void bindView(View view, Context context, Cursor cursor) {
199 // Get handles for the spinner views.
200 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
201 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
203 // Set the folder icon according to the type.
204 if (foldersMergeCursor.getPosition() > 1) { // Set a user folder icon.
205 // Initialize a default folder icon byte array output stream.
206 ByteArrayOutputStream defaultFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
208 // 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).
209 defaultFolderBitmap.compress(Bitmap.CompressFormat.PNG, 0, defaultFolderIconByteArrayOutputStream);
211 // Convert the default folder icon output stream to a byte array.
212 byte[] defaultFolderIconByteArray = defaultFolderIconByteArrayOutputStream.toByteArray();
215 // Get the folder icon byte array from the cursor.
216 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
218 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
219 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
222 // Set the icon according to the type.
223 if (Arrays.equals(folderIconByteArray, defaultFolderIconByteArray)) { // The default folder icon is used.
224 // Set a smaller and darker folder icon, which works well with the spinner.
225 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_dark_blue));
226 } else { // A custom folder icon is uses.
227 // Set the folder image stored in the cursor.
228 spinnerItemImageView.setImageBitmap(folderIconBitmap);
230 } else { // Set the `All Folders` or `Home Folder` icon.
231 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
232 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
235 // Set the text view to display the folder name.
236 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME)));
240 // Set the resource cursor adapter drop drown view resource.
241 foldersCursorAdapter.setDropDownViewResource(R.layout.appbar_spinner_dropdown_item);
243 // Get a handle for the folder spinner and set the adapter.
244 Spinner folderSpinner = findViewById(R.id.spinner);
245 folderSpinner.setAdapter(foldersCursorAdapter);
247 // Wait to set the on item selected listener until the spinner has been inflated. Otherwise the activity will crash on restart.
248 folderSpinner.post(() -> {
249 // Handle taps on the spinner dropdown.
250 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
252 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
253 // Store the current folder database ID.
254 currentFolderDatabaseId = (int) id;
256 // Get a handle for the selected view.
257 TextView selectedFolderTextView = findViewById(R.id.spinner_item_textview);
259 // Store the current folder name.
260 currentFolderName = selectedFolderTextView.getText().toString();
262 // Update the list view.
263 updateBookmarksListView();
267 public void onNothingSelected(AdapterView<?> parent) {
274 // Get a handle for the bookmarks listview.
275 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
277 // Check to see if the activity was restarted.
278 if (savedInstanceState == null) { // The activity was not restarted.
279 // Set the default current folder database ID.
280 currentFolderDatabaseId = ALL_FOLDERS_DATABASE_ID;
281 } else { // The activity was restarted.
282 // Restore the class variables from the saved instance state.
283 currentFolderDatabaseId = savedInstanceState.getInt(CURRENT_FOLDER_DATABASE_ID);
284 currentFolderName = savedInstanceState.getString(CURRENT_FOLDER_NAME);
285 sortByDisplayOrder = savedInstanceState.getBoolean(SORT_BY_DISPLAY_ORDER);
287 // Update the spinner if the home folder is selected. Android handles this by default for the main cursor but not the matrix cursor.
288 if (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) {
289 folderSpinner.setSelection(1);
293 // Update the bookmarks listview.
294 updateBookmarksListView();
296 // Setup a `CursorAdapter` with `this` context. `false` disables autoRequery.
297 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
299 public View newView(Context context, Cursor cursor, ViewGroup parent) {
300 // Inflate the individual item layout. `false` does not attach it to the root.
301 return getLayoutInflater().inflate(R.layout.bookmarks_databaseview_item_linearlayout, parent, false);
305 public void bindView(View view, Context context, Cursor cursor) {
306 boolean isFolder = (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
308 // Get the database ID from the `Cursor` and display it in `bookmarkDatabaseIdTextView`.
309 int bookmarkDatabaseId = cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID));
310 TextView bookmarkDatabaseIdTextView = view.findViewById(R.id.bookmarks_databaseview_database_id);
311 bookmarkDatabaseIdTextView.setText(String.valueOf(bookmarkDatabaseId));
313 // Get the favorite icon byte array from the `Cursor`.
314 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
315 // Convert the byte array to a `Bitmap` beginning at the beginning at the first byte and ending at the last.
316 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
317 // Display the bitmap in `bookmarkFavoriteIcon`.
318 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmarks_databaseview_favorite_icon);
319 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
321 // Get the bookmark name from the `Cursor` and display it in `bookmarkNameTextView`.
322 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
323 TextView bookmarkNameTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_name);
324 bookmarkNameTextView.setText(bookmarkNameString);
326 // Make the font bold for folders.
328 // The first argument is `null` prevent changing of the font.
329 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
330 } else { // Reset the font to default.
331 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
334 // Get the bookmark URL form the `Cursor` and display it in `bookmarkUrlTextView`.
335 String bookmarkUrlString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL));
336 TextView bookmarkUrlTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_url);
337 bookmarkUrlTextView.setText(bookmarkUrlString);
339 // Hide the URL if the bookmark is a folder.
341 bookmarkUrlTextView.setVisibility(View.GONE);
343 bookmarkUrlTextView.setVisibility(View.VISIBLE);
346 // Get the display order from the `Cursor` and display it in `bookmarkDisplayOrderTextView`.
347 int bookmarkDisplayOrder = cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.DISPLAY_ORDER));
348 TextView bookmarkDisplayOrderTextView = view.findViewById(R.id.bookmarks_databaseview_display_order);
349 bookmarkDisplayOrderTextView.setText(String.valueOf(bookmarkDisplayOrder));
351 // Get the parent folder from the `Cursor` and display it in `bookmarkParentFolder`.
352 String bookmarkParentFolder = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.PARENT_FOLDER));
353 ImageView parentFolderImageView = view.findViewById(R.id.bookmarks_databaseview_parent_folder_icon);
354 TextView bookmarkParentFolderTextView = view.findViewById(R.id.bookmarks_databaseview_parent_folder);
356 // Make the folder name gray if it is the home folder.
357 if (bookmarkParentFolder.isEmpty()) {
358 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_gray));
359 bookmarkParentFolderTextView.setText(R.string.home_folder);
360 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_500));
362 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_dark_blue));
363 bookmarkParentFolderTextView.setText(bookmarkParentFolder);
365 // Get the current theme status.
366 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
368 // Set the text color according to the theme.
369 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
370 // This color is a little darker than the default night mode text. But the effect is rather nice.
371 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_300));
373 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
379 // Update the ListView.
380 bookmarksListView.setAdapter(bookmarksCursorAdapter);
382 // Set a listener to edit a bookmark when it is tapped.
383 bookmarksListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
384 // Convert the database ID to an int.
385 int databaseId = (int) id;
387 // Show the edit bookmark or edit bookmark folder dialog.
388 if (bookmarksDatabaseHelper.isFolder(databaseId)) {
389 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
390 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
392 // Show the edit bookmark folder dialog.
393 DialogFragment editBookmarkFolderDatabaseViewDialog = EditBookmarkFolderDatabaseViewDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
394 editBookmarkFolderDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
396 // Show the edit bookmark dialog.
397 DialogFragment editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
398 editBookmarkDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
402 // Handle long presses on the list view.
403 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
404 // Instantiate the common variables.
405 MenuItem selectAllMenuItem;
406 MenuItem deleteMenuItem;
407 boolean deletingBookmarks;
410 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
411 // Inflate the menu for the contextual app bar.
412 getMenuInflater().inflate(R.menu.bookmarks_databaseview_context_menu, menu);
415 mode.setTitle(R.string.bookmarks);
417 // Get handles for the menu items.
418 selectAllMenuItem = menu.findItem(R.id.select_all);
419 deleteMenuItem = menu.findItem(R.id.delete);
421 // Disable the delete menu item if a delete is pending.
422 deleteMenuItem.setEnabled(!deletingBookmarks);
424 // Get the number of currently selected bookmarks.
425 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
427 // 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.
428 mode.setSubtitle(getString(R.string.selected) + " " + numberOfSelectedBookmarks);
430 // Do not show the select all menu item if all the bookmarks are already checked.
431 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
432 selectAllMenuItem.setVisible(false);
440 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
446 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
447 // Calculate the number of selected bookmarks.
448 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
450 // Only run the commands if at least one bookmark is selected. Otherwise, a context menu with 0 selected bookmarks is briefly displayed.
451 if (numberOfSelectedBookmarks > 0) {
452 // Update the action mode subtitle according to the number of selected bookmarks.
453 mode.setSubtitle(getString(R.string.selected) + " " + numberOfSelectedBookmarks);
455 // Only show the select all menu item if all of the bookmarks are not already selected.
456 selectAllMenuItem.setVisible(bookmarksListView.getCheckedItemCount() != bookmarksListView.getCount());
458 // Convert the database ID to an int.
459 int databaseId = (int) id;
461 // If a folder was selected, also select all the contents.
462 if (checked && bookmarksDatabaseHelper.isFolder(databaseId)) {
463 selectAllBookmarksInFolder(databaseId);
466 // Do not allow a bookmark to be deselected if the folder is selected.
468 // Get the folder name.
469 String folderName = bookmarksDatabaseHelper.getParentFolderName((int) id);
471 // If the bookmark is not in the root folder, check to see if the folder is selected.
472 if (!folderName.isEmpty()) {
473 // Get the database ID of the folder.
474 int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderName);
476 // Move the bookmarks cursor to the first position.
477 bookmarksCursor.moveToFirst();
479 // Initialize the folder position variable.
480 int folderPosition = -1;
482 // Get the position of the folder in the bookmarks cursor.
483 while ((folderPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
484 // Check if the folder database ID matches the bookmark database ID.
485 if (folderDatabaseId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID))) {
486 // Get the folder position.
487 folderPosition = bookmarksCursor.getPosition();
489 // Check if the folder is selected.
490 if (bookmarksListView.isItemChecked(folderPosition)) {
491 // Reselect the bookmark.
492 bookmarksListView.setItemChecked(position, true);
494 // Display a snackbar explaining why the bookmark cannot be deselected.
495 Snackbar.make(bookmarksListView, R.string.cannot_deselect_bookmark, Snackbar.LENGTH_LONG).show();
499 // Increment the bookmarks cursor.
500 bookmarksCursor.moveToNext();
508 public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
509 // Get a the menu item ID.
510 int menuItemId = menuItem.getItemId();
512 // Run the command that corresponds to the selected menu item.
513 if (menuItemId == R.id.select_all) { // Select all the bookmarks.
514 // Get the total number of bookmarks.
515 int numberOfBookmarks = bookmarksListView.getCount();
518 for (int i = 0; i < numberOfBookmarks; i++) {
519 bookmarksListView.setItemChecked(i, true);
521 } else if (menuItemId == R.id.delete) { // Delete the selected bookmarks.
522 // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
523 deletingBookmarks = true;
525 // Get an array of the selected row IDs.
526 long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
528 // 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.
529 SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
531 // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
532 switch (currentFolderDatabaseId) {
533 // Get a cursor with all the folders.
534 case ALL_FOLDERS_DATABASE_ID:
535 if (sortByDisplayOrder) {
536 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray);
538 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksExcept(selectedBookmarksIdsLongArray);
542 // Get a cursor for the home folder.
543 case HOME_FOLDER_DATABASE_ID:
544 if (sortByDisplayOrder) {
545 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, "");
547 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, "");
551 // Display the selected folder.
553 // Get a cursor for the selected folder.
554 if (sortByDisplayOrder) {
555 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolderName);
557 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, currentFolderName);
561 // Update the list view.
562 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
564 // Create a Snackbar with the number of deleted bookmarks.
565 bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout),
566 getString(R.string.bookmarks_deleted) + " " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG)
567 .setAction(R.string.undo, view -> {
568 // Do nothing because everything will be handled by `onDismissed()` below.
570 .addCallback(new Snackbar.Callback() {
571 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
573 public void onDismissed(Snackbar snackbar, int event) {
574 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) { // The user pushed the undo button.
575 // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks.
576 updateBookmarksListView();
578 // Re-select the previously selected bookmarks.
579 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
580 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
582 } else { // The Snackbar was dismissed without the undo button being pushed.
583 // Delete each selected bookmark.
584 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
585 // Convert `databaseIdLong` to an int.
586 int databaseIdInt = (int) databaseIdLong;
588 // Delete the selected bookmark.
589 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
593 // Reset the deleting bookmarks flag.
594 deletingBookmarks = false;
596 // Enable the delete menu item.
597 deleteMenuItem.setEnabled(true);
599 // Close the activity if back has been pressed.
600 if (closeActivityAfterDismissingSnackbar) {
606 // Show the Snackbar.
607 bookmarksDeletedSnackbar.show();
610 // Consume the click.
615 public void onDestroyActionMode(ActionMode mode) {
622 public boolean onCreateOptionsMenu(Menu menu) {
624 getMenuInflater().inflate(R.menu.bookmarks_databaseview_options_menu, menu);
626 // Get a handle for the sort menu item.
627 MenuItem sortMenuItem = menu.findItem(R.id.sort);
629 // Change the sort menu item icon if the listview is sorted by display order, which restores the state after a restart.
630 if (sortByDisplayOrder) {
631 sortMenuItem.setIcon(R.drawable.sort_selected);
639 public boolean onOptionsItemSelected(MenuItem menuItem) {
640 // Get the menu item ID.
641 int menuItemId = menuItem.getItemId();
643 // Run the command that corresponds to the selected menu item.
644 if (menuItemId == android.R.id.home) { // Go Home. The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
645 // Prepare to finish the activity.
647 } else if (menuItemId == R.id.sort) { // Toggle the sort mode.
648 // Update the sort by display order tracker.
649 sortByDisplayOrder = !sortByDisplayOrder;
651 // Get a handle for the bookmarks list view.
652 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
654 // Update the icon and display a snackbar.
655 if (sortByDisplayOrder) { // Sort by display order.
657 menuItem.setIcon(R.drawable.sort_selected);
659 // Display a Snackbar indicating the current sort type.
660 Snackbar.make(bookmarksListView, R.string.sorted_by_display_order, Snackbar.LENGTH_SHORT).show();
661 } else { // Sort by database id.
663 menuItem.setIcon(R.drawable.sort);
665 // Display a Snackbar indicating the current sort type.
666 Snackbar.make(bookmarksListView, R.string.sorted_by_database_id, Snackbar.LENGTH_SHORT).show();
669 // Update the list view.
670 updateBookmarksListView();
673 // Consume the event.
678 public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
679 // Run the default commands.
680 super.onSaveInstanceState(savedInstanceState);
682 // Store the class variables in the bundle.
683 savedInstanceState.putInt(CURRENT_FOLDER_DATABASE_ID, currentFolderDatabaseId);
684 savedInstanceState.putString(CURRENT_FOLDER_NAME, currentFolderName);
685 savedInstanceState.putBoolean(SORT_BY_DISPLAY_ORDER, sortByDisplayOrder);
688 private void prepareFinish() {
689 // 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.
690 if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks deleted snackbar before going home.
691 // Set the close flag.
692 closeActivityAfterDismissingSnackbar = true;
694 // Dismiss the snackbar.
695 bookmarksDeletedSnackbar.dismiss();
696 } else { // Go home immediately.
697 // Update the current folder in the bookmarks activity.
698 if ((currentFolderDatabaseId == ALL_FOLDERS_DATABASE_ID) || (currentFolderDatabaseId == HOME_FOLDER_DATABASE_ID)) { // All folders or the the home folder are currently displayed.
699 // Load the home folder.
700 BookmarksActivity.currentFolder = "";
701 } else { // A subfolder is currently displayed.
702 // Load the current folder.
703 BookmarksActivity.currentFolder = currentFolderName;
706 // Reload the bookmarks list view when returning to the bookmarks activity.
707 BookmarksActivity.restartFromBookmarksDatabaseViewActivity = true;
709 // Exit the bookmarks database view activity.
714 private void updateBookmarksListView() {
715 // Populate the bookmarks list view based on the spinner selection.
716 switch (currentFolderDatabaseId) {
717 // Get a cursor with all the folders.
718 case ALL_FOLDERS_DATABASE_ID:
719 if (sortByDisplayOrder) {
720 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrder();
722 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
726 // Get a cursor for the home folder.
727 case HOME_FOLDER_DATABASE_ID:
728 if (sortByDisplayOrder) {
729 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder("");
731 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks("");
735 // Display the selected folder.
737 // Get a cursor for the selected folder.
738 if (sortByDisplayOrder) {
739 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolderName);
741 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks(currentFolderName);
745 // Update the cursor adapter if it isn't null, which happens when the activity is restarted.
746 if (bookmarksCursorAdapter != null) {
747 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
751 private void selectAllBookmarksInFolder(int folderId) {
752 // Get a handle for the bookmarks list view.
753 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
755 // Get the folder name.
756 String folderName = bookmarksDatabaseHelper.getFolderName(folderId);
758 // Get a cursor with the contents of the folder.
759 Cursor folderCursor = bookmarksDatabaseHelper.getBookmarks(folderName);
761 // Move to the beginning of the cursor.
762 folderCursor.moveToFirst();
764 while (folderCursor.getPosition() < folderCursor.getCount()) {
765 // Get the bookmark database ID.
766 int bookmarkId = folderCursor.getInt(folderCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID));
768 // Move the bookmarks cursor to the first position.
769 bookmarksCursor.moveToFirst();
771 // Initialize the bookmark position variable.
772 int bookmarkPosition = -1;
774 // Get the position of this bookmark in the bookmarks cursor.
775 while ((bookmarkPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
776 // Check if the bookmark IDs match.
777 if (bookmarkId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.ID))) {
778 // Get the bookmark position.
779 bookmarkPosition = bookmarksCursor.getPosition();
781 // If this bookmark is a folder, select all the bookmarks inside it.
782 if (bookmarksDatabaseHelper.isFolder(bookmarkId)) {
783 selectAllBookmarksInFolder(bookmarkId);
786 // Select the bookmark.
787 bookmarksListView.setItemChecked(bookmarkPosition, true);
790 // Increment the bookmarks cursor position.
791 bookmarksCursor.moveToNext();
794 // Move to the next position.
795 folderCursor.moveToNext();
800 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
801 // Get the dialog from the dialog fragment.
802 Dialog dialog = dialogFragment.getDialog();
804 // Remove the incorrect lint warning below that the dialog might be null.
805 assert dialog != null;
807 // Get handles for the views from dialog fragment.
808 RadioButton currentIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
809 EditText bookmarkNameEditText = dialog.findViewById(R.id.bookmark_name_edittext);
810 EditText bookmarkUrlEditText = dialog.findViewById(R.id.bookmark_url_edittext);
811 Spinner folderSpinner = dialog.findViewById(R.id.bookmark_folder_spinner);
812 EditText displayOrderEditText = dialog.findViewById(R.id.bookmark_display_order_edittext);
814 // Extract the bookmark information.
815 String bookmarkNameString = bookmarkNameEditText.getText().toString();
816 String bookmarkUrlString = bookmarkUrlEditText.getText().toString();
817 int folderDatabaseId = (int) folderSpinner.getSelectedItemId();
818 int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
820 // Instantiate the parent folder name `String`.
821 String parentFolderNameString;
823 // Set the parent folder name.
824 if (folderDatabaseId == HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
825 parentFolderNameString = "";
826 } else { // Get the parent folder name from the database.
827 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(folderDatabaseId);
830 // Update the bookmark.
831 if (currentIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
832 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt);
833 } else { // Update the bookmark using the `WebView` favorite icon.
834 // Create a favorite icon byte array output stream.
835 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
837 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
838 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
840 // Convert the favorite icon byte array stream to a byte array.
841 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
843 // Update the bookmark and the favorite icon.
844 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt, newFavoriteIconByteArray);
847 // Update the list view.
848 updateBookmarksListView();
852 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
853 // Get the dialog from the dialog fragment.
854 Dialog dialog = dialogFragment.getDialog();
856 // Remove the incorrect lint warning below that the dialog might be null.
857 assert dialog != null;
859 // Get handles for the views from dialog fragment.
860 RadioButton currentIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
861 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
862 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
863 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
864 Spinner parentFolderSpinner = dialog.findViewById(R.id.parent_folder_spinner);
865 EditText displayOrderEditText = dialog.findViewById(R.id.display_order_edittext);
867 // Extract the folder information.
868 String newFolderNameString = folderNameEditText.getText().toString();
869 int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId();
870 int displayOrderInt = Integer.parseInt(displayOrderEditText.getText().toString());
872 // Instantiate the parent folder name `String`.
873 String parentFolderNameString;
875 // Set the parent folder name.
876 if (parentFolderDatabaseId == HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
877 parentFolderNameString = "";
878 } else { // Get the parent folder name from the database.
879 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(parentFolderDatabaseId);
882 // Update the folder.
883 if (currentIconRadioButton.isChecked()) { // Update the folder without changing the favorite icon.
884 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt);
885 } else { // Update the folder and the icon.
886 // Create the new folder icon Bitmap.
887 Bitmap folderIconBitmap;
889 // Populate the new folder icon bitmap.
890 if (defaultIconRadioButton.isChecked()) {
891 // Get the default folder icon drawable.
892 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
894 // Convert the folder icon drawable to a bitmap drawable.
895 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
897 // Convert the folder icon bitmap drawable to a bitmap.
898 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
899 } else { // Use the `WebView` favorite icon.
900 // Get a copy of the favorite icon bitmap.
901 folderIconBitmap = favoriteIconBitmap;
904 // Create a folder icon byte array output stream.
905 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
907 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
908 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
910 // Convert the folder icon byte array stream to a byte array.
911 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
913 // Update the folder and the icon.
914 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt, newFolderIconByteArray);
917 // Update the list view.
918 updateBookmarksListView();
922 public void onDestroy() {
923 // Close the bookmarks cursor and database.
924 bookmarksCursor.close();
925 bookmarksDatabaseHelper.close();
927 // Run the default commands.