]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/BookmarksActivity.java
Update the display order after deleting a bookmark. Fixes https://redmine.stoutner...
[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
480                                                 // Update the display order.
481                                                 for (int i = 0; i < bookmarksListView.getCount(); i++) {
482                                                     // Get the database ID for the current bookmark.
483                                                     int currentBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i);
484
485                                                     // Move `bookmarksCursor` to the current bookmark position.
486                                                     bookmarksCursor.moveToPosition(i);
487
488                                                     // Update the display order only if it is not correct in the database.
489                                                     if (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.DISPLAY_ORDER)) != i) {
490                                                         bookmarksDatabaseHelper.updateBookmarkDisplayOrder(currentBookmarkDatabaseId, i);
491                                                     }
492                                                 }
493                                                 break;
494                                         }
495                                     }
496                                 })
497                                 .show();
498
499                         // Close the contextual app bar.
500                         mode.finish();
501                         break;
502
503                     case R.id.context_menu_select_all_bookmarks:
504                         numberOfBookmarks = bookmarksListView.getCount();
505
506                         for (int i = 0; i < numberOfBookmarks; i++) {
507                             bookmarksListView.setItemChecked(i, true);
508                         }
509                         break;
510                 }
511                 // Consume the click.
512                 return true;
513             }
514
515             @Override
516             public void onDestroyActionMode(ActionMode mode) {
517
518             }
519         });
520
521         // Set a FloatingActionButton for creating new bookmarks.
522         FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
523         createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
524             @Override
525             public void onClick(View view) {
526                 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
527                 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
528                 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
529             }
530         });
531     }
532
533     @Override
534     public boolean onCreateOptionsMenu(Menu menu) {
535         // Inflate the menu.
536         getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
537
538         // Success.
539         return true;
540     }
541
542     @Override
543     public boolean onOptionsItemSelected(MenuItem menuItem) {
544         // Get the ID of the `MenuItem` that was selected.
545         int menuItemId = menuItem.getItemId();
546
547         switch (menuItemId) {
548             case android.R.id.home:  // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
549                 if (currentFolder.isEmpty()) {  // Exit BookmarksActivity if currently in the home folder.
550                     NavUtils.navigateUpFromSameTask(this);
551                 } else {  // Navigate up one folder.
552                     // Place the former parent folder in `currentFolder`.
553                     currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
554
555                     // Update `bookmarksListView`.
556                     updateBookmarksListView(currentFolder);
557                 }
558                 break;
559
560             case R.id.create_folder:
561                 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
562                 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
563                 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
564                 break;
565
566             case R.id.options_menu_select_all_bookmarks:
567                 int numberOfBookmarks = bookmarksListView.getCount();
568
569                 for (int i = 0; i < numberOfBookmarks; i++) {
570                     bookmarksListView.setItemChecked(i, true);
571                 }
572                 break;
573
574             case R.id.bookmarks_database_view:
575                 // Launch `BookmarksDatabaseViewActivity`.
576                 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
577                 startActivity(bookmarksDatabaseViewIntent);
578                 break;
579         }
580         return true;
581     }
582
583     @Override
584     public void onBackPressed() {
585         if (currentFolder.isEmpty()) {  // Exit BookmarksActivity if currently in the home folder.
586             super.onBackPressed();
587         } else {  // Navigate up one folder.
588             // Place the former parent folder in `currentFolder`.
589             currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
590
591             // Reload the `ListView`.
592             updateBookmarksListView(currentFolder);
593         }
594     }
595
596     @Override
597     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
598         // Get the `EditTexts` from the `dialogFragment`.
599         EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
600         EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
601
602         // Extract the strings from the `EditTexts`.
603         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
604         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
605
606         // Convert the favoriteIcon Bitmap to a byte array.
607         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
608         // `0` is for lossless compression (the only option for a PNG).
609         MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
610         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
611
612         // Display the new bookmark below the current items in the (0 indexed) list.
613         int newBookmarkDisplayOrder = bookmarksListView.getCount();
614
615         // Create the bookmark.
616         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
617
618         // Refresh the `ListView`.  `setSelection` scrolls to the bottom of the list.
619         updateBookmarksListView(currentFolder);
620         bookmarksListView.setSelection(newBookmarkDisplayOrder);
621     }
622
623     @Override
624     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
625         // Get `create_folder_name_edit_text` and extract the string.
626         EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
627         String folderNameString = createFolderNameEditText.getText().toString();
628
629         // Check to see if the folder already exists.
630         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(folderNameString);
631         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
632         bookmarkFolderCursor.close();
633         if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
634             String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
635             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
636         } else {  // Create the folder.
637             // Get the new folder icon `Bitmap`.
638             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
639             Bitmap folderIconBitmap;
640             if (defaultFolderIconRadioButton.isChecked()) {
641                 // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
642                 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
643                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
644                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
645                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
646             } else {  // Assign `favoriteIcon` from the `WebView`.
647                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
648             }
649
650             // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
651             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
652             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
653             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
654
655             // Move all the bookmarks down one in the display order.
656             for (int i = 0; i < bookmarksListView.getCount(); i++) {
657                 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
658                 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
659             }
660
661             // Create the folder, placing it at the top of the ListView
662             bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
663
664             // Refresh the ListView.
665             updateBookmarksListView(currentFolder);
666         }
667     }
668
669     @Override
670     public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
671         // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
672         long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
673         int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
674
675         // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
676         EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
677         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
678         EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
679         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
680
681         // Get `edit_bookmark_current_icon_radiobutton`.
682         RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
683
684         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
685             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
686         } else {  // Update the bookmark using the `WebView` favorite icon.
687             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
688             MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
689             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
690
691             //  Update the bookmark and the favorite icon.
692             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
693         }
694
695         // Close the contextual action mode.
696         contextualActionMode.finish();
697
698         // Refresh the `ListView`.  `setSelection` scrolls to the position of the bookmark that was edited.
699         updateBookmarksListView(currentFolder);
700         bookmarksListView.setSelection(selectedBookmarkPosition);
701     }
702
703     @Override
704     public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
705         // Get the new folder name.
706         EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
707         String newFolderNameString = editFolderNameEditText.getText().toString();
708
709         // Check to see if the new folder name is unique.
710         Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
711         int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
712         bookmarkFolderCursor.close();
713         if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
714             // Get a long array with the the database ID of the selected folder and convert it to an `int`.
715             long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
716             int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
717
718             // Get the `RadioButtons` from the `Dialog`.
719             RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
720             RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
721
722             // Check if the favorite icon has changed.
723             if (currentFolderIconRadioButton.isChecked()) {
724                 // Update the folder name if it has changed without modifying the favorite icon.
725                 if (!newFolderNameString.equals(oldFolderNameString)) {
726                     bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
727
728                     // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
729                     updateBookmarksListView(currentFolder);
730                     bookmarksListView.setSelection(selectedBookmarkPosition);
731                 }
732             } else {  // Update the folder icon.
733                 // Get the new folder icon `Bitmap`.
734                 Bitmap folderIconBitmap;
735                 if (defaultFolderIconRadioButton.isChecked()) {
736                     // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
737                     ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
738                     Drawable folderIconDrawable = folderIconImageView.getDrawable();
739                     BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
740                     folderIconBitmap = folderIconBitmapDrawable.getBitmap();
741                 } else {  // Get the web page icon `ImageView` from the `Dialog`.
742                     folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
743                 }
744
745                 // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
746                 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
747                 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
748                 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
749
750                 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
751
752                 // Refresh the `ListView`.  `setSelection` scrolls to the position of the folder that was edited.
753                 updateBookmarksListView(currentFolder);
754                 bookmarksListView.setSelection(selectedBookmarkPosition);
755             }
756         } else {  // Don't edit the folder because the new name is not unique.
757             String cannot_rename_folder = getResources().getString(R.string.cannot_save_folder) + " \"" + newFolderNameString + "\"";
758             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
759         }
760
761         // Close the contextual action mode.
762         contextualActionMode.finish();
763     }
764
765     @Override
766     public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
767         // Get the new folder database id.
768         ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
769         long[] newFolderLongArray = folderListView.getCheckedItemIds();
770
771         if (newFolderLongArray.length == 0) {  // No new folder was selected.
772             Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_INDEFINITE).show();
773         } else {  // Move the selected bookmarks.
774             // Get the new folder database ID.
775             int newFolderDatabaseId = (int) newFolderLongArray[0];
776
777             // Instantiate `newFolderName`.
778             String newFolderName;
779
780             if (newFolderDatabaseId == 0) {
781                 // The new folder is the home folder, represented as `""` in the database.
782                 newFolderName = "";
783             } else {
784                 // Get the new folder name from the database.
785                 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
786             }
787
788             // Get a long array with the the database ID of the selected bookmarks.
789             long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
790             for (long databaseIdLong : selectedBookmarksLongArray) {
791                 // Get `databaseIdInt` for each selected bookmark.
792                 int databaseIdInt = (int) databaseIdLong;
793
794                 // Move the selected bookmark to the new folder.
795                 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
796             }
797
798             // Refresh the `ListView`.
799             updateBookmarksListView(currentFolder);
800
801             // Close the contextual app bar.
802             contextualActionMode.finish();
803         }
804     }
805
806     private void updateBookmarksListView(String folderName) {
807         // Get a `Cursor` with the current contents of the bookmarks database.
808         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
809
810         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables `autoRequery`.
811         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
812             @Override
813             public View newView(Context context, Cursor cursor, ViewGroup parent) {
814                 // Inflate the individual item layout.  `false` does not attach it to the root.
815                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
816             }
817
818             @Override
819             public void bindView(View view, Context context, Cursor cursor) {
820                 // Get the favorite icon byte array from the `Cursor`.
821                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
822
823                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
824                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
825
826                 // Display the bitmap in `bookmarkFavoriteIcon`.
827                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
828                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
829
830
831                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
832                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
833                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
834                 bookmarkNameTextView.setText(bookmarkNameString);
835
836                 // Make the font bold for folders.
837                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
838                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
839                 } else {  // Reset the font to default for normal bookmarks.
840                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
841                 }
842             }
843         };
844
845         // Update the ListView.
846         bookmarksListView.setAdapter(bookmarksCursorAdapter);
847
848         // Set the AppBar title.
849         if (currentFolder.isEmpty()) {
850             appBar.setTitle(R.string.bookmarks);
851         } else {
852             appBar.setTitle(currentFolder);
853         }
854     }
855
856     private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
857         // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
858         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
859
860         // Setup `bookmarksCursorAdapter` with `this` context.  `false` disables autoRequery.
861         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
862             @Override
863             public View newView(Context context, Cursor cursor, ViewGroup parent) {
864                 // Inflate the individual item layout.  `false` does not attach it to the root.
865                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
866             }
867
868             @Override
869             public void bindView(View view, Context context, Cursor cursor) {
870                 // Get the favorite icon byte array from the cursor.
871                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
872
873                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
874                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
875
876                 // Display the bitmap in `bookmarkFavoriteIcon`.
877                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
878                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
879
880
881                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
882                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
883                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
884                 bookmarkNameTextView.setText(bookmarkNameString);
885
886                 // Make the font bold for folders.
887                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
888                     // The first argument is `null` because we don't want to change the font.
889                     bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
890                 } else {  // Reset the font to default.
891                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
892                 }
893             }
894         };
895
896         // Update the `ListView`.
897         bookmarksListView.setAdapter(bookmarksCursorAdapter);
898     }
899
900     private void deleteBookmarkFolderContents(int databaseId) {
901         // Get the name of the folder.
902         String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
903
904         // Get the contents of the folder.
905         Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
906
907         for (int i = 0; i < folderCursor.getCount(); i++) {
908             // Move `folderCursor` to the current row.
909             folderCursor.moveToPosition(i);
910
911             // Get the database ID of the item.
912             int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
913
914             // If this is a folder, delete the contents first.
915             if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
916                 deleteBookmarkFolderContents(itemDatabaseId);
917             }
918
919             bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);
920         }
921     }
922 }