2 * Copyright 2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.activities;
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;
54 import com.stoutner.privacybrowser.dialogs.EditBookmark;
55 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolder;
56 import com.stoutner.privacybrowser.dialogs.MoveToFolder;
57 import com.stoutner.privacybrowser.R;
58 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
59 import com.stoutner.privacybrowser.dialogs.CreateBookmark;
60 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolder;
62 import java.io.ByteArrayOutputStream;
64 public class Bookmarks extends AppCompatActivity implements CreateBookmark.CreateBookmarkListener,
65 CreateBookmarkFolder.CreateBookmarkFolderListener, EditBookmark.EditBookmarkListener,
66 EditBookmarkFolder.EditBookmarkFolderListener, MoveToFolder.MoveToFolderListener {
68 // `bookmarksDatabaseHelper` is public static so it can be accessed from `EditBookmark` and `MoveToFolder`. It is also used in `onCreate()`,
69 // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
70 public static BookmarksDatabaseHelper bookmarksDatabaseHelper;
72 // `currentFolder` is public static so it can be accessed from `MoveToFolder`.
73 // It is used in `onCreate`, `onOptionsItemSelected()`, `onCreateBookmarkCreate`, `onCreateBookmarkFolderCreate`, and `onEditBookmarkSave`.
74 public static String currentFolder;
76 // `checkedItemIds` is public static so it can be accessed from `EditBookmark`, `EditBookmarkFolder`, and `MoveToFolder`.
77 // It is also used in `onActionItemClicked`.
78 public static long[] checkedItemIds;
81 // `bookmarksListView` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
82 private ListView bookmarksListView;
84 // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
85 private ActionMode contextualActionMode;
87 // `selectedBookmarkPosition` is used in `onCreate()` and `onEditBookmarkSave()`.
88 private int selectedBookmarkPosition;
90 // `appBar` is used in `onCreate()` and `updateBookmarksListView()`.
91 private ActionBar appBar;
93 // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
94 private Cursor bookmarksCursor;
96 // `oldFolderName` is used in `onCreate()` and `onEditBookmarkFolderSave()`.
97 private String oldFolderNameString;
100 protected void onCreate(Bundle savedInstanceState) {
101 super.onCreate(savedInstanceState);
102 setContentView(R.layout.bookmarks_coordinatorlayout);
104 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
105 final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
106 setSupportActionBar(bookmarksAppBar);
108 // Display the home arrow on `SupportActionBar`.
109 appBar = getSupportActionBar();
110 assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
111 appBar.setDisplayHomeAsUpEnabled(true);
114 // Initialize the database handler and the ListView. `this` specifies the context. The two `null`s do not specify the database name or a `CursorFactory`.
115 // The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHelper`.
116 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
117 bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
119 // Set currentFolder to the home folder, which is null in the database.
122 // Display the bookmarks in the ListView.
123 updateBookmarksListView(currentFolder);
125 // 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.
126 final Activity bookmarksActivity = this;
127 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
129 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
130 // Convert the id from long to int to match the format of the bookmarks database.
131 int databaseID = (int) id;
133 // Get the bookmark `Cursor` and move it to the first row.
134 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
135 bookmarkCursor.moveToFirst();
137 // If the bookmark is a folder load its contents into the ListView.
138 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
139 // Update `currentFolder`.
140 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
142 // Reload the ListView with `currentFolder`.
143 updateBookmarksListView(currentFolder);
144 } else { // Load the URL into `mainWebView`.
145 // Get the bookmark URL and assign it to formattedUrlString. `mainWebView` will automatically reload when `Bookmarks` closes.
146 MainWebView.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
148 NavUtils.navigateUpFromSameTask(bookmarksActivity);
151 // Close the `Cursor`.
152 bookmarkCursor.close();
156 // `MultiChoiceModeListener` handles long clicks.
157 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
158 // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
159 MenuItem moveBookmarkUpMenuItem;
161 // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
162 MenuItem moveBookmarkDownMenuItem;
164 // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
165 MenuItem editBookmarkMenuItem;
167 // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
168 MenuItem selectAllBookmarksMenuItem;
171 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
172 // Inflate the menu for the contextual app bar and set the title.
173 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
176 if (currentFolder.isEmpty()) {
177 // Use `R.string.bookmarks` if we are in the home folder.
178 mode.setTitle(R.string.bookmarks);
179 } else { // Use the current folder name as the title.
180 mode.setTitle(currentFolder);
183 // Get a handle for MenuItems we need to selectively disable.
184 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
185 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
186 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
187 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
189 // Get a handle for `contextualActionMode` so we can close it programatically.
190 contextualActionMode = mode;
196 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
201 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
202 // Get an array of the selected bookmarks.
203 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
205 // Calculate the number of selected bookmarks.
206 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
208 // Sometimes Android forgets to close the contextual app bar when all the items are deselected.
209 if (numberOfSelectedBookmarks == 0) {
213 // List the number of selected bookmarks in the subtitle.
214 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
216 if (numberOfSelectedBookmarks == 1) {
217 // Show the `Move Up`, `Move Down`, and `Edit` option only if 1 bookmark is selected.
218 moveBookmarkUpMenuItem.setVisible(true);
219 moveBookmarkDownMenuItem.setVisible(true);
220 editBookmarkMenuItem.setVisible(true);
222 // Get the database IDs for the bookmarks.
223 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
224 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
225 // bookmarksListView is 0 indexed.
226 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
228 // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
229 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
230 moveBookmarkUpMenuItem.setEnabled(false);
231 moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_disabled);
232 } else { // Otherwise enable `moveBookmarkUpMenuItem`.
233 moveBookmarkUpMenuItem.setEnabled(true);
234 moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_enabled);
237 // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
238 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
239 moveBookmarkDownMenuItem.setEnabled(false);
240 moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_disabled);
241 } else { // Otherwise enable `moveBookmarkDownMenuItem`.
242 moveBookmarkDownMenuItem.setEnabled(true);
243 moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_enabled);
245 } else { // Hide the MenuItems because more than one bookmark is selected.
246 moveBookmarkUpMenuItem.setVisible(false);
247 moveBookmarkDownMenuItem.setVisible(false);
248 editBookmarkMenuItem.setVisible(false);
251 // Do not show `Select All` if all the bookmarks are already checked.
252 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
253 selectAllBookmarksMenuItem.setVisible(false);
255 selectAllBookmarksMenuItem.setVisible(true);
260 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
261 int menuItemId = item.getItemId();
263 // `numberOfBookmarks` is used in `R.id.move_bookmark_up_enabled`, `R.id.move_bookmark_down_enabled`, and `R.id.context_menu_select_all_bookmarks`.
264 int numberOfBookmarks;
266 // `selectedBookmarkLongArray` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
267 long[]selectedBookmarkLongArray;
268 // `selectedBookmarkDatabaseId` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
269 int selectedBookmarkDatabaseId;
270 // `selectedBookmarkNewPosition` is used in `R.id.move_bookmark_up` and `R.id.move_bookmark_down`.
271 int selectedBookmarkNewPosition;
272 // `bookmarkPositionSparseBooleanArray` is used in `R.id.edit_bookmark` and `R.id.delete_bookmark`.
273 SparseBooleanArray bookmarkPositionSparseBooleanArray;
275 switch (menuItemId) {
276 case R.id.move_bookmark_up:
277 // Get the selected bookmark database ID.
278 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
279 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
281 // Initialize `selectedBookmarkNewPosition`.
282 selectedBookmarkNewPosition = 0;
284 for (int i = 0; i < bookmarksListView.getCount(); i++) {
285 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
286 int nextBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i + 1);
288 if (databaseId == selectedBookmarkDatabaseId || nextBookmarkDatabaseId == selectedBookmarkDatabaseId) {
289 if (databaseId == selectedBookmarkDatabaseId) {
290 // Move the selected bookmark up one and store the new bookmark position.
291 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i - 1);
292 selectedBookmarkNewPosition = i - 1;
293 } else { // Move the bookmark above the selected bookmark down one.
294 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
297 // Reset the rest of the bookmarks' DISPLAY_ORDER to match the position in the ListView.
298 // This isn't necessary, but it clears out any stray values that might have crept into the database.
299 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i);
303 // Refresh the ListView.
304 updateBookmarksListView(currentFolder);
306 // Select the previously selected bookmark in the new location.
307 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
309 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
313 case R.id.move_bookmark_down:
314 // Get the selected bookmark database ID.
315 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
316 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
318 // Initialize `selectedBookmarkNewPosition`.
319 selectedBookmarkNewPosition = 0;
321 for (int i = 0; i <bookmarksListView.getCount(); i++) {
322 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
323 int previousBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i - 1);
325 if (databaseId == selectedBookmarkDatabaseId || previousBookmarkDatabaseId == selectedBookmarkDatabaseId) {
326 if (databaseId == selectedBookmarkDatabaseId) {
327 // Move the selected bookmark down one and store the new bookmark position.
328 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
329 selectedBookmarkNewPosition = i + 1;
330 } else { // Move the bookmark below the selected bookmark up one.
331 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i - 1);
334 // Reset the rest of the bookmark' DISPLAY_ORDER to match the position in the ListView.
335 // This isn't necessary, but it clears out any stray values that might have crept into the database.
336 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i);
340 // Refresh the ListView.
341 updateBookmarksListView(currentFolder);
343 // Select the previously selected bookmark in the new location.
344 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
346 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
349 case R.id.move_to_folder:
350 // Store `checkedItemIds` for use by the `AlertDialog`.
351 checkedItemIds = bookmarksListView.getCheckedItemIds();
353 // Show the `MoveToFolder` `AlertDialog` and name the instance `@string/move_to_folder
354 AppCompatDialogFragment moveToFolderDialog = new MoveToFolder();
355 moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
358 case R.id.edit_bookmark:
359 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
360 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
361 for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
362 // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
363 if (bookmarkPositionSparseBooleanArray.valueAt(i))
364 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
367 // Move to the selected database ID and find out if it is a folder.
368 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
369 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
371 // Store `checkedItemIds` for use by the `AlertDialog`.
372 checkedItemIds = bookmarksListView.getCheckedItemIds();
375 // Save the current folder name.
376 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
378 // Show the `EditBookmarkFolder` `AlertDialog` and name the instance `@string/edit_folder`.
379 AppCompatDialogFragment editFolderDialog = new EditBookmarkFolder();
380 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
382 // Show the `EditBookmark` `AlertDialog` and name the instance `@string/edit_bookmark`.
383 AppCompatDialogFragment editBookmarkDialog = new EditBookmark();
384 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
388 case R.id.delete_bookmark:
389 // Get an array of the selected rows.
390 final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
392 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
393 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
394 for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
395 // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
396 if (bookmarkPositionSparseBooleanArray.valueAt(i))
397 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
400 updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
402 // Scroll to where the deleted bookmark was located.
403 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
405 String snackbarMessage;
407 // Determine how many items are in the array and prepare an appropriate Snackbar message.
408 if (selectedBookmarksLongArray.length == 1) {
409 snackbarMessage = getString(R.string.one_bookmark_deleted);
411 snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
415 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
416 .setAction(R.string.undo, new View.OnClickListener() {
418 public void onClick(View view) {
419 // Do nothing because everything will be handled by `onDismissed()` below.
422 .setCallback(new Snackbar.Callback() {
424 public void onDismissed(Snackbar snackbar, int event) {
425 // Android Studio wants to see entries for every possible `Snackbar.Callback` even if they aren't used.
427 // The user pushed the "Undo" button.
428 case Snackbar.Callback.DISMISS_EVENT_ACTION:
429 // Refresh the ListView to show the rows again.
430 updateBookmarksListView(currentFolder);
432 // Scroll to where the deleted bookmark was located.
433 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
437 case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE:
438 // Do nothing and let the default behavior run.
440 case Snackbar.Callback.DISMISS_EVENT_MANUAL:
441 // Do nothing and let the default behavior run.
443 case Snackbar.Callback.DISMISS_EVENT_SWIPE:
444 // Do nothing and let the default behavior run.
446 case Snackbar.Callback.DISMISS_EVENT_TIMEOUT:
447 // Do nothing and let the default behavior run.
449 // The Snackbar was dismissed without the "Undo" button being pushed.
451 // Delete each selected row.
452 for (long databaseIdLong : selectedBookmarksLongArray) {
453 // Convert `databaseIdLong` to an int.
454 int databaseIdInt = (int) databaseIdLong;
456 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
457 deleteBookmarkFolderContents(databaseIdInt);
460 // Delete `databaseIdInt`.
461 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
469 // Close the contextual app bar.
473 case R.id.context_menu_select_all_bookmarks:
474 numberOfBookmarks = bookmarksListView.getCount();
476 for (int i = 0; i < numberOfBookmarks; i++) {
477 bookmarksListView.setItemChecked(i, true);
481 // Consume the click.
486 public void onDestroyActionMode(ActionMode mode) {
491 // Set a FloatingActionButton for creating new bookmarks.
492 FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
493 createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
495 public void onClick(View view) {
496 // Show the `CreateBookmark` `AlertDialog` and name the instance `@string/create_bookmark`.
497 AppCompatDialogFragment createBookmarkDialog = new CreateBookmark();
498 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
504 public boolean onCreateOptionsMenu(Menu menu) {
506 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
512 public boolean onPrepareOptionsMenu(Menu menu) {
513 super.onPrepareOptionsMenu(menu);
519 public boolean onOptionsItemSelected(MenuItem menuItem) {
520 int menuItemId = menuItem.getItemId();
522 switch (menuItemId) {
523 case android.R.id.home:
524 if (currentFolder.isEmpty()) { // Exit Bookmarks if currently in the home folder.
525 NavUtils.navigateUpFromSameTask(this);
526 } else { // Navigate up one folder.
527 // Place the former parent folder in `currentFolder`.
528 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
530 // Exit Bookmarks if currently in the home folder.
531 updateBookmarksListView(currentFolder);
535 case R.id.create_folder:
536 // Show the `CreateBookmarkFolder` `AlertDialog` and name the instance `@string/create_folder`.
537 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolder();
538 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
541 case R.id.options_menu_select_all_bookmarks:
542 int numberOfBookmarks = bookmarksListView.getCount();
544 for (int i = 0; i < numberOfBookmarks; i++) {
545 bookmarksListView.setItemChecked(i, true);
549 case R.id.bookmarks_database_view:
550 // Launch `BookmarksDatabaseView`.
551 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseView.class);
552 startActivity(bookmarksDatabaseViewIntent);
559 public void onBackPressed() {
560 if (currentFolder.isEmpty()) { // Exit Bookmarks if currently in the home folder.
561 super.onBackPressed();
562 } else { // Navigate up one folder.
563 // Place the former parent folder in `currentFolder`.
564 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
566 // Reload the `ListView`.
567 updateBookmarksListView(currentFolder);
572 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
573 // Get the `EditText`s from the `createBookmarkDialogFragment` and extract the strings.
574 EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
575 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
576 EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
577 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
579 // Convert the favoriteIcon Bitmap to a byte array.
580 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
581 // `0` is for lossless compression (the only option for a PNG).
582 MainWebView.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
583 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
585 // Display the new bookmark below the current items in the (0 indexed) list.
586 int newBookmarkDisplayOrder = bookmarksListView.getCount();
588 // Create the bookmark.
589 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
591 // Refresh the ListView. `setSelection` scrolls to the bottom of the list.
592 updateBookmarksListView(currentFolder);
593 bookmarksListView.setSelection(newBookmarkDisplayOrder);
597 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
598 // Get `create_folder_name_edit_text` and extract the string.
599 EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
600 String folderNameString = createFolderNameEditText.getText().toString();
602 // Check to see if the folder already exists.
603 Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(folderNameString);
604 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
605 bookmarkFolderCursor.close();
606 if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
607 String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
608 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
609 } else { // Create the folder.
610 // Get the new folder icon `Bitmap`.
611 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
612 Bitmap folderIconBitmap;
613 if (defaultFolderIconRadioButton.isChecked()) {
614 // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
615 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
616 Drawable folderIconDrawable = folderIconImageView.getDrawable();
617 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
618 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
619 } else { // Assign `favoriteIcon` from the `WebView`.
620 folderIconBitmap = MainWebView.favoriteIcon;
623 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
624 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
625 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
626 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
628 // Move all the bookmarks down one in the display order.
629 for (int i = 0; i < bookmarksListView.getCount(); i++) {
630 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
631 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
634 // Create the folder, placing it at the top of the ListView
635 bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
637 // Refresh the ListView.
638 updateBookmarksListView(currentFolder);
643 public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
644 // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
645 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
646 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
648 // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
649 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
650 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
651 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
652 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
654 // Get `edit_bookmark_current_icon_radiobutton`.
655 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
657 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
658 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
659 } else { // Update the bookmark using the `WebView` favorite icon.
660 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
661 MainWebView.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
662 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
664 // Update the bookmark and the favorite icon.
665 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
668 // Close the contextual action mode.
669 contextualActionMode.finish();
671 // Refresh the `ListView`. `setSelection` scrolls to the position of the bookmark that was edited.
672 updateBookmarksListView(currentFolder);
673 bookmarksListView.setSelection(selectedBookmarkPosition);
677 public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
678 // Get the new folder name.
679 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
680 String newFolderNameString = editFolderNameEditText.getText().toString();
682 // Check to see if the new folder name is unique.
683 Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
684 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
685 bookmarkFolderCursor.close();
686 if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
687 // Get a long array with the the database ID of the selected folder and convert it to an `int`.
688 long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
689 int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
691 // Get the `RadioButtons` from the `Dialog`.
692 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
693 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
695 // Check if the favorite icon has changed.
696 if (currentFolderIconRadioButton.isChecked()) {
697 // Update the folder name if it has changed without modifying the favorite icon.
698 if (!newFolderNameString.equals(oldFolderNameString)) {
699 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
701 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
702 updateBookmarksListView(currentFolder);
703 bookmarksListView.setSelection(selectedBookmarkPosition);
705 } else { // Update the folder icon.
706 // Get the new folder icon `Bitmap`.
707 Bitmap folderIconBitmap;
708 if (defaultFolderIconRadioButton.isChecked()) {
709 // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
710 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
711 Drawable folderIconDrawable = folderIconImageView.getDrawable();
712 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
713 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
714 } else { // Get the web page icon `ImageView` from the `Dialog`.
715 folderIconBitmap = MainWebView.favoriteIcon;
718 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
719 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
720 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
721 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
723 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
725 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
726 updateBookmarksListView(currentFolder);
727 bookmarksListView.setSelection(selectedBookmarkPosition);
729 } else { // Don't edit the folder because the new name is not unique.
730 String cannot_rename_folder = getResources().getString(R.string.cannot_rename_folder) + " \"" + newFolderNameString + "\"";
731 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
734 // Close the contextual action mode.
735 contextualActionMode.finish();
739 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
740 // Get the new folder database id.
741 ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
742 long[] newFolderLongArray = folderListView.getCheckedItemIds();
744 if (newFolderLongArray.length == 0) { // No new folder was selected.
745 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_LONG).show();
746 } else { // Move the selected bookmarks.
747 // Get the new folder database ID.
748 int newFolderDatabaseId = (int) newFolderLongArray[0];
750 // Instantiate `newFolderName`.
751 String newFolderName;
753 if (newFolderDatabaseId == 0) {
754 // The new folder is the home folder, represented as `""` in the database.
757 // Get the new folder name from the database.
758 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
761 // Get a long array with the the database ID of the selected bookmarks.
762 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
763 for (long databaseIdLong : selectedBookmarksLongArray) {
764 // Get `databaseIdInt` for each selected bookmark.
765 int databaseIdInt = (int) databaseIdLong;
767 // Move the selected bookmark to the new folder.
768 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
771 // Refresh the `ListView`.
772 updateBookmarksListView(currentFolder);
774 // Close the contextual app bar.
775 contextualActionMode.finish();
779 private void updateBookmarksListView(String folderName) {
780 // Get a `Cursor` with the current contents of the bookmarks database.
781 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
783 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables autoRequery.
784 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
786 public View newView(Context context, Cursor cursor, ViewGroup parent) {
787 // Inflate the individual item layout. `false` does not attach it to the root.
788 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
792 public void bindView(View view, Context context, Cursor cursor) {
793 // Get the favorite icon byte array from the `Cursor`.
794 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
796 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
797 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
799 // Display the bitmap in `bookmarkFavoriteIcon`.
800 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
801 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
804 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
805 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
806 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
807 bookmarkNameTextView.setText(bookmarkNameString);
809 // Make the font bold for folders.
810 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
811 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
812 } else { // Reset the font to default for normal bookmarks.
813 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
818 // Update the ListView.
819 bookmarksListView.setAdapter(bookmarksCursorAdapter);
821 // Set the AppBar title.
822 if (currentFolder.isEmpty()) {
823 appBar.setTitle(R.string.bookmarks);
825 appBar.setTitle(currentFolder);
829 private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
830 // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
831 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
833 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables autoRequery.
834 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
836 public View newView(Context context, Cursor cursor, ViewGroup parent) {
837 // Inflate the individual item layout. `false` does not attach it to the root.
838 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
842 public void bindView(View view, Context context, Cursor cursor) {
843 // Get the favorite icon byte array from the cursor.
844 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
846 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
847 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
849 // Display the bitmap in `bookmarkFavoriteIcon`.
850 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
851 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
854 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
855 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
856 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
857 bookmarkNameTextView.setText(bookmarkNameString);
859 // Make the font bold for folders.
860 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
861 // The first argument is `null` because we don't want to change the font.
862 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
863 } else { // Reset the font to default.
864 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
869 // Update the ListView.
870 bookmarksListView.setAdapter(bookmarksCursorAdapter);
873 private void deleteBookmarkFolderContents(int databaseId) {
874 // Get the name of the folder.
875 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
877 // Get the contents of the folder.
878 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
880 for (int i = 0; i < folderCursor.getCount(); i++) {
881 // Move `folderCursor` to the current row.
882 folderCursor.moveToPosition(i);
884 // Get the database ID of the item.
885 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
887 // If this is a folder, delete the contents first.
888 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
889 deleteBookmarkFolderContents(itemDatabaseId);
892 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);