]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/BookmarksActivity.java
Add the ability to create and edit bookmark folders.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / BookmarksActivity.java
1 /**
2  * Copyright 2016 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;
21
22 import android.app.Activity;
23 import android.app.DialogFragment;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.database.Cursor;
27 import android.database.DatabaseUtils;
28 import android.graphics.Bitmap;
29 import android.graphics.BitmapFactory;
30 import android.graphics.Typeface;
31 import android.graphics.drawable.BitmapDrawable;
32 import android.graphics.drawable.Drawable;
33 import android.os.Bundle;
34 import android.support.design.widget.FloatingActionButton;
35 import android.support.design.widget.Snackbar;
36 import android.support.v4.app.NavUtils;
37 import android.support.v4.content.ContextCompat;
38 import android.support.v4.widget.CursorAdapter;
39 import android.support.v7.app.ActionBar;
40 import android.support.v7.app.AppCompatActivity;
41 import android.support.v7.widget.Toolbar;
42 import android.util.SparseBooleanArray;
43 import android.view.ActionMode;
44 import android.view.Menu;
45 import android.view.MenuItem;
46 import android.view.View;
47 import android.view.ViewGroup;
48 import android.widget.AbsListView;
49 import android.widget.AdapterView;
50 import android.widget.CheckBox;
51 import android.widget.EditText;
52 import android.widget.ImageView;
53 import android.widget.ListView;
54 import android.widget.RadioButton;
55 import android.widget.TextView;
56
57 import java.io.ByteArrayOutputStream;
58
59 public class BookmarksActivity extends AppCompatActivity implements CreateBookmark.CreateBookmarkListener,
60         CreateBookmarkFolder.CreateBookmarkFolderListener, EditBookmark.EditBookmarkListener,
61         EditBookmarkFolder.EditBookmarkFolderListener {
62     // `bookmarksDatabaseHandler` is public static so it can be accessed from EditBookmark.  It is also used in `onCreate()`,
63     // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
64     public static BookmarksDatabaseHandler bookmarksDatabaseHandler;
65
66     // `bookmarksListView` is public static so it can be accessed from EditBookmark.
67     // It is also used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
68     public static ListView bookmarksListView;
69
70     // `currentFolder` is used in `onCreate`, `onOptionsItemSelected()`, `onCreateBookmarkCreate`, `onCreateBookmarkFolderCreate`, and `onEditBookmarkSave`.
71     private String currentFolder;
72
73     // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
74     private ActionMode contextualActionMode;
75
76     // `selectedBookmarkPosition` is used in `onCreate()` and `onEditBookarkSave()`.
77     private int selectedBookmarkPosition;
78
79     // `appBar` is used in `onCreate()` and `updateBookmarksListView()`.
80     private ActionBar appBar;
81
82     // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
83     private Cursor bookmarksCursor;
84
85     // `oldFolderName` is used in `onCreate()` and `onEditBookmarkFolderSave()`.
86     private String oldFolderNameString;
87
88     @Override
89     protected void onCreate(Bundle savedInstanceState) {
90         super.onCreate(savedInstanceState);
91         setContentView(R.layout.bookmarks_coordinatorlayout);
92
93         // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
94         final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
95         setSupportActionBar(bookmarksAppBar);
96
97         // Display the home arrow on `SupportActionBar`.
98         appBar = getSupportActionBar();
99         assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
100         appBar.setDisplayHomeAsUpEnabled(true);
101
102
103         // Initialize the database handler and the ListView.
104         // `this` specifies the context.  The two `null`s do not specify the database name or a `CursorFactory`.
105         // The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHandler`.
106         bookmarksDatabaseHandler = new BookmarksDatabaseHandler(this, null, null, 0);
107         bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
108
109         // Set currentFolder to the home folder, which is null in the database.
110         currentFolder = "";
111
112         // Display the bookmarks in the ListView.
113         updateBookmarksListView(currentFolder);
114
115         // Set a listener so that tapping a list item loads the URL.  We need to store the activity
116         // in a variable so that we can return to the parent activity after loading the URL.
117         final Activity bookmarksActivity = this;
118         bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
119             @Override
120             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
121                 // Convert the id from long to int to match the format of the bookmarks database.
122                 int databaseID = (int) id;
123
124                 // Get the bookmark `Cursor` and move it to the first row.
125                 Cursor bookmarkCursor = bookmarksDatabaseHandler.getBookmarkCursor(databaseID);
126                 bookmarkCursor.moveToFirst();
127
128                 // If the bookmark is a folder load its contents into the ListView.
129                 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
130                     // Update `currentFolder`.
131                     currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
132
133                     // Reload the ListView with `currentFolder`.
134                     updateBookmarksListView(currentFolder);
135                 } else {  // Load the URL into `mainWebView`.
136                     // Get the bookmark URL and assign it to formattedUrlString.
137                     MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_URL));
138
139                     //  Load formattedUrlString and return to the main activity.
140                     MainWebViewActivity.mainWebView.loadUrl(MainWebViewActivity.formattedUrlString);
141                     NavUtils.navigateUpFromSameTask(bookmarksActivity);
142                 }
143
144                 // Close the `Cursor`.
145                 bookmarkCursor.close();
146             }
147         });
148
149         // `MultiChoiceModeListener` handles long clicks.
150         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
151             // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
152             MenuItem moveBookmarkUpMenuItem;
153
154             // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
155             MenuItem moveBookmarkDownMenuItem;
156
157             // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
158             MenuItem editBookmarkMenuItem;
159
160             // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
161             MenuItem selectAllBookmarksMenuItem;
162
163             @Override
164             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
165                 // Inflate the menu for the contextual app bar and set the title.
166                 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
167
168                 // Set the title.
169                 if (currentFolder.isEmpty()) {
170                     // Use `R.string.bookmarks` if we are in the home folder.
171                     mode.setTitle(R.string.bookmarks);
172                 } else {  // Use the current folder name as the title.
173                     mode.setTitle(currentFolder);
174                 }
175
176                 // Get a handle for MenuItems we need to selectively disable.
177                 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
178                 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
179                 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
180                 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
181
182                 return true;
183             }
184
185             @Override
186             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
187                 return false;
188             }
189
190             @Override
191             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
192                 // Get an array of the selected bookmarks.
193                 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
194
195                 // Calculate the number of selected bookmarks.
196                 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
197
198                 // List the number of selected bookmarks in the subtitle.
199                 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
200
201                 if (numberOfSelectedBookmarks == 1) {
202                     // Show the `Move Up`, `Move Down`, and  `Edit` option only if 1 bookmark is selected.
203                     moveBookmarkUpMenuItem.setVisible(true);
204                     moveBookmarkDownMenuItem.setVisible(true);
205                     editBookmarkMenuItem.setVisible(true);
206
207                     // Get the database IDs for the bookmarks.
208                     int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
209                     int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
210                     // bookmarksListView is 0 indexed.
211                     int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
212
213                     // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
214                     if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
215                         moveBookmarkUpMenuItem.setEnabled(false);
216                         moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_disabled);
217                     } else {  // Otherwise enable `moveBookmarkUpMenuItem`.
218                         moveBookmarkUpMenuItem.setEnabled(true);
219                         moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_enabled);
220                     }
221
222                     // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
223                     if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
224                         moveBookmarkDownMenuItem.setEnabled(false);
225                         moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_disabled);
226                     } else {  // Otherwise enable `moveBookmarkDownMenuItem`.
227                         moveBookmarkDownMenuItem.setEnabled(true);
228                         moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_enabled);
229                     }
230                 } else {  // Hide the MenuItems because more than one bookmark is selected.
231                     moveBookmarkUpMenuItem.setVisible(false);
232                     moveBookmarkDownMenuItem.setVisible(false);
233                     editBookmarkMenuItem.setVisible(false);
234                 }
235
236                 // Do not show `Select All` if all the bookmarks are already checked.
237                 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
238                     selectAllBookmarksMenuItem.setVisible(false);
239                 } else {
240                     selectAllBookmarksMenuItem.setVisible(true);
241                 }
242             }
243
244             @Override
245             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
246                 int menuItemId = item.getItemId();
247
248                 // `numberOfBookmarks` is used in `R.id.move_bookmark_up_enabled`, `R.id.move_bookmark_down_enabled`, and `R.id.context_menu_select_all_bookmarks`.
249                 int numberOfBookmarks;
250
251                 // `selectedBookmarkLongArray` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
252                 long[]selectedBookmarkLongArray;
253                 // `selectedBookmarkDatabaseId` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
254                 int selectedBookmarkDatabaseId;
255                 // `selectedBookmarkNewPosition` is used in `R.id.move_bookmark_up` and `R.id.move_bookmark_down`.
256                 int selectedBookmarkNewPosition;
257                 // `bookmarkPositionSparseBooleanArray` is used in `R.id.edit_bookmark` and `R.id.delete_bookmark`.
258                 SparseBooleanArray bookmarkPositionSparseBooleanArray;
259
260                 switch (menuItemId) {
261                     case R.id.move_bookmark_up:
262                         // Get the selected bookmark database ID.
263                         selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
264                         selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
265
266                         // Initialize `selectedBookmarkNewPosition`.
267                         selectedBookmarkNewPosition = 0;
268
269                         for (int i = 0; i < bookmarksListView.getCount(); i++) {
270                             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
271                             int nextBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i + 1);
272
273                             if (databaseId == selectedBookmarkDatabaseId || nextBookmarkDatabaseId == selectedBookmarkDatabaseId) {
274                                 if (databaseId == selectedBookmarkDatabaseId) {
275                                     // Move the selected bookmark up one and store the new bookmark position.
276                                     bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i - 1);
277                                     selectedBookmarkNewPosition = i - 1;
278                                 } else {  // Move the bookmark above the selected bookmark down one.
279                                     bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
280                                 }
281                             } else {
282                                 // Reset the rest of the bookmarks' DISPLAY_ORDER to match the position in the ListView.
283                                 // This isn't necessary, but it clears out any stray values that might have crept into the database.
284                                 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i);
285                             }
286                         }
287
288                         // Refresh the ListView.
289                         updateBookmarksListView(currentFolder);
290
291                         // Select the previously selected bookmark in the new location.
292                         bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
293
294                         bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
295
296                         break;
297
298                     case R.id.move_bookmark_down:
299                         // Get the selected bookmark database ID.
300                         selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
301                         selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
302
303                         // Initialize `selectedBookmarkNewPosition`.
304                         selectedBookmarkNewPosition = 0;
305
306                         for (int i = 0; i <bookmarksListView.getCount(); i++) {
307                             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
308                             int previousBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i - 1);
309
310                             if (databaseId == selectedBookmarkDatabaseId || previousBookmarkDatabaseId == selectedBookmarkDatabaseId) {
311                                 if (databaseId == selectedBookmarkDatabaseId) {
312                                     // Move the selected bookmark down one and store the new bookmark position.
313                                     bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
314                                     selectedBookmarkNewPosition = i + 1;
315                                 } else {  // Move the bookmark below the selected bookmark up one.
316                                     bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i - 1);
317                                 }
318                             } else {
319                                 // Reset the rest of the bookmark' DISPLAY_ORDER to match the position in the ListView.
320                                 // This isn't necessary, but it clears out any stray values that might have crept into the database.
321                                 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i);
322                             }
323                         }
324
325                         // Refresh the ListView.
326                         updateBookmarksListView(currentFolder);
327
328                         // Select the previously selected bookmark in the new location.
329                         bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
330
331                         bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
332                         break;
333
334                     case R.id.edit_bookmark:
335                         // Get a handle for `contextualActionMode` so we can close it when `editBookmarkDialog` is finished.
336                         contextualActionMode = mode;
337
338                         // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
339                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
340                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
341
342                         // Move to the selected database ID and find out if it is a folder.
343                         bookmarksCursor.moveToPosition(selectedBookmarkPosition);
344                         boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1);
345
346                         if (isFolder) {
347                             // Save the current folder name.
348                             oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
349
350                             // Show the `EditBookmarkFolder` `AlertDialog` and name the instance `@string/edit_folder`.
351                             DialogFragment editFolderDialog = new EditBookmarkFolder();
352                             editFolderDialog.show(getFragmentManager(), getResources().getString(R.string.edit_folder));
353                         } else {
354                             // Show the `EditBookmark` `AlertDialog` and name the instance `@string/edit_bookmark`.
355                             DialogFragment editBookmarkDialog = new EditBookmark();
356                             editBookmarkDialog.show(getFragmentManager(), getResources().getString(R.string.edit_bookmark));
357                         }
358                         break;
359
360                     case R.id.delete_bookmark:
361                         // Get an array of the selected rows.
362                         final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
363
364                         // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
365                         bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
366                         selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
367
368                         updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
369
370                         // Scroll to where the deleted bookmark was located.
371                         bookmarksListView.setSelection(selectedBookmarkPosition);
372
373                         String snackbarMessage;
374
375                         // Determine how many items are in the array and prepare an appropriate Snackbar message.
376                         if (selectedBookmarksLongArray.length == 1) {
377                             snackbarMessage = getString(R.string.one_bookmark_deleted);
378                         } else {
379                             snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
380                         }
381
382                         // Show a SnackBar.
383                         Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
384                                 .setAction(R.string.undo, new View.OnClickListener() {
385                                     @Override
386                                     public void onClick(View view) {
387                                         // Do nothing because everything will be handled by `onDismissed()` below.
388                                     }
389                                 })
390                                 .setCallback(new Snackbar.Callback() {
391                                     @Override
392                                     public void onDismissed(Snackbar snackbar, int event) {
393                                         switch (event) {
394                                             // The user pushed the "Undo" button.
395                                             case Snackbar.Callback.DISMISS_EVENT_ACTION:
396                                                 // Refresh the ListView to show the rows again.
397                                                 updateBookmarksListView(currentFolder);
398
399                                                 break;
400
401                                             // The Snackbar was dismissed without the "Undo" button being pushed.
402                                             default:
403                                                 // Delete each selected row.
404                                                 for (long databaseIdLong : selectedBookmarksLongArray) {
405                                                     // Convert `databaseIdLong` to an int.
406                                                     int databaseIdInt = (int) databaseIdLong;
407
408                                                     // Delete the database row.
409                                                     bookmarksDatabaseHandler.deleteBookmark(databaseIdInt);
410                                                 }
411                                                 break;
412                                         }
413                                     }
414                                 })
415                                 .show();
416
417                         // Close the contextual app bar.
418                         mode.finish();
419                         break;
420
421                     case R.id.context_menu_select_all_bookmarks:
422                         numberOfBookmarks = bookmarksListView.getCount();
423
424                         for (int i = 0; i < numberOfBookmarks; i++) {
425                             bookmarksListView.setItemChecked(i, true);
426                         }
427                         break;
428                 }
429                 // Consume the click.
430                 return true;
431             }
432
433             @Override
434             public void onDestroyActionMode(ActionMode mode) {
435
436             }
437         });
438
439         // Set a FloatingActionButton for creating new bookmarks.
440         FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
441         assert createBookmarkFAB != null;
442         createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
443             @Override
444             public void onClick(View view) {
445                 // Show the `CreateBookmark` `AlertDialog` and name the instance `@string/create_bookmark`.
446                 DialogFragment createBookmarkDialog = new CreateBookmark();
447                 createBookmarkDialog.show(getFragmentManager(), getResources().getString(R.string.create_bookmark));
448             }
449         });
450     }
451
452     @Override
453     public boolean onCreateOptionsMenu(Menu menu) {
454         //Inflate the menu.
455         getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
456
457         return true;
458     }
459
460     @Override
461     public boolean onPrepareOptionsMenu(Menu menu) {
462         super.onPrepareOptionsMenu(menu);
463
464         return true;
465     }
466
467     @Override
468     public boolean onOptionsItemSelected(MenuItem menuItem) {
469         int menuItemId = menuItem.getItemId();
470
471         switch (menuItemId) {
472             case android.R.id.home:
473                 // Exit BookmarksActivity if currently at the home folder.
474                 if (currentFolder.isEmpty()) {
475                     NavUtils.navigateUpFromSameTask(this);
476                 } else {  // Navigate up one folder.
477                     // Place the former parent folder in `currentFolder`.
478                     currentFolder = bookmarksDatabaseHandler.getParentFolder(currentFolder);
479
480                     updateBookmarksListView(currentFolder);
481                 }
482                 break;
483
484             case R.id.create_folder:
485                 // Show the `CreateBookmarkFolder` `AlertDialog` and name the instance `@string/create_folder`.
486                 DialogFragment createBookmarkFolderDialog = new CreateBookmarkFolder();
487                 createBookmarkFolderDialog.show(getFragmentManager(), getResources().getString(R.string.create_folder));
488                 break;
489
490             case R.id.options_menu_select_all_bookmarks:
491                 int numberOfBookmarks = bookmarksListView.getCount();
492
493                 for (int i = 0; i < numberOfBookmarks; i++) {
494                     bookmarksListView.setItemChecked(i, true);
495                 }
496                 break;
497
498             case R.id.bookmarks_database_view:
499                 // Launch `BookmarksDatabaseViewActivity`.
500                 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
501                 startActivity(bookmarksDatabaseViewIntent);
502                 break;
503         }
504         return true;
505     }
506
507     @Override
508     public void onCancelCreateBookmark(DialogFragment dialogFragment) {
509         // Do nothing because the user selected `Cancel`.
510     }
511
512     @Override
513     public void onCreateBookmark(DialogFragment dialogFragment) {
514         // Get the `EditText`s from the `createBookmarkDialogFragment` and extract the strings.
515         EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
516         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
517         EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
518         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
519
520         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
521         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
522         MainWebViewActivity.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
523         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
524
525         // Display the new bookmark below the current items in the (0 indexed) list.
526         int newBookmarkDisplayOrder = bookmarksListView.getCount();
527
528         // Create the bookmark.
529         bookmarksDatabaseHandler.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
530
531         // Refresh the ListView.  `setSelection` scrolls to the bottom of the list.
532         updateBookmarksListView(currentFolder);
533         bookmarksListView.setSelection(newBookmarkDisplayOrder);
534     }
535
536     @Override
537     public void onCancelCreateBookmarkFolder(DialogFragment dialogFragment) {
538         // Do nothing because the user selected `Cancel`.
539     }
540
541     @Override
542     public void onCreateBookmarkFolder(DialogFragment dialogFragment) {
543         // Get `create_folder_name_edit_text` and extract the string.
544         EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
545         String folderNameString = createFolderNameEditText.getText().toString();
546
547         // Check to see if the folder already exists.
548         Cursor bookmarkFolderCursor = bookmarksDatabaseHandler.getFolderCursor(folderNameString);
549         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
550         bookmarkFolderCursor.close();
551         if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
552             String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
553             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
554         } else {  // Create the folder.
555             // Get the new folder icon.
556             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobuttion);
557             Bitmap folderIconBitmap;
558             if (defaultFolderIconRadioButton.isChecked()) {
559                 // Get the default folder icon drawable and convert it to a `Bitmap`.  `this` specifies the current context.
560                 Drawable folderIconDrawable = ContextCompat.getDrawable(this, R.drawable.folder_blue_bitmap);
561                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
562                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
563             } else {
564                 folderIconBitmap = MainWebViewActivity.favoriteIcon;
565             }
566
567             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
568             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
569             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
570             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
571
572             // Move all the bookmarks down one in the display order.
573             for (int i = 0; i < bookmarksListView.getCount(); i++) {
574                 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
575                 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
576             }
577
578             // Create the folder, placing it at the top of the ListView
579             bookmarksDatabaseHandler.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
580
581             // Refresh the ListView.
582             updateBookmarksListView(currentFolder);
583         }
584     }
585
586     @Override
587     public void onCancelEditBookmark(DialogFragment dialogFragment) {
588         // Do nothing because the user selected `Cancel`.
589     }
590
591     @Override
592     public void onSaveEditBookmark(DialogFragment dialogFragment) {
593         // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
594         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
595         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
596
597         // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
598         EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
599         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
600         EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
601         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
602
603         // Get `edit_bookmark_current_icon_radiobutton`.
604         RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
605
606         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
607             bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
608         } else {  // Update the bookmark and the favorite icon.
609             // Get the new favorite icon from the `Dialog` and convert it into a `Bitmap`.
610             ImageView newFavoriteIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_web_page_favorite_icon);
611             Drawable newFavoriteIconDrawable = newFavoriteIconImageView.getDrawable();
612             Bitmap newFavoriteIconBitmap = ((BitmapDrawable) newFavoriteIconDrawable).getBitmap();
613
614             // Convert `newFavoriteIconBitmap` into a Byte Array.
615             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
616             newFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
617             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
618
619             //  Update the bookmark and the favorite icon.
620             bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
621         }
622
623         // Close the contextual action mode.
624         contextualActionMode.finish();
625
626         // Refresh the `ListView`.  `setSelection` scrolls to the position of the bookmark that was edited.
627         updateBookmarksListView(currentFolder);
628         bookmarksListView.setSelection(selectedBookmarkPosition);
629     }
630
631     @Override
632     public void onCancelEditBookmarkFolder(DialogFragment dialogFragment) {
633         // Do nothing because the user selected `Cancel`.
634     }
635
636     @Override
637     public void onSaveEditBookmarkFolder(DialogFragment dialogFragment) {
638         // Get the new folder name.
639         EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
640         String newFolderNameString = editFolderNameEditText.getText().toString();
641
642         // Check to see if the new folder name is unique.
643         Cursor bookmarkFolderCursor = bookmarksDatabaseHandler.getFolderCursor(newFolderNameString);
644         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
645         bookmarkFolderCursor.close();
646         if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
647             // Get a long array with the the databaseId of the selected folder and convert it to an `int`.
648             long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
649             int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
650
651             // Get the `RadioButtons` from the `Dialog`.
652             RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
653             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
654             Bitmap folderIconBitmap;
655
656             // Prepare the favorite icon.
657             if (currentFolderIconRadioButton.isChecked()) {
658                 // Update the folder name if it has changed.
659                 if (!newFolderNameString.equals(oldFolderNameString)) {
660                     bookmarksDatabaseHandler.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
661
662                     // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
663                     updateBookmarksListView(currentFolder);
664                     bookmarksListView.setSelection(selectedBookmarkPosition);
665                 }
666             } else {  // Prepare the new favorite icon.
667                 if (defaultFolderIconRadioButton.isChecked()) {
668                     // Get the default folder icon drawable and convert it to a `Bitmap`.  `this` specifies the current context.
669                     Drawable folderIconDrawable = ContextCompat.getDrawable(this, R.drawable.folder_blue_bitmap);
670                     BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
671                     folderIconBitmap = folderIconBitmapDrawable.getBitmap();
672                 } else {  // Use the web page favorite icon.
673                     folderIconBitmap = MainWebViewActivity.favoriteIcon;
674                 }
675
676                 // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
677                 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
678                 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
679                 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
680
681                 bookmarksDatabaseHandler.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
682
683                 // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
684                 updateBookmarksListView(currentFolder);
685                 bookmarksListView.setSelection(selectedBookmarkPosition);
686             }
687         } else {  // Don't edit the folder because the new name is not unique.
688             String cannot_rename_folder = getResources().getString(R.string.cannot_rename_folder) + " \"" + newFolderNameString + "\"";
689             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
690         }
691     }
692
693     private void updateBookmarksListView(String folderName) {
694         // Get a `Cursor` with the current contents of the bookmarks database.
695         bookmarksCursor = bookmarksDatabaseHandler.getAllBookmarksCursorByDisplayOrder(folderName);
696
697         // Setup `bookmarksCursorAdapter` with `this` context.  The `false` disables autoRequery.
698         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
699             @Override
700             public View newView(Context context, Cursor cursor, ViewGroup parent) {
701                 // Inflate the individual item layout.  `false` does not attach it to the root.
702                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
703             }
704
705             @Override
706             public void bindView(View view, Context context, Cursor cursor) {
707                 // Get the favorite icon byte array from the `Cursor`.
708                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
709
710                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
711                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
712
713                 // Display the bitmap in `bookmarkFavoriteIcon`.
714                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
715                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
716
717
718                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
719                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
720                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
721                 bookmarkNameTextView.setText(bookmarkNameString);
722
723                 // Make the font bold for folders.
724                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
725                     // The first argument is `null` because we don't want to chage the font.
726                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
727                 } else {  // Reset the font to default.
728                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
729                 }
730             }
731         };
732
733         // Update the ListView.
734         bookmarksListView.setAdapter(bookmarksCursorAdapter);
735
736         // Set the AppBar title.
737         if (currentFolder.isEmpty()) {
738             appBar.setTitle(R.string.bookmarks);
739         } else {
740             appBar.setTitle(currentFolder);
741         }
742     }
743
744     private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
745         // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
746         bookmarksCursor = bookmarksDatabaseHandler.getBookmarksCursorExcept(exceptIdLongArray, folderName);
747
748         // Setup `bookmarksCursorAdapter` with `this` context.  The `false` disables autoRequery.
749         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
750             @Override
751             public View newView(Context context, Cursor cursor, ViewGroup parent) {
752                 // Inflate the individual item layout.  `false` does not attach it to the root.
753                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
754             }
755
756             @Override
757             public void bindView(View view, Context context, Cursor cursor) {
758                 // Get the favorite icon byte array from the cursor.
759                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
760
761                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
762                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
763
764                 // Display the bitmap in `bookmarkFavoriteIcon`.
765                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
766                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
767
768
769                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
770                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
771                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
772                 bookmarkNameTextView.setText(bookmarkNameString);
773
774                 // Make the font bold for folders.
775                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
776                     // The first argument is `null` because we don't want to chage the font.
777                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
778                 } else {  // Reset the font to default.
779                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
780                 }
781             }
782         };
783
784         // Update the ListView.
785         bookmarksListView.setAdapter(bookmarksCursorAdapter);
786     }
787 }