2 * Copyright © 2016-2019 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.content.Context;
24 import android.content.Intent;
25 import android.database.Cursor;
26 import android.database.MatrixCursor;
27 import android.database.MergeCursor;
28 import android.graphics.Bitmap;
29 import android.graphics.BitmapFactory;
30 import android.graphics.Typeface;
31 import android.graphics.drawable.BitmapDrawable;
32 import android.graphics.drawable.Drawable;
33 import android.os.Bundle;
34 import android.util.SparseBooleanArray;
35 import android.view.ActionMode;
36 import android.view.Menu;
37 import android.view.MenuItem;
38 import android.view.View;
39 import android.view.ViewGroup;
40 import android.view.WindowManager;
41 import android.widget.AbsListView;
42 import android.widget.AdapterView;
43 import android.widget.EditText;
44 import android.widget.ImageView;
45 import android.widget.ListView;
46 import android.widget.RadioButton;
47 import android.widget.ResourceCursorAdapter;
48 import android.widget.Spinner;
49 import android.widget.TextView;
51 import androidx.appcompat.app.ActionBar;
52 import androidx.appcompat.app.AppCompatActivity;
53 import androidx.appcompat.widget.Toolbar; // The AndroidX toolbar must be used until the minimum API is >= 21.
54 import androidx.core.content.ContextCompat;
55 import androidx.cursoradapter.widget.CursorAdapter;
56 import androidx.fragment.app.DialogFragment; // The AndroidX dialog fragment must be used or an error is produced on API <=22.
58 import com.google.android.material.snackbar.Snackbar;
60 import com.stoutner.privacybrowser.R;
61 import com.stoutner.privacybrowser.dialogs.EditBookmarkDatabaseViewDialog;
62 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDatabaseViewDialog;
63 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
65 import java.io.ByteArrayOutputStream;
66 import java.util.Arrays;
68 public class BookmarksDatabaseViewActivity extends AppCompatActivity implements EditBookmarkDatabaseViewDialog.EditBookmarkDatabaseViewListener,
69 EditBookmarkFolderDatabaseViewDialog.EditBookmarkFolderDatabaseViewListener {
70 // Instantiate the constants.
71 private static final int ALL_FOLDERS_DATABASE_ID = -2;
72 private static final int HOME_FOLDER_DATABASE_ID = -1;
74 // `bookmarksDatabaseHelper` is used in `onCreate()`, `updateBookmarksListView()`, `selectAllBookmarksInFolder()`, and `onDestroy()`.
75 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
77 // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, `onSaveBookmark()`, `onSaveBookmarkFolder()`, and `onDestroy()`.
78 private Cursor bookmarksCursor;
80 // `bookmarksCursorAdapter` is used in `onCreate()`, `selectAllBookmarksInFolder()`, and `updateBookmarksListView()`.
81 private CursorAdapter bookmarksCursorAdapter;
83 // `oldFolderNameString` is used in `onCreate()` and `onSaveBookmarkFolder()`.
84 private String oldFolderNameString;
86 // `currentFolderDatabaseId` is used in `onCreate()`, `updateBookmarksListView()`, `onSaveBookmark()`, and `onSaveBookmarkFolder()`.
87 private int currentFolderDatabaseId;
89 // `currentFolder` is used in `onCreate()`, `onSaveBookmark()`, and `onSaveBookmarkFolder()`.
90 private String currentFolderName;
92 // `sortByDisplayOrder` is used in `onCreate()`, `onOptionsItemSelected()`, and `updateBookmarksListView()`.
93 private boolean sortByDisplayOrder;
95 // `bookmarksDeletedSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
96 private Snackbar bookmarksDeletedSnackbar;
98 // `closeActivityAfterDismissingSnackbar` is used in `onCreate()`, `onOptionsItemSelected()`, and `onBackPressed()`.
99 private boolean closeActivityAfterDismissingSnackbar;
102 public void onCreate(Bundle savedInstanceState) {
103 // Disable screenshots if not allowed.
104 if (!MainWebViewActivity.allowScreenshots) {
105 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
108 // Set the activity theme.
109 if (MainWebViewActivity.darkTheme) {
110 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
112 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
115 // Run the default commands.
116 super.onCreate(savedInstanceState);
118 // Get the intent that launched the activity.
119 Intent launchingIntent = getIntent();
121 // Get the favorite icon byte array.
122 byte[] favoriteIconByteArray = launchingIntent.getByteArrayExtra("favorite_icon_byte_array");
124 // Remove the incorrect lint warning below that the favorite icon byte array might be null.
125 assert favoriteIconByteArray != null;
127 // Convert the favorite icon byte array to a bitmap and store it in a class variable.
128 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
130 // Set the content view.
131 setContentView(R.layout.bookmarks_databaseview_coordinatorlayout);
133 // The AndroidX toolbar must be used until the minimum API is >= 21.
134 Toolbar toolbar = findViewById(R.id.bookmarks_databaseview_toolbar);
135 setSupportActionBar(toolbar);
137 // Get a handle for the action bar.
138 ActionBar actionBar = getSupportActionBar();
140 // Remove the incorrect lint warning that the action bar might be null.
141 assert actionBar != null;
143 // Display the spinner and the back arrow in the action bar.
144 actionBar.setCustomView(R.layout.spinner);
145 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
147 // Initialize the database handler. The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHelper`.
148 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
150 // Setup a matrix cursor for "All Folders" and "Home Folder".
151 String[] matrixCursorColumnNames = {BookmarksDatabaseHelper._ID, BookmarksDatabaseHelper.BOOKMARK_NAME};
152 MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
153 matrixCursor.addRow(new Object[]{ALL_FOLDERS_DATABASE_ID, getString(R.string.all_folders)});
154 matrixCursor.addRow(new Object[]{HOME_FOLDER_DATABASE_ID, getString(R.string.home_folder)});
156 // Get a cursor with the list of all the folders.
157 Cursor foldersCursor = bookmarksDatabaseHelper.getAllFolders();
159 // Combine `matrixCursor` and `foldersCursor`.
160 MergeCursor foldersMergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});
163 // Get the default folder bitmap. `ContextCompat` must be used until the minimum API >= 21.
164 Drawable defaultFolderDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_blue_bitmap);
166 // Cast the default folder drawable to a `BitmapDrawable`.
167 BitmapDrawable defaultFolderBitmapDrawable = (BitmapDrawable) defaultFolderDrawable;
169 // Remove the incorrect lint warning that `.getBitmap()` might be null.
170 assert defaultFolderBitmapDrawable != null;
172 // Convert the default folder `BitmapDrawable` to a bitmap.
173 Bitmap defaultFolderBitmap = defaultFolderBitmapDrawable.getBitmap();
176 // Create a resource cursor adapter for the spinner.
177 ResourceCursorAdapter foldersCursorAdapter = new ResourceCursorAdapter(this, R.layout.appbar_spinner_item, foldersMergeCursor, 0) {
179 public void bindView(View view, Context context, Cursor cursor) {
180 // Get handles for the spinner views.
181 ImageView spinnerItemImageView = view.findViewById(R.id.spinner_item_imageview);
182 TextView spinnerItemTextView = view.findViewById(R.id.spinner_item_textview);
184 // Set the folder icon according to the type.
185 if (foldersMergeCursor.getPosition() > 1) { // Set a user folder icon.
186 // Initialize a default folder icon byte array output stream.
187 ByteArrayOutputStream defaultFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
189 // 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).
190 defaultFolderBitmap.compress(Bitmap.CompressFormat.PNG, 0, defaultFolderIconByteArrayOutputStream);
192 // Convert the default folder icon output stream to a byte array.
193 byte[] defaultFolderIconByteArray = defaultFolderIconByteArrayOutputStream.toByteArray();
196 // Get the folder icon byte array from the cursor.
197 byte[] folderIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
199 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
200 Bitmap folderIconBitmap = BitmapFactory.decodeByteArray(folderIconByteArray, 0, folderIconByteArray.length);
203 // Set the icon according to the type.
204 if (Arrays.equals(folderIconByteArray, defaultFolderIconByteArray)) { // The default folder icon is used.
205 // Set a smaller and darker folder icon, which works well with the spinner.
206 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_dark_blue));
207 } else { // A custom folder icon is uses.
208 // Set the folder image stored in the cursor.
209 spinnerItemImageView.setImageBitmap(folderIconBitmap);
211 } else { // Set the `All Folders` or `Home Folder` icon.
212 // Set the gray folder image. `ContextCompat` must be used until the minimum API >= 21.
213 spinnerItemImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.folder_gray));
216 // Set the text view to display the folder name.
217 spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME)));
221 // Set the resource cursor adapter drop drown view resource.
222 foldersCursorAdapter.setDropDownViewResource(R.layout.appbar_spinner_dropdown_item);
224 // Get a handle for the folder spinner and set the adapter.
225 Spinner folderSpinner = findViewById(R.id.spinner);
226 folderSpinner.setAdapter(foldersCursorAdapter);
228 // Handle taps on the spinner dropdown.
229 folderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
231 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
232 // Store the current folder database ID.
233 currentFolderDatabaseId = (int) id;
235 // Get a handle for the selected view.
236 TextView selectedFolderTextView = findViewById(R.id.spinner_item_textview);
238 // Store the current folder name.
239 currentFolderName = selectedFolderTextView.getText().toString();
241 // Update the list view.
242 updateBookmarksListView();
246 public void onNothingSelected(AdapterView<?> parent) {
251 // Get a handle for the bookmarks `ListView`.
252 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
254 // Get a `Cursor` with the current contents of the bookmarks database.
255 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
257 // Setup a `CursorAdapter` with `this` context. `false` disables autoRequery.
258 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
260 public View newView(Context context, Cursor cursor, ViewGroup parent) {
261 // Inflate the individual item layout. `false` does not attach it to the root.
262 return getLayoutInflater().inflate(R.layout.bookmarks_databaseview_item_linearlayout, parent, false);
266 public void bindView(View view, Context context, Cursor cursor) {
267 boolean isFolder = (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
269 // Get the database ID from the `Cursor` and display it in `bookmarkDatabaseIdTextView`.
270 int bookmarkDatabaseId = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper._ID));
271 TextView bookmarkDatabaseIdTextView = view.findViewById(R.id.bookmarks_databaseview_database_id);
272 bookmarkDatabaseIdTextView.setText(String.valueOf(bookmarkDatabaseId));
274 // Get the favorite icon byte array from the `Cursor`.
275 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
276 // Convert the byte array to a `Bitmap` beginning at the beginning at the first byte and ending at the last.
277 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
278 // Display the bitmap in `bookmarkFavoriteIcon`.
279 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmarks_databaseview_favorite_icon);
280 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
282 // Get the bookmark name from the `Cursor` and display it in `bookmarkNameTextView`.
283 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
284 TextView bookmarkNameTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_name);
285 bookmarkNameTextView.setText(bookmarkNameString);
287 // Make the font bold for folders.
289 // The first argument is `null` prevent changing of the font.
290 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
291 } else { // Reset the font to default.
292 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
295 // Get the bookmark URL form the `Cursor` and display it in `bookmarkUrlTextView`.
296 String bookmarkUrlString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
297 TextView bookmarkUrlTextView = view.findViewById(R.id.bookmarks_databaseview_bookmark_url);
298 bookmarkUrlTextView.setText(bookmarkUrlString);
300 // Hide the URL if the bookmark is a folder.
302 bookmarkUrlTextView.setVisibility(View.GONE);
304 bookmarkUrlTextView.setVisibility(View.VISIBLE);
307 // Get the display order from the `Cursor` and display it in `bookmarkDisplayOrderTextView`.
308 int bookmarkDisplayOrder = cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER));
309 TextView bookmarkDisplayOrderTextView = view.findViewById(R.id.bookmarks_databaseview_display_order);
310 bookmarkDisplayOrderTextView.setText(String.valueOf(bookmarkDisplayOrder));
312 // Get the parent folder from the `Cursor` and display it in `bookmarkParentFolder`.
313 String bookmarkParentFolder = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.PARENT_FOLDER));
314 ImageView parentFolderImageView = view.findViewById(R.id.bookmarks_databaseview_parent_folder_icon);
315 TextView bookmarkParentFolderTextView = view.findViewById(R.id.bookmarks_databaseview_parent_folder);
317 // Make the folder name gray if it is the home folder.
318 if (bookmarkParentFolder.isEmpty()) {
319 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_gray));
320 bookmarkParentFolderTextView.setText(R.string.home_folder);
321 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_500));
323 parentFolderImageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.folder_dark_blue));
324 bookmarkParentFolderTextView.setText(bookmarkParentFolder);
326 // Set the text color according to the theme.
327 if (MainWebViewActivity.darkTheme) {
328 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray_300));
330 bookmarkParentFolderTextView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
336 // Update the ListView.
337 bookmarksListView.setAdapter(bookmarksCursorAdapter);
339 // Set the current folder database ID.
340 currentFolderDatabaseId = ALL_FOLDERS_DATABASE_ID;
342 // Set a listener to edit a bookmark when it is tapped.
343 bookmarksListView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
344 // Convert the database ID to an int.
345 int databaseId = (int) id;
347 // Show the edit bookmark or edit bookmark folder dialog.
348 if (bookmarksDatabaseHelper.isFolder(databaseId)) {
349 // Save the current folder name, which is used in `onSaveBookmarkFolder()`.
350 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
352 // Show the edit bookmark folder dialog.
353 DialogFragment editBookmarkFolderDatabaseViewDialog = EditBookmarkFolderDatabaseViewDialog.folderDatabaseId(databaseId, favoriteIconBitmap);
354 editBookmarkFolderDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
356 // Show the edit bookmark dialog.
357 DialogFragment editBookmarkDatabaseViewDialog = EditBookmarkDatabaseViewDialog.bookmarkDatabaseId(databaseId, favoriteIconBitmap);
358 editBookmarkDatabaseViewDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
362 // Handle long presses on the list view.
363 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
364 // Instantiate the common variables.
365 MenuItem selectAllMenuItem;
366 MenuItem deleteMenuItem;
367 boolean deletingBookmarks;
370 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
371 // Inflate the menu for the contextual app bar.
372 getMenuInflater().inflate(R.menu.bookmarks_databaseview_context_menu, menu);
375 mode.setTitle(R.string.bookmarks);
377 // Get handles for the menu items.
378 selectAllMenuItem = menu.findItem(R.id.select_all);
379 deleteMenuItem = menu.findItem(R.id.delete);
381 // Disable the delete menu item if a delete is pending.
382 deleteMenuItem.setEnabled(!deletingBookmarks);
389 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
395 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
396 // Calculate the number of selected bookmarks.
397 int numberOfSelectedBookmarks = bookmarksListView.getCheckedItemCount();
399 // Adjust the ActionMode according to the number of selected bookmarks.
400 mode.setSubtitle(getString(R.string.selected) + " " + numberOfSelectedBookmarks);
402 // Do not show the select all menu item if all the bookmarks are already checked.
403 if (bookmarksListView.getCheckedItemCount() == bookmarksListView.getCount()) {
404 selectAllMenuItem.setVisible(false);
406 selectAllMenuItem.setVisible(true);
409 // Convert the database ID to an int.
410 int databaseId = (int) id;
412 // If a folder was selected, also select all the contents.
413 if (checked && bookmarksDatabaseHelper.isFolder(databaseId)) {
414 selectAllBookmarksInFolder(databaseId);
417 // Do not allow a bookmark to be deselected if the folder is selected.
419 // Get the folder name.
420 String folderName = bookmarksDatabaseHelper.getParentFolderName((int) id);
422 // If the bookmark is not in the root folder, check to see if the folder is selected.
423 if (!folderName.isEmpty()) {
424 // Get the database ID of the folder.
425 int folderDatabaseId = bookmarksDatabaseHelper.getFolderDatabaseId(folderName);
427 // Move the bookmarks cursor to the first position.
428 bookmarksCursor.moveToFirst();
430 // Initialize the folder position variable.
431 int folderPosition = -1;
433 // Get the position of the folder in the bookmarks cursor.
434 while ((folderPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
435 // Check if the folder database ID matches the bookmark database ID.
436 if (folderDatabaseId == bookmarksCursor.getInt((bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID)))) {
437 // Get the folder position.
438 folderPosition = bookmarksCursor.getPosition();
440 // Check if the folder is selected.
441 if (bookmarksListView.isItemChecked(folderPosition)) {
442 // Reselect the bookmark.
443 bookmarksListView.setItemChecked(position, true);
445 // Display a snackbar explaining why the bookmark cannot be deselected.
446 Snackbar.make(bookmarksListView, R.string.cannot_deselect_bookmark, Snackbar.LENGTH_LONG).show();
450 // Increment the bookmarks cursor.
451 bookmarksCursor.moveToNext();
458 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
459 switch (item.getItemId()) {
460 case R.id.select_all:
461 // Get the total number of bookmarks.
462 int numberOfBookmarks = bookmarksListView.getCount();
465 for (int i = 0; i < numberOfBookmarks; i++) {
466 bookmarksListView.setItemChecked(i, true);
471 // Set the deleting bookmarks flag, which prevents the delete menu item from being enabled until the current process finishes.
472 deletingBookmarks = true;
474 // Get an array of the selected row IDs.
475 long[] selectedBookmarksIdsLongArray = bookmarksListView.getCheckedItemIds();
477 // 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.
478 SparseBooleanArray selectedBookmarksPositionsSparseBooleanArray = bookmarksListView.getCheckedItemPositions().clone();
480 // Update the bookmarks cursor with the current contents of the bookmarks database except for the specified database IDs.
481 switch (currentFolderDatabaseId) {
482 // Get a cursor with all the folders.
483 case ALL_FOLDERS_DATABASE_ID:
484 if (sortByDisplayOrder) {
485 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray);
487 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksExcept(selectedBookmarksIdsLongArray);
491 // Get a cursor for the home folder.
492 case HOME_FOLDER_DATABASE_ID:
493 if (sortByDisplayOrder) {
494 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, "");
496 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, "");
500 // Display the selected folder.
502 // Get a cursor for the selected folder.
503 if (sortByDisplayOrder) {
504 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrderExcept(selectedBookmarksIdsLongArray, currentFolderName);
506 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksExcept(selectedBookmarksIdsLongArray, currentFolderName);
510 // Update the list view.
511 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
513 // Show a Snackbar with the number of deleted bookmarks.
514 bookmarksDeletedSnackbar = Snackbar.make(findViewById(R.id.bookmarks_databaseview_coordinatorlayout),
515 getString(R.string.bookmarks_deleted) + " " + selectedBookmarksIdsLongArray.length, Snackbar.LENGTH_LONG)
516 .setAction(R.string.undo, view -> {
517 // Do nothing because everything will be handled by `onDismissed()` below.
519 .addCallback(new Snackbar.Callback() {
520 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
522 public void onDismissed(Snackbar snackbar, int event) {
524 // The user pushed the `Undo` button.
525 case Snackbar.Callback.DISMISS_EVENT_ACTION:
526 // Update the bookmarks list view with the current contents of the bookmarks database, including the "deleted bookmarks.
527 updateBookmarksListView();
529 // Re-select the previously selected bookmarks.
530 for (int i = 0; i < selectedBookmarksPositionsSparseBooleanArray.size(); i++) {
531 bookmarksListView.setItemChecked(selectedBookmarksPositionsSparseBooleanArray.keyAt(i), true);
535 // The Snackbar was dismissed without the `Undo` button being pushed.
537 // Delete each selected bookmark.
538 for (long databaseIdLong : selectedBookmarksIdsLongArray) {
539 // Convert `databaseIdLong` to an int.
540 int databaseIdInt = (int) databaseIdLong;
542 // Delete the selected bookmark.
543 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
547 // Reset the deleting bookmarks flag.
548 deletingBookmarks = false;
550 // Enable the delete menu item.
551 deleteMenuItem.setEnabled(true);
553 // Close the activity if back has been pressed.
554 if (closeActivityAfterDismissingSnackbar) {
560 // Show the Snackbar.
561 bookmarksDeletedSnackbar.show();
565 // Consume the click.
570 public void onDestroyActionMode(ActionMode mode) {
577 public boolean onCreateOptionsMenu(Menu menu) {
579 getMenuInflater().inflate(R.menu.bookmarks_databaseview_options_menu, menu);
586 public boolean onOptionsItemSelected(MenuItem menuItem) {
587 // Get the ID of the menu item that was selected.
588 int menuItemId = menuItem.getItemId();
590 switch (menuItemId) {
591 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
592 // Exit the activity.
596 case R.id.options_menu_sort:
597 // Update the sort by display order tracker.
598 sortByDisplayOrder = !sortByDisplayOrder;
600 // Get a handle for the bookmarks `ListView`.
601 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
603 // Update the icon and display a snackbar.
604 if (sortByDisplayOrder) { // Sort by display order.
605 // Update the icon according to the theme.
606 if (MainWebViewActivity.darkTheme) {
607 menuItem.setIcon(R.drawable.sort_selected_dark);
609 menuItem.setIcon(R.drawable.sort_selected_light);
612 // Display a Snackbar indicating the current sort type.
613 Snackbar.make(bookmarksListView, R.string.sorted_by_display_order, Snackbar.LENGTH_SHORT).show();
614 } else { // Sort by database id.
615 // Update the icon according to the theme.
616 if (MainWebViewActivity.darkTheme) {
617 menuItem.setIcon(R.drawable.sort_dark);
619 menuItem.setIcon(R.drawable.sort_light);
622 // Display a Snackbar indicating the current sort type.
623 Snackbar.make(bookmarksListView, R.string.sorted_by_database_id, Snackbar.LENGTH_SHORT).show();
626 // Update the list view.
627 updateBookmarksListView();
634 public void onBackPressed() {
635 // 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.
636 if ((bookmarksDeletedSnackbar != null) && bookmarksDeletedSnackbar.isShown()) { // Close the bookmarks deleted snackbar before going home.
637 // Set the close flag.
638 closeActivityAfterDismissingSnackbar = true;
640 // Dismiss the snackbar.
641 bookmarksDeletedSnackbar.dismiss();
642 } else { // Go home immediately.
643 // Update the current folder in the bookmarks activity.
644 switch (currentFolderDatabaseId) {
645 case ALL_FOLDERS_DATABASE_ID:
646 // Load the home folder.
647 BookmarksActivity.currentFolder = "";
650 case HOME_FOLDER_DATABASE_ID:
651 // Load the home folder.
652 BookmarksActivity.currentFolder = "";
656 // Load the current folder.
657 BookmarksActivity.currentFolder = currentFolderName;
660 // Reload the bookmarks list view when returning to the bookmarks activity.
661 BookmarksActivity.restartFromBookmarksDatabaseViewActivity = true;
663 // Exit the bookmarks database view activity.
664 super.onBackPressed();
668 private void updateBookmarksListView() {
669 // Populate the bookmarks list view based on the spinner selection.
670 switch (currentFolderDatabaseId) {
671 // Get a cursor with all the folders.
672 case ALL_FOLDERS_DATABASE_ID:
673 if (sortByDisplayOrder) {
674 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksByDisplayOrder();
676 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarks();
680 // Get a cursor for the home folder.
681 case HOME_FOLDER_DATABASE_ID:
682 if (sortByDisplayOrder) {
683 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder("");
685 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks("");
689 // Display the selected folder.
691 // Get a cursor for the selected folder.
692 if (sortByDisplayOrder) {
693 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentFolderName);
695 bookmarksCursor = bookmarksDatabaseHelper.getBookmarks(currentFolderName);
699 // Update the list view.
700 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
703 private void selectAllBookmarksInFolder(int folderId) {
704 // Get a handle for the bookmarks list view.
705 ListView bookmarksListView = findViewById(R.id.bookmarks_databaseview_listview);
707 // Get the folder name.
708 String folderName = bookmarksDatabaseHelper.getFolderName(folderId);
710 // Get a cursor with the contents of the folder.
711 Cursor folderCursor = bookmarksDatabaseHelper.getBookmarks(folderName);
713 // Move to the beginning of the cursor.
714 folderCursor.moveToFirst();
716 while (folderCursor.getPosition() < folderCursor.getCount()) {
717 // Get the bookmark database ID.
718 int bookmarkId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
720 // Move the bookmarks cursor to the first position.
721 bookmarksCursor.moveToFirst();
723 // Initialize the bookmark position variable.
724 int bookmarkPosition = -1;
726 // Get the position of this bookmark in the bookmarks cursor.
727 while ((bookmarkPosition < 0) && (bookmarksCursor.getPosition() < bookmarksCursor.getCount())) {
728 // Check if the bookmark IDs match.
729 if (bookmarkId == bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper._ID))) {
730 // Get the bookmark position.
731 bookmarkPosition = bookmarksCursor.getPosition();
733 // If this bookmark is a folder, select all the bookmarks inside it.
734 if (bookmarksDatabaseHelper.isFolder(bookmarkId)) {
735 selectAllBookmarksInFolder(bookmarkId);
738 // Select the bookmark.
739 bookmarksListView.setItemChecked(bookmarkPosition, true);
742 // Increment the bookmarks cursor position.
743 bookmarksCursor.moveToNext();
746 // Move to the next position.
747 folderCursor.moveToNext();
752 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
753 // Get handles for the views from dialog fragment.
754 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
755 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
756 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
757 Spinner folderSpinner = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_folder_spinner);
758 EditText displayOrderEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_display_order_edittext);
760 // Extract the bookmark information.
761 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
762 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
763 int folderDatabaseId = (int) folderSpinner.getSelectedItemId();
764 int displayOrderInt = Integer.valueOf(displayOrderEditText.getText().toString());
766 // Instantiate the parent folder name `String`.
767 String parentFolderNameString;
769 // Set the parent folder name.
770 if (folderDatabaseId == EditBookmarkDatabaseViewDialog.HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
771 parentFolderNameString = "";
772 } else { // Get the parent folder name from the database.
773 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(folderDatabaseId);
776 // Update the bookmark.
777 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
778 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt);
779 } else { // Update the bookmark using the `WebView` favorite icon.
780 // Create a favorite icon byte array output stream.
781 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
783 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
784 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
786 // Convert the favorite icon byte array stream to a byte array.
787 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
789 // Update the bookmark and the favorite icon.
790 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, parentFolderNameString, displayOrderInt, newFavoriteIconByteArray);
793 // Update the list view.
794 updateBookmarksListView();
798 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
799 // Get handles for the views from dialog fragment.
800 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
801 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
802 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
803 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
804 Spinner parentFolderSpinner = dialogFragment.getDialog().findViewById(R.id.edit_folder_parent_folder_spinner);
805 EditText displayOrderEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_display_order_edittext);
807 // Extract the folder information.
808 String newFolderNameString = editBookmarkNameEditText.getText().toString();
809 int parentFolderDatabaseId = (int) parentFolderSpinner.getSelectedItemId();
810 int displayOrderInt = Integer.valueOf(displayOrderEditText.getText().toString());
812 // Instantiate the parent folder name `String`.
813 String parentFolderNameString;
815 // Set the parent folder name.
816 if (parentFolderDatabaseId == EditBookmarkFolderDatabaseViewDialog.HOME_FOLDER_DATABASE_ID) { // The home folder is selected. Use `""`.
817 parentFolderNameString = "";
818 } else { // Get the parent folder name from the database.
819 parentFolderNameString = bookmarksDatabaseHelper.getFolderName(parentFolderDatabaseId);
822 // Update the folder.
823 if (currentBookmarkIconRadioButton.isChecked()) { // Update the folder without changing the favorite icon.
824 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt);
825 } else { // Update the folder and the icon.
826 // Create the new folder icon Bitmap.
827 Bitmap folderIconBitmap;
829 // Populate the new folder icon bitmap.
830 if (defaultFolderIconRadioButton.isChecked()) {
831 // Get the default folder icon drawable.
832 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
834 // Convert the folder icon drawable to a bitmap drawable.
835 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
837 // Convert the folder icon bitmap drawable to a bitmap.
838 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
839 } else { // Use the `WebView` favorite icon.
840 // Get a copy of the favorite icon bitmap.
841 folderIconBitmap = favoriteIconBitmap;
844 // Create a folder icon byte array output stream.
845 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
847 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
848 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
850 // Convert the folder icon byte array stream to a byte array.
851 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
853 // Update the folder and the icon.
854 bookmarksDatabaseHelper.updateFolder(selectedBookmarkDatabaseId, oldFolderNameString, newFolderNameString, parentFolderNameString, displayOrderInt, newFolderIconByteArray);
857 // Update the list view.
858 updateBookmarksListView();
862 public void onDestroy() {
863 // Close the bookmarks cursor and database.
864 bookmarksCursor.close();
865 bookmarksDatabaseHelper.close();
867 // Run the default commands.