2 * Copyright © 2016-2017 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.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;
62 import java.io.ByteArrayOutputStream;
64 public class BookmarksActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
65 MoveToFolderDialog.MoveToFolderListener {
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;
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;
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;
80 // `bookmarksListView` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
81 private ListView bookmarksListView;
83 // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
84 private ActionMode contextualActionMode;
86 // `selectedBookmarkPosition` is used in `onCreate()` and `onEditBookmarkSave()`.
87 private int selectedBookmarkPosition;
89 // `appBar` is used in `onCreate()` and `updateBookmarksListView()`.
90 private ActionBar appBar;
92 // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
93 private Cursor bookmarksCursor;
95 // `oldFolderName` is used in `onCreate()` and `onEditBookmarkFolderSave()`.
96 private String oldFolderNameString;
99 protected void onCreate(Bundle savedInstanceState) {
100 // Set the activity theme.
101 if (MainWebViewActivity.darkTheme) {
102 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
104 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
107 // Run the default commands.
108 super.onCreate(savedInstanceState);
110 // Set the content view.
111 setContentView(R.layout.bookmarks_coordinatorlayout);
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);
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);
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);
128 // Set currentFolder to the home folder, which is `""` in the database.
131 // Display the bookmarks in the ListView.
132 updateBookmarksListView(currentFolder);
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() {
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;
142 // Get the bookmark `Cursor` for this ID and move it to the first row.
143 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
144 bookmarkCursor.moveToFirst();
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));
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));
157 NavUtils.navigateUpFromSameTask(bookmarksActivity);
160 // Close the `Cursor`.
161 bookmarkCursor.close();
165 // `MultiChoiceModeListener` handles long clicks.
166 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
167 // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
168 MenuItem moveBookmarkUpMenuItem;
170 // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
171 MenuItem moveBookmarkDownMenuItem;
173 // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
174 MenuItem editBookmarkMenuItem;
176 // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
177 MenuItem selectAllBookmarksMenuItem;
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);
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);
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);
198 // Store `contextualActionMode` so we can close it programatically.
199 contextualActionMode = mode;
205 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
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();
214 // Calculate the number of selected bookmarks.
215 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
217 // Adjust the `mode` and the menu for the number of selected bookmarks.
218 if (numberOfSelectedBookmarks == 0) {
220 } else if (numberOfSelectedBookmarks == 1) {
221 // List the number of selected bookmarks in the subtitle.
222 mode.setSubtitle(getString(R.string.one_selected));
224 // Show the `Move Up`, `Move Down`, and `Edit` options.
225 moveBookmarkUpMenuItem.setVisible(true);
226 moveBookmarkDownMenuItem.setVisible(true);
227 editBookmarkMenuItem.setVisible(true);
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);
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);
242 // Set the icon according to the theme.
243 if (MainWebViewActivity.darkTheme) {
244 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
246 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
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);
257 // Set the icon according to the theme.
258 if (MainWebViewActivity.darkTheme) {
259 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
261 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
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));
268 // Hide non-applicable `MenuItems`.
269 moveBookmarkUpMenuItem.setVisible(false);
270 moveBookmarkDownMenuItem.setVisible(false);
271 editBookmarkMenuItem.setVisible(false);
274 // Do not show `Select All` if all the bookmarks are already checked.
275 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
276 selectAllBookmarksMenuItem.setVisible(false);
278 selectAllBookmarksMenuItem.setVisible(true);
283 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
284 // Get the menu item ID.
285 int menuItemId = item.getItemId();
287 // Instantiate the common variables.
288 int numberOfBookmarks;
289 int selectedBookmarkNewPosition;
290 SparseBooleanArray bookmarkPositionSparseBooleanArray;
292 switch (menuItemId) {
293 case R.id.move_bookmark_up:
294 // Get the array of checked bookmarks.
295 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
297 // Store the position of the selected bookmark.
298 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
300 // Initialize `selectedBookmarkNewPosition`.
301 selectedBookmarkNewPosition = 0;
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);
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);
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);
327 // Refresh the ListView.
328 updateBookmarksListView(currentFolder);
330 // Select the previously selected bookmark in the new location.
331 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
333 // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
334 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
338 case R.id.move_bookmark_down:
339 // Get the array of checked bookmarks.
340 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
342 // Store the position of the selected bookmark.
343 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
345 // Initialize `selectedBookmarkNewPosition`.
346 selectedBookmarkNewPosition = 0;
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);
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);
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);
372 // Refresh the ListView.
373 updateBookmarksListView(currentFolder);
375 // Select the previously selected bookmark in the new location.
376 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
378 // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
379 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
382 case R.id.move_to_folder:
383 // Store `checkedItemIds` for use by the `AlertDialog`.
384 checkedItemIds = bookmarksListView.getCheckedItemIds();
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));
391 case R.id.edit_bookmark:
392 // Get the array of checked bookmarks.
393 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
395 // Store the position of the selected bookmark.
396 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
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);
402 // Store `checkedItemIds` for use by the `AlertDialog`.
403 checkedItemIds = bookmarksListView.getCheckedItemIds();
406 // Save the current folder name.
407 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
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));
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));
419 case R.id.delete_bookmark:
420 // Get an array of the selected rows.
421 final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
423 // Get the array of checked bookmarks.
424 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
426 // Store the position of the first selected bookmark.
427 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
429 updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
431 // Scroll to where the first deleted bookmark was located.
432 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
434 // Create `snackbarMessage`.
435 String snackbarMessage;
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);
441 snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
445 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
446 .setAction(R.string.undo, new View.OnClickListener() {
448 public void onClick(View view) {
449 // Do nothing because everything will be handled by `onDismissed()` below.
452 .addCallback(new Snackbar.Callback() {
454 public void onDismissed(Snackbar snackbar, int 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);
461 // Scroll to where the first deleted bookmark was located.
462 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
465 // The `Snackbar` was dismissed without the `Undo` button being pushed.
467 // Delete each selected row.
468 for (long databaseIdLong : selectedBookmarksLongArray) {
469 // Convert `databaseIdLong` to an int.
470 int databaseIdInt = (int) databaseIdLong;
472 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
473 deleteBookmarkFolderContents(databaseIdInt);
476 // Delete `databaseIdInt`.
477 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
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);
485 // Move `bookmarksCursor` to the current bookmark position.
486 bookmarksCursor.moveToPosition(i);
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);
499 // Close the contextual app bar.
503 case R.id.context_menu_select_all_bookmarks:
504 numberOfBookmarks = bookmarksListView.getCount();
506 for (int i = 0; i < numberOfBookmarks; i++) {
507 bookmarksListView.setItemChecked(i, true);
511 // Consume the click.
516 public void onDestroyActionMode(ActionMode mode) {
521 // Set a FloatingActionButton for creating new bookmarks.
522 FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
523 createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
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));
534 public boolean onCreateOptionsMenu(Menu menu) {
536 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
543 public boolean onOptionsItemSelected(MenuItem menuItem) {
544 // Get the ID of the `MenuItem` that was selected.
545 int menuItemId = menuItem.getItemId();
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);
555 // Update `bookmarksListView`.
556 updateBookmarksListView(currentFolder);
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));
566 case R.id.options_menu_select_all_bookmarks:
567 int numberOfBookmarks = bookmarksListView.getCount();
569 for (int i = 0; i < numberOfBookmarks; i++) {
570 bookmarksListView.setItemChecked(i, true);
574 case R.id.bookmarks_database_view:
575 // Launch `BookmarksDatabaseViewActivity`.
576 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
577 startActivity(bookmarksDatabaseViewIntent);
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);
591 // Reload the `ListView`.
592 updateBookmarksListView(currentFolder);
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);
602 // Extract the strings from the `EditTexts`.
603 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
604 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
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();
612 // Display the new bookmark below the current items in the (0 indexed) list.
613 int newBookmarkDisplayOrder = bookmarksListView.getCount();
615 // Create the bookmark.
616 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
618 // Refresh the `ListView`. `setSelection` scrolls to the bottom of the list.
619 updateBookmarksListView(currentFolder);
620 bookmarksListView.setSelection(newBookmarkDisplayOrder);
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();
629 // Get the new folder icon `Bitmap`.
630 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
631 Bitmap folderIconBitmap;
632 if (defaultFolderIconRadioButton.isChecked()) {
633 // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
634 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
635 Drawable folderIconDrawable = folderIconImageView.getDrawable();
636 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
637 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
638 } else { // Assign `favoriteIcon` from the `WebView`.
639 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
642 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
643 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
644 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
645 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
647 // Move all the bookmarks down one in the display order.
648 for (int i = 0; i < bookmarksListView.getCount(); i++) {
649 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
650 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
653 // Create the folder, placing it at the top of the ListView
654 bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
656 // Refresh the ListView.
657 updateBookmarksListView(currentFolder);
661 public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
662 // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
663 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
664 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
666 // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
667 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
668 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
669 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
670 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
672 // Get `edit_bookmark_current_icon_radiobutton`.
673 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
675 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
676 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
677 } else { // Update the bookmark using the `WebView` favorite icon.
678 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
679 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
680 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
682 // Update the bookmark and the favorite icon.
683 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
686 // Close the contextual action mode.
687 contextualActionMode.finish();
689 // Refresh the `ListView`. `setSelection` scrolls to the position of the bookmark that was edited.
690 updateBookmarksListView(currentFolder);
691 bookmarksListView.setSelection(selectedBookmarkPosition);
695 public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
696 // Get the new folder name.
697 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
698 String newFolderNameString = editFolderNameEditText.getText().toString();
700 // Check to see if the new folder name is unique.
701 Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
702 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
703 bookmarkFolderCursor.close();
704 if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
705 // Get a long array with the the database ID of the selected folder and convert it to an `int`.
706 long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
707 int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
709 // Get the `RadioButtons` from the `Dialog`.
710 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
711 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
713 // Check if the favorite icon has changed.
714 if (currentFolderIconRadioButton.isChecked()) {
715 // Update the folder name if it has changed without modifying the favorite icon.
716 if (!newFolderNameString.equals(oldFolderNameString)) {
717 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
719 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
720 updateBookmarksListView(currentFolder);
721 bookmarksListView.setSelection(selectedBookmarkPosition);
723 } else { // Update the folder icon.
724 // Get the new folder icon `Bitmap`.
725 Bitmap folderIconBitmap;
726 if (defaultFolderIconRadioButton.isChecked()) {
727 // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
728 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
729 Drawable folderIconDrawable = folderIconImageView.getDrawable();
730 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
731 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
732 } else { // Get the web page icon `ImageView` from the `Dialog`.
733 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
736 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
737 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
738 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
739 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
741 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
743 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
744 updateBookmarksListView(currentFolder);
745 bookmarksListView.setSelection(selectedBookmarkPosition);
747 } else { // Don't edit the folder because the new name is not unique.
748 String cannot_rename_folder = getResources().getString(R.string.cannot_save_folder) + " \"" + newFolderNameString + "\"";
749 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
752 // Close the contextual action mode.
753 contextualActionMode.finish();
757 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
758 // Get the new folder database id.
759 ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
760 long[] newFolderLongArray = folderListView.getCheckedItemIds();
762 if (newFolderLongArray.length == 0) { // No new folder was selected.
763 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_INDEFINITE).show();
764 } else { // Move the selected bookmarks.
765 // Get the new folder database ID.
766 int newFolderDatabaseId = (int) newFolderLongArray[0];
768 // Instantiate `newFolderName`.
769 String newFolderName;
771 if (newFolderDatabaseId == 0) {
772 // The new folder is the home folder, represented as `""` in the database.
775 // Get the new folder name from the database.
776 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
779 // Get a long array with the the database ID of the selected bookmarks.
780 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
781 for (long databaseIdLong : selectedBookmarksLongArray) {
782 // Get `databaseIdInt` for each selected bookmark.
783 int databaseIdInt = (int) databaseIdLong;
785 // Move the selected bookmark to the new folder.
786 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
789 // Refresh the `ListView`.
790 updateBookmarksListView(currentFolder);
792 // Close the contextual app bar.
793 contextualActionMode.finish();
797 private void updateBookmarksListView(String folderName) {
798 // Get a `Cursor` with the current contents of the bookmarks database.
799 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
801 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables `autoRequery`.
802 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
804 public View newView(Context context, Cursor cursor, ViewGroup parent) {
805 // Inflate the individual item layout. `false` does not attach it to the root.
806 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
810 public void bindView(View view, Context context, Cursor cursor) {
811 // Get the favorite icon byte array from the `Cursor`.
812 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
814 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
815 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
817 // Display the bitmap in `bookmarkFavoriteIcon`.
818 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
819 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
822 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
823 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
824 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
825 bookmarkNameTextView.setText(bookmarkNameString);
827 // Make the font bold for folders.
828 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
829 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
830 } else { // Reset the font to default for normal bookmarks.
831 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
836 // Update the ListView.
837 bookmarksListView.setAdapter(bookmarksCursorAdapter);
839 // Set the AppBar title.
840 if (currentFolder.isEmpty()) {
841 appBar.setTitle(R.string.bookmarks);
843 appBar.setTitle(currentFolder);
847 private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
848 // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
849 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
851 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables autoRequery.
852 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
854 public View newView(Context context, Cursor cursor, ViewGroup parent) {
855 // Inflate the individual item layout. `false` does not attach it to the root.
856 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
860 public void bindView(View view, Context context, Cursor cursor) {
861 // Get the favorite icon byte array from the cursor.
862 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
864 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
865 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
867 // Display the bitmap in `bookmarkFavoriteIcon`.
868 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
869 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
872 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
873 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
874 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
875 bookmarkNameTextView.setText(bookmarkNameString);
877 // Make the font bold for folders.
878 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
879 // The first argument is `null` because we don't want to change the font.
880 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
881 } else { // Reset the font to default.
882 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
887 // Update the `ListView`.
888 bookmarksListView.setAdapter(bookmarksCursorAdapter);
891 private void deleteBookmarkFolderContents(int databaseId) {
892 // Get the name of the folder.
893 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
895 // Get the contents of the folder.
896 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
898 for (int i = 0; i < folderCursor.getCount(); i++) {
899 // Move `folderCursor` to the current row.
900 folderCursor.moveToPosition(i);
902 // Get the database ID of the item.
903 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
905 // If this is a folder, delete the contents first.
906 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
907 deleteBookmarkFolderContents(itemDatabaseId);
910 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);