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