Hide the move to folder menu item if no folders exist. https://redmine.stoutner...
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / BookmarksActivity.java
1 /*
2  * Copyright © 2016-2017 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.activities;
21
22 import android.app.Activity;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.database.Cursor;
26 import android.graphics.Bitmap;
27 import android.graphics.BitmapFactory;
28 import android.graphics.Typeface;
29 import android.graphics.drawable.BitmapDrawable;
30 import android.graphics.drawable.Drawable;
31 import android.os.Bundle;
32 import android.support.design.widget.FloatingActionButton;
33 import android.support.design.widget.Snackbar;
34 import android.support.v4.app.NavUtils;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.support.v7.widget.Toolbar;
39 import android.util.SparseBooleanArray;
40 import android.view.ActionMode;
41 import android.view.Menu;
42 import android.view.MenuItem;
43 import android.view.View;
44 import android.view.ViewGroup;
45 import android.widget.AbsListView;
46 import android.widget.AdapterView;
47 import android.widget.CursorAdapter;
48 import android.widget.EditText;
49 import android.widget.ImageView;
50 import android.widget.ListView;
51 import android.widget.RadioButton;
52 import android.widget.TextView;
53
54 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
55 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
56 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
57 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
58 import com.stoutner.privacybrowser.dialogs.MoveToFolderDialog;
59 import com.stoutner.privacybrowser.R;
60 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
61
62 import java.io.ByteArrayOutputStream;
63
64 public class BookmarksActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
65         MoveToFolderDialog.MoveToFolderListener {
66
67     // `bookmarksDatabaseHelper` is public static so it can be accessed from `EditBookmarkDialog` and `MoveToFolderDialog`.  It is also used in `onCreate()`,
68     // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
69     public static BookmarksDatabaseHelper bookmarksDatabaseHelper;
70
71     // `currentFolder` is public static so it can be accessed from `MoveToFolderDialog`.
72     // It is used in `onCreate`, `onOptionsItemSelected()`, `onCreateBookmarkCreate`, `onCreateBookmarkFolderCreate`, and `onEditBookmarkSave`.
73     public static String currentFolder;
74
75     // `checkedItemIds` is public static so it can be accessed from `EditBookmarkDialog`, `EditBookmarkFolderDialog`, and `MoveToFolderDialog`.
76     // It is also used in `onActionItemClicked`.
77     public static long[] checkedItemIds;
78
79
80     // `bookmarksListView` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
81     private ListView bookmarksListView;
82
83     // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
84     private ActionMode contextualActionMode;
85
86     // `selectedBookmarkPosition` is used in `onCreate()` and `onEditBookmarkSave()`.
87     private int selectedBookmarkPosition;
88
89     // `appBar` is used in `onCreate()` and `updateBookmarksListView()`.
90     private ActionBar appBar;
91
92     // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
93     private Cursor bookmarksCursor;
94
95     // `oldFolderName` is used in `onCreate()` and `onEditBookmarkFolderSave()`.
96     private String oldFolderNameString;
97
98     @Override
99     protected void onCreate(Bundle savedInstanceState) {
100         // Set the activity theme.
101         if (MainWebViewActivity.darkTheme) {
102             setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
103         } else {
104             setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
105         }
106
107         // Run the default commands.
108         super.onCreate(savedInstanceState);
109
110         // Set the content view.
111         setContentView(R.layout.bookmarks_coordinatorlayout);
112
113         // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
114         final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
115         setSupportActionBar(bookmarksAppBar);
116
117         // Display the home arrow on `SupportActionBar`.
118         appBar = getSupportActionBar();
119         assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
120         appBar.setDisplayHomeAsUpEnabled(true);
121
122
123         // Initialize the database handler and the `ListView`.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
124         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
125         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
126         bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
127
128         // Set currentFolder to the home folder, which is `""` in the database.
129         currentFolder = "";
130
131         // Display the bookmarks in the ListView.
132         updateBookmarksListView(currentFolder);
133
134         // Set a listener so that tapping a list item loads the URL.  We need to store the activity in a variable so that we can return to the parent activity after loading the URL.
135         final Activity bookmarksActivity = this;
136         bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
137             @Override
138             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
139                 // Convert the id from long to int to match the format of the bookmarks database.
140                 int databaseID = (int) id;
141
142                 // Get the bookmark `Cursor` for this ID and move it to the first row.
143                 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
144                 bookmarkCursor.moveToFirst();
145
146                 // If the bookmark is a folder load its contents into the ListView.
147                 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
148                     // Update `currentFolder`.
149                     currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
150
151                     // Reload the ListView with `currentFolder`.
152                     updateBookmarksListView(currentFolder);
153                 } else {  // Load the URL into `mainWebView`.
154                     // Get the bookmark URL and assign it to formattedUrlString.  `mainWebView` will automatically reload when `BookmarksActivity` closes.
155                     MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
156
157                     NavUtils.navigateUpFromSameTask(bookmarksActivity);
158                 }
159
160                 // Close the `Cursor`.
161                 bookmarkCursor.close();
162             }
163         });
164
165         // `MultiChoiceModeListener` handles long clicks.
166         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
167             // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
168             MenuItem moveBookmarkUpMenuItem;
169
170             // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
171             MenuItem moveBookmarkDownMenuItem;
172
173             // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
174             MenuItem editBookmarkMenuItem;
175
176             // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
177             MenuItem selectAllBookmarksMenuItem;
178
179             @Override
180             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
181                 // Inflate the menu for the contextual app bar and set the title.
182                 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
183
184                 // Set the title.
185                 if (currentFolder.isEmpty()) {
186                     // Use `R.string.bookmarks` if we are in the home folder.
187                     mode.setTitle(R.string.bookmarks);
188                 } else {  // Use the current folder name as the title.
189                     mode.setTitle(currentFolder);
190                 }
191
192                 // Get a handle for MenuItems we need to selectively disable.
193                 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
194                 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
195                 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
196                 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
197
198                 // Store `contextualActionMode` so we can close it programatically.
199                 contextualActionMode = mode;
200
201                 return true;
202             }
203
204             @Override
205             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
206                 // Get a handle for the move to folder menu item.
207                 MenuItem moveToFolderMenuItem = menu.findItem(R.id.move_to_folder);
208
209                 // Get a `Cursor` with all of the folders.
210                 Cursor folderCursor = bookmarksDatabaseHelper.getAllFoldersCursor();
211
212                 // Enable the move to folder menu item if at least one folder exists.
213                 moveToFolderMenuItem.setVisible(folderCursor.getCount() > 0);
214
215                 // `return true` indicates that the menu has been updated.
216                 return true;
217             }
218
219             @Override
220             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
221                 // Get an array of the selected bookmarks.
222                 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
223
224                 // Calculate the number of selected bookmarks.
225                 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
226
227                 // Adjust the `mode` and the menu for the number of selected bookmarks.
228                 if (numberOfSelectedBookmarks == 0) {
229                     mode.finish();
230                 } else if (numberOfSelectedBookmarks == 1) {
231                     // List the number of selected bookmarks in the subtitle.
232                     mode.setSubtitle(getString(R.string.one_selected));
233
234                     // Show the `Move Up`, `Move Down`, and  `Edit` options.
235                     moveBookmarkUpMenuItem.setVisible(true);
236                     moveBookmarkDownMenuItem.setVisible(true);
237                     editBookmarkMenuItem.setVisible(true);
238
239                     // Get the database IDs for the bookmarks.
240                     int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
241                     int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
242                     // bookmarksListView is 0 indexed.
243                     int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
244
245                     // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
246                     if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
247                         moveBookmarkUpMenuItem.setEnabled(false);
248                         moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
249                     } else {  // Otherwise enable `moveBookmarkUpMenuItem`.
250                         moveBookmarkUpMenuItem.setEnabled(true);
251
252                         // Set the icon according to the theme.
253                         if (MainWebViewActivity.darkTheme) {
254                             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
255                         } else {
256                             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
257                         }
258                     }
259
260                     // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
261                     if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
262                         moveBookmarkDownMenuItem.setEnabled(false);
263                         moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
264                     } else {  // Otherwise enable `moveBookmarkDownMenuItem`.
265                         moveBookmarkDownMenuItem.setEnabled(true);
266
267                         // Set the icon according to the theme.
268                         if (MainWebViewActivity.darkTheme) {
269                             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
270                         } else {
271                             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
272                         }
273                     }
274                 } else {  // More than one bookmark is selected.
275                     // List the number of selected bookmarks in the subtitle.
276                     mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
277
278                     // Hide non-applicable `MenuItems`.
279                     moveBookmarkUpMenuItem.setVisible(false);
280                     moveBookmarkDownMenuItem.setVisible(false);
281                     editBookmarkMenuItem.setVisible(false);
282                 }
283
284                 // Do not show `Select All` if all the bookmarks are already checked.
285                 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
286                     selectAllBookmarksMenuItem.setVisible(false);
287                 } else {
288                     selectAllBookmarksMenuItem.setVisible(true);
289                 }
290             }
291
292             @Override
293             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
294                 // Get the menu item ID.
295                 int menuItemId = item.getItemId();
296
297                 // Instantiate the common variables.
298                 int numberOfBookmarks;
299                 int selectedBookmarkNewPosition;
300                 SparseBooleanArray bookmarkPositionSparseBooleanArray;
301
302                 switch (menuItemId) {
303                     case R.id.move_bookmark_up:
304                         // Get the array of checked bookmarks.
305                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
306
307                         // Store the position of the selected bookmark.
308                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
309
310                         // Initialize `selectedBookmarkNewPosition`.
311                         selectedBookmarkNewPosition = 0;
312
313                         // Iterate through the bookmarks.
314                         for (int i = 0; i < bookmarksListView.getCount(); i++) {
315                             // Get the database ID for the current bookmark.
316                             int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
317
318                             // Update the display order for the current bookmark.
319                             if (i == selectedBookmarkPosition) {  // The current bookmark is the selected bookmark.
320                                 // Move the current bookmark up one.
321                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i - 1);
322                                 selectedBookmarkNewPosition = i - 1;
323                             } else if ((i + 1) == selectedBookmarkPosition){  // The current bookmark is immediately above the selected bookmark.
324                                 // Move the current bookmark down one.
325                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i + 1);
326                             } else {  // The current bookmark is not changing positions.
327                                 // Move `bookmarksCursor` to the current bookmark position.
328                                 bookmarksCursor.moveToPosition(i);
329
330                                 // Update the display order only if it is not correct in the database.
331                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
332                                     bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i);
333                                 }
334                             }
335                         }
336
337                         // Refresh the ListView.
338                         updateBookmarksListView(currentFolder);
339
340                         // Select the previously selected bookmark in the new location.
341                         bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
342
343                         // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
344                         bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
345
346                         break;
347
348                     case R.id.move_bookmark_down:
349                         // Get the array of checked bookmarks.
350                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
351
352                         // Store the position of the selected bookmark.
353                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
354
355                         // Initialize `selectedBookmarkNewPosition`.
356                         selectedBookmarkNewPosition = 0;
357
358                         // Iterate through the bookmarks.
359                         for (int i = 0; i <bookmarksListView.getCount(); i++) {
360                             // Get the database ID for the current bookmark.
361                             int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
362
363                             // Update the display order for the current bookmark.
364                             if (i == selectedBookmarkPosition) {  // The current bookmark is the selected bookmark.
365                                 // Move the current bookmark down one.
366                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i + 1);
367                                 selectedBookmarkNewPosition = i + 1;
368                             } else if ((i - 1) == selectedBookmarkPosition) {  // The current bookmark is immediately below the selected bookmark.
369                                 // Move the bookmark below the selected bookmark up one.
370                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i - 1);
371                             } else {  // The current bookmark is not changing positions.
372                                 // Move `bookmarksCursor` to the current bookmark position.
373                                 bookmarksCursor.moveToPosition(i);
374
375                                 // Update the display order only if it is not correct in the database.
376                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
377                                     bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i);
378                                 }
379                             }
380                         }
381
382                         // Refresh the ListView.
383                         updateBookmarksListView(currentFolder);
384
385                         // Select the previously selected bookmark in the new location.
386                         bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
387
388                         // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
389                         bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
390                         break;
391
392                     case R.id.move_to_folder:
393                         // Store `checkedItemIds` for use by the `AlertDialog`.
394                         checkedItemIds = bookmarksListView.getCheckedItemIds();
395
396                         // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
397                         AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
398                         moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
399                         break;
400
401                     case R.id.edit_bookmark:
402                         // Get the array of checked bookmarks.
403                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
404
405                         // Store the position of the selected bookmark.
406                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
407
408                         // Move to the selected database ID and find out if it is a folder.
409                         bookmarksCursor.moveToPosition(selectedBookmarkPosition);
410                         boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
411
412                         // Store `checkedItemIds` for use by the `AlertDialog`.
413                         checkedItemIds = bookmarksListView.getCheckedItemIds();
414
415                         if (isFolder) {
416                             // Save the current folder name.
417                             oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
418
419                             // Show the `EditBookmarkFolderDialog` `AlertDialog` and name the instance `@string/edit_folder`.
420                             AppCompatDialogFragment editFolderDialog = new EditBookmarkFolderDialog();
421                             editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
422                         } else {
423                             // Show the `EditBookmarkDialog` `AlertDialog` and name the instance `@string/edit_bookmark`.
424                             AppCompatDialogFragment editBookmarkDialog = new EditBookmarkDialog();
425                             editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
426                         }
427                         break;
428
429                     case R.id.delete_bookmark:
430                         // Get an array of the selected rows.
431                         final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
432
433                         // Get the array of checked bookmarks.
434                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
435
436                         // Store the position of the first selected bookmark.
437                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
438
439                         updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
440
441                         // Scroll to where the first deleted bookmark was located.
442                         bookmarksListView.setSelection(selectedBookmarkPosition - 5);
443
444                         // Create `snackbarMessage`.
445                         String snackbarMessage;
446
447                         // Determine how many items are in the array and prepare an appropriate Snackbar message.
448                         if (selectedBookmarksLongArray.length == 1) {
449                             snackbarMessage = getString(R.string.one_bookmark_deleted);
450                         } else {
451                             snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
452                         }
453
454                         // Show a SnackBar.
455                         Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
456                                 .setAction(R.string.undo, new View.OnClickListener() {
457                                     @Override
458                                     public void onClick(View view) {
459                                         // Do nothing because everything will be handled by `onDismissed()` below.
460                                     }
461                                 })
462                                 .addCallback(new Snackbar.Callback() {
463                                     @Override
464                                     public void onDismissed(Snackbar snackbar, int event) {
465                                         switch (event) {
466                                             // The user pushed the `Undo` button.
467                                             case Snackbar.Callback.DISMISS_EVENT_ACTION:
468                                                 // Refresh the ListView to show the rows again.
469                                                 updateBookmarksListView(currentFolder);
470
471                                                 // Scroll to where the first deleted bookmark was located.
472                                                 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
473                                                 break;
474
475                                             // The `Snackbar` was dismissed without the `Undo` button being pushed.
476                                             default:
477                                                 // Delete each selected row.
478                                                 for (long databaseIdLong : selectedBookmarksLongArray) {
479                                                     // Convert `databaseIdLong` to an int.
480                                                     int databaseIdInt = (int) databaseIdLong;
481
482                                                     if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
483                                                         deleteBookmarkFolderContents(databaseIdInt);
484                                                     }
485
486                                                     // Delete `databaseIdInt`.
487                                                     bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
488                                                 }
489
490                                                 // Update the display order.
491                                                 for (int i = 0; i < bookmarksListView.getCount(); i++) {
492                                                     // Get the database ID for the current bookmark.
493                                                     int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
494
495                                                     // Move `bookmarksCursor` to the current bookmark position.
496                                                     bookmarksCursor.moveToPosition(i);
497
498                                                     // Update the display order only if it is not correct in the database.
499                                                     if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
500                                                         bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i);
501                                                     }
502                                                 }
503                                                 break;
504                                         }
505                                     }
506                                 })
507                                 .show();
508
509                         // Close the contextual app bar.
510                         mode.finish();
511                         break;
512
513                     case R.id.context_menu_select_all_bookmarks:
514                         numberOfBookmarks = bookmarksListView.getCount();
515
516                         for (int i = 0; i < numberOfBookmarks; i++) {
517                             bookmarksListView.setItemChecked(i, true);
518                         }
519                         break;
520                 }
521                 // Consume the click.
522                 return true;
523             }
524
525             @Override
526             public void onDestroyActionMode(ActionMode mode) {
527
528             }
529         });
530
531         // Set a FloatingActionButton for creating new bookmarks.
532         FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
533         createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
534             @Override
535             public void onClick(View view) {
536                 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
537                 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
538                 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
539             }
540         });
541     }
542
543     @Override
544     public boolean onCreateOptionsMenu(Menu menu) {
545         // Inflate the menu.
546         getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
547
548         // Success.
549         return true;
550     }
551
552     @Override
553     public boolean onOptionsItemSelected(MenuItem menuItem) {
554         // Get the ID of the `MenuItem` that was selected.
555         int menuItemId = menuItem.getItemId();
556
557         switch (menuItemId) {
558             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
559                 if (currentFolder.isEmpty()) {  // Exit BookmarksActivity if currently in the home folder.
560                     NavUtils.navigateUpFromSameTask(this);
561                 } else {  // Navigate up one folder.
562                     // Place the former parent folder in `currentFolder`.
563                     currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
564
565                     // Update `bookmarksListView`.
566                     updateBookmarksListView(currentFolder);
567                 }
568                 break;
569
570             case R.id.create_folder:
571                 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
572                 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
573                 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
574                 break;
575
576             case R.id.options_menu_select_all_bookmarks:
577                 int numberOfBookmarks = bookmarksListView.getCount();
578
579                 for (int i = 0; i < numberOfBookmarks; i++) {
580                     bookmarksListView.setItemChecked(i, true);
581                 }
582                 break;
583
584             case R.id.bookmarks_database_view:
585                 // Launch `BookmarksDatabaseViewActivity`.
586                 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
587                 startActivity(bookmarksDatabaseViewIntent);
588                 break;
589         }
590         return true;
591     }
592
593     @Override
594     public void onBackPressed() {
595         if (currentFolder.isEmpty()) {  // Exit BookmarksActivity if currently in the home folder.
596             super.onBackPressed();
597         } else {  // Navigate up one folder.
598             // Place the former parent folder in `currentFolder`.
599             currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
600
601             // Reload the `ListView`.
602             updateBookmarksListView(currentFolder);
603         }
604     }
605
606     @Override
607     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
608         // Get the `EditTexts` from the `dialogFragment`.
609         EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
610         EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
611
612         // Extract the strings from the `EditTexts`.
613         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
614         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
615
616         // Convert the favoriteIcon Bitmap to a byte array.
617         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
618         // `0` is for lossless compression (the only option for a PNG).
619         MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
620         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
621
622         // Display the new bookmark below the current items in the (0 indexed) list.
623         int newBookmarkDisplayOrder = bookmarksListView.getCount();
624
625         // Create the bookmark.
626         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
627
628         // Refresh the `ListView`.  `setSelection` scrolls to the bottom of the list.
629         updateBookmarksListView(currentFolder);
630         bookmarksListView.setSelection(newBookmarkDisplayOrder);
631     }
632
633     @Override
634     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
635         // Get `create_folder_name_edit_text` and extract the string.
636         EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
637         String folderNameString = createFolderNameEditText.getText().toString();
638
639         // Get the new folder icon `Bitmap`.
640         RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
641         Bitmap folderIconBitmap;
642         if (defaultFolderIconRadioButton.isChecked()) {
643             // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
644             ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
645             Drawable folderIconDrawable = folderIconImageView.getDrawable();
646             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
647             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
648         } else {  // Assign `favoriteIcon` from the `WebView`.
649             folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
650         }
651
652         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
653         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
654         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
655         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
656
657         // Move all the bookmarks down one in the display order.
658         for (int i = 0; i < bookmarksListView.getCount(); i++) {
659             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
660             bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
661         }
662
663         // Create the folder, placing it at the top of the ListView
664         bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
665
666         // Refresh the ListView.
667         updateBookmarksListView(currentFolder);
668     }
669
670     @Override
671     public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
672         // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
673         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
674         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
675
676         // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
677         EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
678         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
679         EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
680         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
681
682         // Get `edit_bookmark_current_icon_radiobutton`.
683         RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
684
685         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
686             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
687         } else {  // Update the bookmark using the `WebView` favorite icon.
688             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
689             MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
690             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
691
692             //  Update the bookmark and the favorite icon.
693             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
694         }
695
696         // Close the contextual action mode.
697         contextualActionMode.finish();
698
699         // Refresh the `ListView`.  `setSelection` scrolls to the position of the bookmark that was edited.
700         updateBookmarksListView(currentFolder);
701         bookmarksListView.setSelection(selectedBookmarkPosition);
702     }
703
704     @Override
705     public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
706         // Get the new folder name.
707         EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
708         String newFolderNameString = editFolderNameEditText.getText().toString();
709
710         // Check to see if the new folder name is unique.
711         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
712         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
713         bookmarkFolderCursor.close();
714         if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
715             // Get a long array with the the database ID of the selected folder and convert it to an `int`.
716             long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
717             int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
718
719             // Get the `RadioButtons` from the `Dialog`.
720             RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
721             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
722
723             // Check if the favorite icon has changed.
724             if (currentFolderIconRadioButton.isChecked()) {
725                 // Update the folder name if it has changed without modifying the favorite icon.
726                 if (!newFolderNameString.equals(oldFolderNameString)) {
727                     bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
728
729                     // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
730                     updateBookmarksListView(currentFolder);
731                     bookmarksListView.setSelection(selectedBookmarkPosition);
732                 }
733             } else {  // Update the folder icon.
734                 // Get the new folder icon `Bitmap`.
735                 Bitmap folderIconBitmap;
736                 if (defaultFolderIconRadioButton.isChecked()) {
737                     // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
738                     ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
739                     Drawable folderIconDrawable = folderIconImageView.getDrawable();
740                     BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
741                     folderIconBitmap = folderIconBitmapDrawable.getBitmap();
742                 } else {  // Get the web page icon `ImageView` from the `Dialog`.
743                     folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
744                 }
745
746                 // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
747                 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
748                 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
749                 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
750
751                 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
752
753                 // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
754                 updateBookmarksListView(currentFolder);
755                 bookmarksListView.setSelection(selectedBookmarkPosition);
756             }
757         } else {  // Don't edit the folder because the new name is not unique.
758             String cannot_rename_folder = getResources().getString(R.string.cannot_save_folder) + " \"" + newFolderNameString + "\"";
759             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
760         }
761
762         // Close the contextual action mode.
763         contextualActionMode.finish();
764     }
765
766     @Override
767     public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
768         // Get the new folder database id.
769         ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
770         long[] newFolderLongArray = folderListView.getCheckedItemIds();
771
772         // Get the new folder database ID.
773         int newFolderDatabaseId = (int) newFolderLongArray[0];
774
775         // Instantiate `newFolderName`.
776         String newFolderName;
777
778         if (newFolderDatabaseId == 0) {
779             // The new folder is the home folder, represented as `""` in the database.
780             newFolderName = "";
781         } else {
782             // Get the new folder name from the database.
783             newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
784         }
785
786         // Get a long array with the the database ID of the selected bookmarks.
787         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
788         for (long databaseIdLong : selectedBookmarksLongArray) {
789             // Get `databaseIdInt` for each selected bookmark.
790             int databaseIdInt = (int) databaseIdLong;
791
792             // Move the selected bookmark to the new folder.
793             bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
794         }
795
796         // Refresh the `ListView`.
797         updateBookmarksListView(currentFolder);
798
799         // Close the contextual app bar.
800         contextualActionMode.finish();
801     }
802
803     private void updateBookmarksListView(String folderName) {
804         // Get a `Cursor` with the current contents of the bookmarks database.
805         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
806
807         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables `autoRequery`.
808         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
809             @Override
810             public View newView(Context context, Cursor cursor, ViewGroup parent) {
811                 // Inflate the individual item layout.  `false` does not attach it to the root.
812                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
813             }
814
815             @Override
816             public void bindView(View view, Context context, Cursor cursor) {
817                 // Get the favorite icon byte array from the `Cursor`.
818                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
819
820                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
821                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
822
823                 // Display the bitmap in `bookmarkFavoriteIcon`.
824                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
825                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
826
827
828                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
829                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
830                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
831                 bookmarkNameTextView.setText(bookmarkNameString);
832
833                 // Make the font bold for folders.
834                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
835                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
836                 } else {  // Reset the font to default for normal bookmarks.
837                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
838                 }
839             }
840         };
841
842         // Update the ListView.
843         bookmarksListView.setAdapter(bookmarksCursorAdapter);
844
845         // Set the AppBar title.
846         if (currentFolder.isEmpty()) {
847             appBar.setTitle(R.string.bookmarks);
848         } else {
849             appBar.setTitle(currentFolder);
850         }
851     }
852
853     private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
854         // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
855         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
856
857         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables autoRequery.
858         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
859             @Override
860             public View newView(Context context, Cursor cursor, ViewGroup parent) {
861                 // Inflate the individual item layout.  `false` does not attach it to the root.
862                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
863             }
864
865             @Override
866             public void bindView(View view, Context context, Cursor cursor) {
867                 // Get the favorite icon byte array from the cursor.
868                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
869
870                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
871                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
872
873                 // Display the bitmap in `bookmarkFavoriteIcon`.
874                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
875                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
876
877
878                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
879                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
880                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
881                 bookmarkNameTextView.setText(bookmarkNameString);
882
883                 // Make the font bold for folders.
884                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
885                     // The first argument is `null` because we don't want to change the font.
886                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
887                 } else {  // Reset the font to default.
888                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
889                 }
890             }
891         };
892
893         // Update the `ListView`.
894         bookmarksListView.setAdapter(bookmarksCursorAdapter);
895     }
896
897     private void deleteBookmarkFolderContents(int databaseId) {
898         // Get the name of the folder.
899         String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
900
901         // Get the contents of the folder.
902         Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
903
904         for (int i = 0; i < folderCursor.getCount(); i++) {
905             // Move `folderCursor` to the current row.
906             folderCursor.moveToPosition(i);
907
908             // Get the database ID of the item.
909             int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
910
911             // If this is a folder, delete the contents first.
912             if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
913                 deleteBookmarkFolderContents(itemDatabaseId);
914             }
915
916             bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
917         }
918     }
919 }