]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksActivity.java
Speed up the moving of bookmarks. https://redmine.stoutner.com/issues/48.
[PrivacyBrowserAndroid.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                 return false;
207             }
208
209             @Override
210             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
211                 // Get an array of the selected bookmarks.
212                 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
213
214                 // Calculate the number of selected bookmarks.
215                 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
216
217                 // Adjust the `mode` and the menu for the number of selected bookmarks.
218                 if (numberOfSelectedBookmarks == 0) {
219                     mode.finish();
220                 } else if (numberOfSelectedBookmarks == 1) {
221                     // List the number of selected bookmarks in the subtitle.
222                     mode.setSubtitle(getString(R.string.one_selected));
223
224                     // Show the `Move Up`, `Move Down`, and  `Edit` options.
225                     moveBookmarkUpMenuItem.setVisible(true);
226                     moveBookmarkDownMenuItem.setVisible(true);
227                     editBookmarkMenuItem.setVisible(true);
228
229                     // Get the database IDs for the bookmarks.
230                     int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
231                     int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
232                     // bookmarksListView is 0 indexed.
233                     int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
234
235                     // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
236                     if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
237                         moveBookmarkUpMenuItem.setEnabled(false);
238                         moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
239                     } else {  // Otherwise enable `moveBookmarkUpMenuItem`.
240                         moveBookmarkUpMenuItem.setEnabled(true);
241
242                         // Set the icon according to the theme.
243                         if (MainWebViewActivity.darkTheme) {
244                             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
245                         } else {
246                             moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
247                         }
248                     }
249
250                     // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
251                     if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
252                         moveBookmarkDownMenuItem.setEnabled(false);
253                         moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
254                     } else {  // Otherwise enable `moveBookmarkDownMenuItem`.
255                         moveBookmarkDownMenuItem.setEnabled(true);
256
257                         // Set the icon according to the theme.
258                         if (MainWebViewActivity.darkTheme) {
259                             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
260                         } else {
261                             moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
262                         }
263                     }
264                 } else {  // More than one bookmark is selected.
265                     // List the number of selected bookmarks in the subtitle.
266                     mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
267
268                     // Hide non-applicable `MenuItems`.
269                     moveBookmarkUpMenuItem.setVisible(false);
270                     moveBookmarkDownMenuItem.setVisible(false);
271                     editBookmarkMenuItem.setVisible(false);
272                 }
273
274                 // Do not show `Select All` if all the bookmarks are already checked.
275                 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
276                     selectAllBookmarksMenuItem.setVisible(false);
277                 } else {
278                     selectAllBookmarksMenuItem.setVisible(true);
279                 }
280             }
281
282             @Override
283             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
284                 // Get the menu item ID.
285                 int menuItemId = item.getItemId();
286
287                 // Instantiate the common variables.
288                 int numberOfBookmarks;
289                 int selectedBookmarkNewPosition;
290                 SparseBooleanArray bookmarkPositionSparseBooleanArray;
291
292                 switch (menuItemId) {
293                     case R.id.move_bookmark_up:
294                         // Get the array of checked bookmarks.
295                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
296
297                         // Store the position of the selected bookmark.
298                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
299
300                         // Initialize `selectedBookmarkNewPosition`.
301                         selectedBookmarkNewPosition = 0;
302
303                         // Iterate through the bookmarks.
304                         for (int i = 0; i < bookmarksListView.getCount(); i++) {
305                             // Get the database ID for the current bookmark.
306                             int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
307
308                             // Update the display order for the current bookmark.
309                             if (i == selectedBookmarkPosition) {  // The current bookmark is the selected bookmark.
310                                 // Move the current bookmark up one.
311                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i - 1);
312                                 selectedBookmarkNewPosition = i - 1;
313                             } else if ((i + 1) == selectedBookmarkPosition){  // The current bookmark is immediately above the selected bookmark.
314                                 // Move the current bookmark down one.
315                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i + 1);
316                             } else {  // The current bookmark is not changing positions.
317                                 // Move `bookmarksCursor` to the current bookmark position.
318                                 bookmarksCursor.moveToPosition(i);
319
320                                 // Update the display order only if it is not correct in the database.
321                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
322                                     bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i);
323                                 }
324                             }
325                         }
326
327                         // Refresh the ListView.
328                         updateBookmarksListView(currentFolder);
329
330                         // Select the previously selected bookmark in the new location.
331                         bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
332
333                         // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
334                         bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
335
336                         break;
337
338                     case R.id.move_bookmark_down:
339                         // Get the array of checked bookmarks.
340                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
341
342                         // Store the position of the selected bookmark.
343                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
344
345                         // Initialize `selectedBookmarkNewPosition`.
346                         selectedBookmarkNewPosition = 0;
347
348                         // Iterate through the bookmarks.
349                         for (int i = 0; i <bookmarksListView.getCount(); i++) {
350                             // Get the database ID for the current bookmark.
351                             int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
352
353                             // Update the display order for the current bookmark.
354                             if (i == selectedBookmarkPosition) {  // The current bookmark is the selected bookmark.
355                                 // Move the current bookmark down one.
356                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i + 1);
357                                 selectedBookmarkNewPosition = i + 1;
358                             } else if ((i - 1) == selectedBookmarkPosition) {  // The current bookmark is immediately below the selected bookmark.
359                                 // Move the bookmark below the selected bookmark up one.
360                                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i - 1);
361                             } else {  // The current bookmark is not changing positions.
362                                 // Move `bookmarksCursor` to the current bookmark position.
363                                 bookmarksCursor.moveToPosition(i);
364
365                                 // Update the display order only if it is not correct in the database.
366                                 if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
367                                     bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i);
368                                 }
369                             }
370                         }
371
372                         // Refresh the ListView.
373                         updateBookmarksListView(currentFolder);
374
375                         // Select the previously selected bookmark in the new location.
376                         bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
377
378                         // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
379                         bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
380                         break;
381
382                     case R.id.move_to_folder:
383                         // Store `checkedItemIds` for use by the `AlertDialog`.
384                         checkedItemIds = bookmarksListView.getCheckedItemIds();
385
386                         // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
387                         AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
388                         moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
389                         break;
390
391                     case R.id.edit_bookmark:
392                         // Get the array of checked bookmarks.
393                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
394
395                         // Store the position of the selected bookmark.
396                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
397
398                         // Move to the selected database ID and find out if it is a folder.
399                         bookmarksCursor.moveToPosition(selectedBookmarkPosition);
400                         boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
401
402                         // Store `checkedItemIds` for use by the `AlertDialog`.
403                         checkedItemIds = bookmarksListView.getCheckedItemIds();
404
405                         if (isFolder) {
406                             // Save the current folder name.
407                             oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
408
409                             // Show the `EditBookmarkFolderDialog` `AlertDialog` and name the instance `@string/edit_folder`.
410                             AppCompatDialogFragment editFolderDialog = new EditBookmarkFolderDialog();
411                             editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
412                         } else {
413                             // Show the `EditBookmarkDialog` `AlertDialog` and name the instance `@string/edit_bookmark`.
414                             AppCompatDialogFragment editBookmarkDialog = new EditBookmarkDialog();
415                             editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
416                         }
417                         break;
418
419                     case R.id.delete_bookmark:
420                         // Get an array of the selected rows.
421                         final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
422
423                         // Get the array of checked bookmarks.
424                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
425
426                         // Store the position of the first selected bookmark.
427                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
428
429                         updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
430
431                         // Scroll to where the first deleted bookmark was located.
432                         bookmarksListView.setSelection(selectedBookmarkPosition - 5);
433
434                         // Create `snackbarMessage`.
435                         String snackbarMessage;
436
437                         // Determine how many items are in the array and prepare an appropriate Snackbar message.
438                         if (selectedBookmarksLongArray.length == 1) {
439                             snackbarMessage = getString(R.string.one_bookmark_deleted);
440                         } else {
441                             snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
442                         }
443
444                         // Show a SnackBar.
445                         Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
446                                 .setAction(R.string.undo, new View.OnClickListener() {
447                                     @Override
448                                     public void onClick(View view) {
449                                         // Do nothing because everything will be handled by `onDismissed()` below.
450                                     }
451                                 })
452                                 .addCallback(new Snackbar.Callback() {
453                                     @Override
454                                     public void onDismissed(Snackbar snackbar, int event) {
455                                         switch (event) {
456                                             // The user pushed the `Undo` button.
457                                             case Snackbar.Callback.DISMISS_EVENT_ACTION:
458                                                 // Refresh the ListView to show the rows again.
459                                                 updateBookmarksListView(currentFolder);
460
461                                                 // Scroll to where the first deleted bookmark was located.
462                                                 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
463                                                 break;
464
465                                             // The `Snackbar` was dismissed without the `Undo` button being pushed.
466                                             default:
467                                                 // Delete each selected row.
468                                                 for (long databaseIdLong : selectedBookmarksLongArray) {
469                                                     // Convert `databaseIdLong` to an int.
470                                                     int databaseIdInt = (int) databaseIdLong;
471
472                                                     if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
473                                                         deleteBookmarkFolderContents(databaseIdInt);
474                                                     }
475
476                                                     // Delete `databaseIdInt`.
477                                                     bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
478                                                 }
479                                                 break;
480                                         }
481                                     }
482                                 })
483                                 .show();
484
485                         // Close the contextual app bar.
486                         mode.finish();
487                         break;
488
489                     case R.id.context_menu_select_all_bookmarks:
490                         numberOfBookmarks = bookmarksListView.getCount();
491
492                         for (int i = 0; i < numberOfBookmarks; i++) {
493                             bookmarksListView.setItemChecked(i, true);
494                         }
495                         break;
496                 }
497                 // Consume the click.
498                 return true;
499             }
500
501             @Override
502             public void onDestroyActionMode(ActionMode mode) {
503
504             }
505         });
506
507         // Set a FloatingActionButton for creating new bookmarks.
508         FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
509         createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
510             @Override
511             public void onClick(View view) {
512                 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
513                 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
514                 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
515             }
516         });
517     }
518
519     @Override
520     public boolean onCreateOptionsMenu(Menu menu) {
521         // Inflate the menu.
522         getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
523
524         // Success.
525         return true;
526     }
527
528     @Override
529     public boolean onOptionsItemSelected(MenuItem menuItem) {
530         // Get the ID of the `MenuItem` that was selected.
531         int menuItemId = menuItem.getItemId();
532
533         switch (menuItemId) {
534             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
535                 if (currentFolder.isEmpty()) {  // Exit BookmarksActivity if currently in the home folder.
536                     NavUtils.navigateUpFromSameTask(this);
537                 } else {  // Navigate up one folder.
538                     // Place the former parent folder in `currentFolder`.
539                     currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
540
541                     // Update `bookmarksListView`.
542                     updateBookmarksListView(currentFolder);
543                 }
544                 break;
545
546             case R.id.create_folder:
547                 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
548                 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
549                 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
550                 break;
551
552             case R.id.options_menu_select_all_bookmarks:
553                 int numberOfBookmarks = bookmarksListView.getCount();
554
555                 for (int i = 0; i < numberOfBookmarks; i++) {
556                     bookmarksListView.setItemChecked(i, true);
557                 }
558                 break;
559
560             case R.id.bookmarks_database_view:
561                 // Launch `BookmarksDatabaseViewActivity`.
562                 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
563                 startActivity(bookmarksDatabaseViewIntent);
564                 break;
565         }
566         return true;
567     }
568
569     @Override
570     public void onBackPressed() {
571         if (currentFolder.isEmpty()) {  // Exit BookmarksActivity if currently in the home folder.
572             super.onBackPressed();
573         } else {  // Navigate up one folder.
574             // Place the former parent folder in `currentFolder`.
575             currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
576
577             // Reload the `ListView`.
578             updateBookmarksListView(currentFolder);
579         }
580     }
581
582     @Override
583     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
584         // Get the `EditTexts` from the `dialogFragment`.
585         EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
586         EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
587
588         // Extract the strings from the `EditTexts`.
589         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
590         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
591
592         // Convert the favoriteIcon Bitmap to a byte array.
593         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
594         // `0` is for lossless compression (the only option for a PNG).
595         MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
596         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
597
598         // Display the new bookmark below the current items in the (0 indexed) list.
599         int newBookmarkDisplayOrder = bookmarksListView.getCount();
600
601         // Create the bookmark.
602         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
603
604         // Refresh the `ListView`.  `setSelection` scrolls to the bottom of the list.
605         updateBookmarksListView(currentFolder);
606         bookmarksListView.setSelection(newBookmarkDisplayOrder);
607     }
608
609     @Override
610     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
611         // Get `create_folder_name_edit_text` and extract the string.
612         EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
613         String folderNameString = createFolderNameEditText.getText().toString();
614
615         // Check to see if the folder already exists.
616         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(folderNameString);
617         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
618         bookmarkFolderCursor.close();
619         if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
620             String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
621             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
622         } else {  // Create the folder.
623             // Get the new folder icon `Bitmap`.
624             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
625             Bitmap folderIconBitmap;
626             if (defaultFolderIconRadioButton.isChecked()) {
627                 // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
628                 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
629                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
630                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
631                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
632             } else {  // Assign `favoriteIcon` from the `WebView`.
633                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
634             }
635
636             // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
637             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
638             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
639             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
640
641             // Move all the bookmarks down one in the display order.
642             for (int i = 0; i < bookmarksListView.getCount(); i++) {
643                 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
644                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
645             }
646
647             // Create the folder, placing it at the top of the ListView
648             bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
649
650             // Refresh the ListView.
651             updateBookmarksListView(currentFolder);
652         }
653     }
654
655     @Override
656     public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
657         // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
658         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
659         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
660
661         // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
662         EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
663         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
664         EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
665         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
666
667         // Get `edit_bookmark_current_icon_radiobutton`.
668         RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
669
670         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
671             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
672         } else {  // Update the bookmark using the `WebView` favorite icon.
673             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
674             MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
675             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
676
677             //  Update the bookmark and the favorite icon.
678             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
679         }
680
681         // Close the contextual action mode.
682         contextualActionMode.finish();
683
684         // Refresh the `ListView`.  `setSelection` scrolls to the position of the bookmark that was edited.
685         updateBookmarksListView(currentFolder);
686         bookmarksListView.setSelection(selectedBookmarkPosition);
687     }
688
689     @Override
690     public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
691         // Get the new folder name.
692         EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
693         String newFolderNameString = editFolderNameEditText.getText().toString();
694
695         // Check to see if the new folder name is unique.
696         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
697         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
698         bookmarkFolderCursor.close();
699         if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
700             // Get a long array with the the database ID of the selected folder and convert it to an `int`.
701             long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
702             int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
703
704             // Get the `RadioButtons` from the `Dialog`.
705             RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
706             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
707
708             // Check if the favorite icon has changed.
709             if (currentFolderIconRadioButton.isChecked()) {
710                 // Update the folder name if it has changed without modifying the favorite icon.
711                 if (!newFolderNameString.equals(oldFolderNameString)) {
712                     bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
713
714                     // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
715                     updateBookmarksListView(currentFolder);
716                     bookmarksListView.setSelection(selectedBookmarkPosition);
717                 }
718             } else {  // Update the folder icon.
719                 // Get the new folder icon `Bitmap`.
720                 Bitmap folderIconBitmap;
721                 if (defaultFolderIconRadioButton.isChecked()) {
722                     // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
723                     ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
724                     Drawable folderIconDrawable = folderIconImageView.getDrawable();
725                     BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
726                     folderIconBitmap = folderIconBitmapDrawable.getBitmap();
727                 } else {  // Get the web page icon `ImageView` from the `Dialog`.
728                     folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
729                 }
730
731                 // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
732                 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
733                 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
734                 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
735
736                 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
737
738                 // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
739                 updateBookmarksListView(currentFolder);
740                 bookmarksListView.setSelection(selectedBookmarkPosition);
741             }
742         } else {  // Don't edit the folder because the new name is not unique.
743             String cannot_rename_folder = getResources().getString(R.string.cannot_save_folder) + " \"" + newFolderNameString + "\"";
744             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
745         }
746
747         // Close the contextual action mode.
748         contextualActionMode.finish();
749     }
750
751     @Override
752     public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
753         // Get the new folder database id.
754         ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
755         long[] newFolderLongArray = folderListView.getCheckedItemIds();
756
757         if (newFolderLongArray.length == 0) {  // No new folder was selected.
758             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_INDEFINITE).show();
759         } else {  // Move the selected bookmarks.
760             // Get the new folder database ID.
761             int newFolderDatabaseId = (int) newFolderLongArray[0];
762
763             // Instantiate `newFolderName`.
764             String newFolderName;
765
766             if (newFolderDatabaseId == 0) {
767                 // The new folder is the home folder, represented as `""` in the database.
768                 newFolderName = "";
769             } else {
770                 // Get the new folder name from the database.
771                 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
772             }
773
774             // Get a long array with the the database ID of the selected bookmarks.
775             long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
776             for (long databaseIdLong : selectedBookmarksLongArray) {
777                 // Get `databaseIdInt` for each selected bookmark.
778                 int databaseIdInt = (int) databaseIdLong;
779
780                 // Move the selected bookmark to the new folder.
781                 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
782             }
783
784             // Refresh the `ListView`.
785             updateBookmarksListView(currentFolder);
786
787             // Close the contextual app bar.
788             contextualActionMode.finish();
789         }
790     }
791
792     private void updateBookmarksListView(String folderName) {
793         // Get a `Cursor` with the current contents of the bookmarks database.
794         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
795
796         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables `autoRequery`.
797         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
798             @Override
799             public View newView(Context context, Cursor cursor, ViewGroup parent) {
800                 // Inflate the individual item layout.  `false` does not attach it to the root.
801                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
802             }
803
804             @Override
805             public void bindView(View view, Context context, Cursor cursor) {
806                 // Get the favorite icon byte array from the `Cursor`.
807                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
808
809                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
810                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
811
812                 // Display the bitmap in `bookmarkFavoriteIcon`.
813                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
814                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
815
816
817                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
818                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
819                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
820                 bookmarkNameTextView.setText(bookmarkNameString);
821
822                 // Make the font bold for folders.
823                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
824                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
825                 } else {  // Reset the font to default for normal bookmarks.
826                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
827                 }
828             }
829         };
830
831         // Update the ListView.
832         bookmarksListView.setAdapter(bookmarksCursorAdapter);
833
834         // Set the AppBar title.
835         if (currentFolder.isEmpty()) {
836             appBar.setTitle(R.string.bookmarks);
837         } else {
838             appBar.setTitle(currentFolder);
839         }
840     }
841
842     private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
843         // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
844         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
845
846         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables autoRequery.
847         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
848             @Override
849             public View newView(Context context, Cursor cursor, ViewGroup parent) {
850                 // Inflate the individual item layout.  `false` does not attach it to the root.
851                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
852             }
853
854             @Override
855             public void bindView(View view, Context context, Cursor cursor) {
856                 // Get the favorite icon byte array from the cursor.
857                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
858
859                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
860                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
861
862                 // Display the bitmap in `bookmarkFavoriteIcon`.
863                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
864                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
865
866
867                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
868                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
869                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
870                 bookmarkNameTextView.setText(bookmarkNameString);
871
872                 // Make the font bold for folders.
873                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
874                     // The first argument is `null` because we don't want to change the font.
875                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
876                 } else {  // Reset the font to default.
877                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
878                 }
879             }
880         };
881
882         // Update the `ListView`.
883         bookmarksListView.setAdapter(bookmarksCursorAdapter);
884     }
885
886     private void deleteBookmarkFolderContents(int databaseId) {
887         // Get the name of the folder.
888         String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
889
890         // Get the contents of the folder.
891         Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
892
893         for (int i = 0; i < folderCursor.getCount(); i++) {
894             // Move `folderCursor` to the current row.
895             folderCursor.moveToPosition(i);
896
897             // Get the database ID of the item.
898             int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
899
900             // If this is a folder, delete the contents first.
901             if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
902                 deleteBookmarkFolderContents(itemDatabaseId);
903             }
904
905             bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
906         }
907     }
908 }