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 super.onCreate(savedInstanceState);
101 setContentView(R.layout.bookmarks_coordinatorlayout);
103 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
104 final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
105 setSupportActionBar(bookmarksAppBar);
107 // Display the home arrow on `SupportActionBar`.
108 appBar = getSupportActionBar();
109 assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
110 appBar.setDisplayHomeAsUpEnabled(true);
113 // Initialize the database handler and the `ListView`. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
114 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
115 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
116 bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
118 // Set currentFolder to the home folder, which is `""` in the database.
121 // Display the bookmarks in the ListView.
122 updateBookmarksListView(currentFolder);
124 // 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.
125 final Activity bookmarksActivity = this;
126 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
128 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
129 // Convert the id from long to int to match the format of the bookmarks database.
130 int databaseID = (int) id;
132 // Get the bookmark `Cursor` for this ID and move it to the first row.
133 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
134 bookmarkCursor.moveToFirst();
136 // If the bookmark is a folder load its contents into the ListView.
137 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
138 // Update `currentFolder`.
139 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
141 // Reload the ListView with `currentFolder`.
142 updateBookmarksListView(currentFolder);
143 } else { // Load the URL into `mainWebView`.
144 // Get the bookmark URL and assign it to formattedUrlString. `mainWebView` will automatically reload when `BookmarksActivity` closes.
145 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
147 NavUtils.navigateUpFromSameTask(bookmarksActivity);
150 // Close the `Cursor`.
151 bookmarkCursor.close();
155 // `MultiChoiceModeListener` handles long clicks.
156 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
157 // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
158 MenuItem moveBookmarkUpMenuItem;
160 // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
161 MenuItem moveBookmarkDownMenuItem;
163 // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
164 MenuItem editBookmarkMenuItem;
166 // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
167 MenuItem selectAllBookmarksMenuItem;
170 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
171 // Inflate the menu for the contextual app bar and set the title.
172 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
175 if (currentFolder.isEmpty()) {
176 // Use `R.string.bookmarks` if we are in the home folder.
177 mode.setTitle(R.string.bookmarks);
178 } else { // Use the current folder name as the title.
179 mode.setTitle(currentFolder);
182 // Get a handle for MenuItems we need to selectively disable.
183 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
184 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
185 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
186 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
188 // Get a handle for `contextualActionMode` so we can close it programatically.
189 contextualActionMode = mode;
195 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
200 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
201 // Get an array of the selected bookmarks.
202 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
204 // Calculate the number of selected bookmarks.
205 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
207 // Adjust the `mode` and the menu for the number of selected bookmarks.
208 if (numberOfSelectedBookmarks == 0) {
210 } else if (numberOfSelectedBookmarks == 1) {
211 // List the number of selected bookmarks in the subtitle.
212 mode.setSubtitle(getString(R.string.one_selected));
214 // Show the `Move Up`, `Move Down`, and `Edit` options.
215 moveBookmarkUpMenuItem.setVisible(true);
216 moveBookmarkDownMenuItem.setVisible(true);
217 editBookmarkMenuItem.setVisible(true);
219 // Get the database IDs for the bookmarks.
220 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
221 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
222 // bookmarksListView is 0 indexed.
223 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
225 // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
226 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
227 moveBookmarkUpMenuItem.setEnabled(false);
228 moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_disabled);
229 } else { // Otherwise enable `moveBookmarkUpMenuItem`.
230 moveBookmarkUpMenuItem.setEnabled(true);
231 moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_enabled);
234 // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
235 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
236 moveBookmarkDownMenuItem.setEnabled(false);
237 moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_disabled);
238 } else { // Otherwise enable `moveBookmarkDownMenuItem`.
239 moveBookmarkDownMenuItem.setEnabled(true);
240 moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_enabled);
242 } else { // More than one bookmark is selected.
243 // List the number of selected bookmarks in the subtitle.
244 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
246 // Hide non-applicable `MenuItems`.
247 moveBookmarkUpMenuItem.setVisible(false);
248 moveBookmarkDownMenuItem.setVisible(false);
249 editBookmarkMenuItem.setVisible(false);
252 // Do not show `Select All` if all the bookmarks are already checked.
253 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
254 selectAllBookmarksMenuItem.setVisible(false);
256 selectAllBookmarksMenuItem.setVisible(true);
261 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
262 int menuItemId = item.getItemId();
264 // `numberOfBookmarks` is used in `R.id.move_bookmark_up_enabled`, `R.id.move_bookmark_down_enabled`, and `R.id.context_menu_select_all_bookmarks`.
265 int numberOfBookmarks;
267 // `selectedBookmarkLongArray` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
268 long[]selectedBookmarkLongArray;
269 // `selectedBookmarkDatabaseId` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
270 int selectedBookmarkDatabaseId;
271 // `selectedBookmarkNewPosition` is used in `R.id.move_bookmark_up` and `R.id.move_bookmark_down`.
272 int selectedBookmarkNewPosition;
273 // `bookmarkPositionSparseBooleanArray` is used in `R.id.edit_bookmark` and `R.id.delete_bookmark`.
274 SparseBooleanArray bookmarkPositionSparseBooleanArray;
276 switch (menuItemId) {
277 case R.id.move_bookmark_up:
278 // Get the selected bookmark database ID.
279 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
280 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
282 // Initialize `selectedBookmarkNewPosition`.
283 selectedBookmarkNewPosition = 0;
285 for (int i = 0; i < bookmarksListView.getCount(); i++) {
286 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
287 int nextBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i + 1);
289 if (databaseId == selectedBookmarkDatabaseId || nextBookmarkDatabaseId == selectedBookmarkDatabaseId) {
290 if (databaseId == selectedBookmarkDatabaseId) {
291 // Move the selected bookmark up one and store the new bookmark position.
292 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i - 1);
293 selectedBookmarkNewPosition = i - 1;
294 } else { // Move the bookmark above the selected bookmark down one.
295 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
298 // Reset the rest of the bookmarks' DISPLAY_ORDER to match the position in the ListView.
299 // This isn't necessary, but it clears out any stray values that might have crept into the database.
300 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i);
304 // Refresh the ListView.
305 updateBookmarksListView(currentFolder);
307 // Select the previously selected bookmark in the new location.
308 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
310 // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
311 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
315 case R.id.move_bookmark_down:
316 // Get the selected bookmark database ID.
317 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
318 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
320 // Initialize `selectedBookmarkNewPosition`.
321 selectedBookmarkNewPosition = 0;
323 for (int i = 0; i <bookmarksListView.getCount(); i++) {
324 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
325 int previousBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i - 1);
327 if (databaseId == selectedBookmarkDatabaseId || previousBookmarkDatabaseId == selectedBookmarkDatabaseId) {
328 if (databaseId == selectedBookmarkDatabaseId) {
329 // Move the selected bookmark down one and store the new bookmark position.
330 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
331 selectedBookmarkNewPosition = i + 1;
332 } else { // Move the bookmark below the selected bookmark up one.
333 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i - 1);
336 // Reset the rest of the bookmark' DISPLAY_ORDER to match the position in the ListView.
337 // This isn't necessary, but it clears out any stray values that might have crept into the database.
338 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i);
342 // Refresh the ListView.
343 updateBookmarksListView(currentFolder);
345 // Select the previously selected bookmark in the new location.
346 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
348 // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
349 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
352 case R.id.move_to_folder:
353 // Store `checkedItemIds` for use by the `AlertDialog`.
354 checkedItemIds = bookmarksListView.getCheckedItemIds();
356 // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
357 AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
358 moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
361 case R.id.edit_bookmark:
362 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
363 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
364 for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
365 // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
366 if (bookmarkPositionSparseBooleanArray.valueAt(i))
367 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
370 // Move to the selected database ID and find out if it is a folder.
371 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
372 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
374 // Store `checkedItemIds` for use by the `AlertDialog`.
375 checkedItemIds = bookmarksListView.getCheckedItemIds();
378 // Save the current folder name.
379 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
381 // Show the `EditBookmarkFolderDialog` `AlertDialog` and name the instance `@string/edit_folder`.
382 AppCompatDialogFragment editFolderDialog = new EditBookmarkFolderDialog();
383 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
385 // Show the `EditBookmarkDialog` `AlertDialog` and name the instance `@string/edit_bookmark`.
386 AppCompatDialogFragment editBookmarkDialog = new EditBookmarkDialog();
387 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
391 case R.id.delete_bookmark:
392 // Get an array of the selected rows.
393 final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
395 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
396 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
397 for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
398 // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
399 if (bookmarkPositionSparseBooleanArray.valueAt(i))
400 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
403 updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
405 // Scroll to where the deleted bookmark was located.
406 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
408 // Initialize `snackbarMessage`.
409 String snackbarMessage;
411 // Determine how many items are in the array and prepare an appropriate Snackbar message.
412 if (selectedBookmarksLongArray.length == 1) {
413 snackbarMessage = getString(R.string.one_bookmark_deleted);
415 snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
419 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
420 .setAction(R.string.undo, new View.OnClickListener() {
422 public void onClick(View view) {
423 // Do nothing because everything will be handled by `onDismissed()` below.
426 .addCallback(new Snackbar.Callback() {
428 public void onDismissed(Snackbar snackbar, int event) {
430 // The user pushed the `Undo` button.
431 case Snackbar.Callback.DISMISS_EVENT_ACTION:
432 // Refresh the ListView to show the rows again.
433 updateBookmarksListView(currentFolder);
435 // Scroll to where the deleted bookmark was located.
436 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
439 // The `Snackbar` was dismissed without the `Undo` button being pushed.
441 // Delete each selected row.
442 for (long databaseIdLong : selectedBookmarksLongArray) {
443 // Convert `databaseIdLong` to an int.
444 int databaseIdInt = (int) databaseIdLong;
446 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
447 deleteBookmarkFolderContents(databaseIdInt);
450 // Delete `databaseIdInt`.
451 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
459 // Close the contextual app bar.
463 case R.id.context_menu_select_all_bookmarks:
464 numberOfBookmarks = bookmarksListView.getCount();
466 for (int i = 0; i < numberOfBookmarks; i++) {
467 bookmarksListView.setItemChecked(i, true);
471 // Consume the click.
476 public void onDestroyActionMode(ActionMode mode) {
481 // Set a FloatingActionButton for creating new bookmarks.
482 FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
483 createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
485 public void onClick(View view) {
486 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
487 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
488 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
494 public boolean onCreateOptionsMenu(Menu menu) {
496 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
503 public boolean onOptionsItemSelected(MenuItem menuItem) {
504 // Get the ID of the `MenuItem` that was selected.
505 int menuItemId = menuItem.getItemId();
507 switch (menuItemId) {
508 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
509 if (currentFolder.isEmpty()) { // Exit BookmarksActivity if currently in the home folder.
510 NavUtils.navigateUpFromSameTask(this);
511 } else { // Navigate up one folder.
512 // Place the former parent folder in `currentFolder`.
513 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
515 // Update `bookmarksListView`.
516 updateBookmarksListView(currentFolder);
520 case R.id.create_folder:
521 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
522 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
523 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
526 case R.id.options_menu_select_all_bookmarks:
527 int numberOfBookmarks = bookmarksListView.getCount();
529 for (int i = 0; i < numberOfBookmarks; i++) {
530 bookmarksListView.setItemChecked(i, true);
534 case R.id.bookmarks_database_view:
535 // Launch `BookmarksDatabaseViewActivity`.
536 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
537 startActivity(bookmarksDatabaseViewIntent);
544 public void onBackPressed() {
545 if (currentFolder.isEmpty()) { // Exit BookmarksActivity if currently in the home folder.
546 super.onBackPressed();
547 } else { // Navigate up one folder.
548 // Place the former parent folder in `currentFolder`.
549 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
551 // Reload the `ListView`.
552 updateBookmarksListView(currentFolder);
557 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
558 // Get the `EditTexts` from the `dialogFragment`.
559 EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
560 EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
562 // Extract the strings from the `EditTexts`.
563 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
564 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
566 // Convert the favoriteIcon Bitmap to a byte array.
567 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
568 // `0` is for lossless compression (the only option for a PNG).
569 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
570 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
572 // Display the new bookmark below the current items in the (0 indexed) list.
573 int newBookmarkDisplayOrder = bookmarksListView.getCount();
575 // Create the bookmark.
576 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
578 // Refresh the `ListView`. `setSelection` scrolls to the bottom of the list.
579 updateBookmarksListView(currentFolder);
580 bookmarksListView.setSelection(newBookmarkDisplayOrder);
584 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
585 // Get `create_folder_name_edit_text` and extract the string.
586 EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
587 String folderNameString = createFolderNameEditText.getText().toString();
589 // Check to see if the folder already exists.
590 Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(folderNameString);
591 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
592 bookmarkFolderCursor.close();
593 if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
594 String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
595 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
596 } else { // Create the folder.
597 // Get the new folder icon `Bitmap`.
598 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
599 Bitmap folderIconBitmap;
600 if (defaultFolderIconRadioButton.isChecked()) {
601 // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
602 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
603 Drawable folderIconDrawable = folderIconImageView.getDrawable();
604 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
605 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
606 } else { // Assign `favoriteIcon` from the `WebView`.
607 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
610 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
611 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
612 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
613 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
615 // Move all the bookmarks down one in the display order.
616 for (int i = 0; i < bookmarksListView.getCount(); i++) {
617 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
618 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
621 // Create the folder, placing it at the top of the ListView
622 bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
624 // Refresh the ListView.
625 updateBookmarksListView(currentFolder);
630 public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
631 // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
632 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
633 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
635 // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
636 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
637 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
638 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
639 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
641 // Get `edit_bookmark_current_icon_radiobutton`.
642 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
644 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
645 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
646 } else { // Update the bookmark using the `WebView` favorite icon.
647 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
648 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
649 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
651 // Update the bookmark and the favorite icon.
652 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
655 // Close the contextual action mode.
656 contextualActionMode.finish();
658 // Refresh the `ListView`. `setSelection` scrolls to the position of the bookmark that was edited.
659 updateBookmarksListView(currentFolder);
660 bookmarksListView.setSelection(selectedBookmarkPosition);
664 public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
665 // Get the new folder name.
666 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
667 String newFolderNameString = editFolderNameEditText.getText().toString();
669 // Check to see if the new folder name is unique.
670 Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
671 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
672 bookmarkFolderCursor.close();
673 if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
674 // Get a long array with the the database ID of the selected folder and convert it to an `int`.
675 long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
676 int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
678 // Get the `RadioButtons` from the `Dialog`.
679 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
680 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
682 // Check if the favorite icon has changed.
683 if (currentFolderIconRadioButton.isChecked()) {
684 // Update the folder name if it has changed without modifying the favorite icon.
685 if (!newFolderNameString.equals(oldFolderNameString)) {
686 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
688 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
689 updateBookmarksListView(currentFolder);
690 bookmarksListView.setSelection(selectedBookmarkPosition);
692 } else { // Update the folder icon.
693 // Get the new folder icon `Bitmap`.
694 Bitmap folderIconBitmap;
695 if (defaultFolderIconRadioButton.isChecked()) {
696 // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
697 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
698 Drawable folderIconDrawable = folderIconImageView.getDrawable();
699 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
700 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
701 } else { // Get the web page icon `ImageView` from the `Dialog`.
702 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
705 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
706 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
707 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
708 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
710 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
712 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
713 updateBookmarksListView(currentFolder);
714 bookmarksListView.setSelection(selectedBookmarkPosition);
716 } else { // Don't edit the folder because the new name is not unique.
717 String cannot_rename_folder = getResources().getString(R.string.cannot_save_folder) + " \"" + newFolderNameString + "\"";
718 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
721 // Close the contextual action mode.
722 contextualActionMode.finish();
726 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
727 // Get the new folder database id.
728 ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
729 long[] newFolderLongArray = folderListView.getCheckedItemIds();
731 if (newFolderLongArray.length == 0) { // No new folder was selected.
732 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_INDEFINITE).show();
733 } else { // Move the selected bookmarks.
734 // Get the new folder database ID.
735 int newFolderDatabaseId = (int) newFolderLongArray[0];
737 // Instantiate `newFolderName`.
738 String newFolderName;
740 if (newFolderDatabaseId == 0) {
741 // The new folder is the home folder, represented as `""` in the database.
744 // Get the new folder name from the database.
745 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
748 // Get a long array with the the database ID of the selected bookmarks.
749 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
750 for (long databaseIdLong : selectedBookmarksLongArray) {
751 // Get `databaseIdInt` for each selected bookmark.
752 int databaseIdInt = (int) databaseIdLong;
754 // Move the selected bookmark to the new folder.
755 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
758 // Refresh the `ListView`.
759 updateBookmarksListView(currentFolder);
761 // Close the contextual app bar.
762 contextualActionMode.finish();
766 private void updateBookmarksListView(String folderName) {
767 // Get a `Cursor` with the current contents of the bookmarks database.
768 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
770 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables `autoRequery`.
771 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
773 public View newView(Context context, Cursor cursor, ViewGroup parent) {
774 // Inflate the individual item layout. `false` does not attach it to the root.
775 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
779 public void bindView(View view, Context context, Cursor cursor) {
780 // Get the favorite icon byte array from the `Cursor`.
781 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
783 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
784 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
786 // Display the bitmap in `bookmarkFavoriteIcon`.
787 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
788 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
791 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
792 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
793 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
794 bookmarkNameTextView.setText(bookmarkNameString);
796 // Make the font bold for folders.
797 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
798 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
799 } else { // Reset the font to default for normal bookmarks.
800 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
805 // Update the ListView.
806 bookmarksListView.setAdapter(bookmarksCursorAdapter);
808 // Set the AppBar title.
809 if (currentFolder.isEmpty()) {
810 appBar.setTitle(R.string.bookmarks);
812 appBar.setTitle(currentFolder);
816 private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
817 // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
818 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
820 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables autoRequery.
821 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
823 public View newView(Context context, Cursor cursor, ViewGroup parent) {
824 // Inflate the individual item layout. `false` does not attach it to the root.
825 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
829 public void bindView(View view, Context context, Cursor cursor) {
830 // Get the favorite icon byte array from the cursor.
831 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
833 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
834 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
836 // Display the bitmap in `bookmarkFavoriteIcon`.
837 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
838 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
841 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
842 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
843 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
844 bookmarkNameTextView.setText(bookmarkNameString);
846 // Make the font bold for folders.
847 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
848 // The first argument is `null` because we don't want to change the font.
849 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
850 } else { // Reset the font to default.
851 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
856 // Update the `ListView`.
857 bookmarksListView.setAdapter(bookmarksCursorAdapter);
860 private void deleteBookmarkFolderContents(int databaseId) {
861 // Get the name of the folder.
862 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
864 // Get the contents of the folder.
865 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
867 for (int i = 0; i < folderCursor.getCount(); i++) {
868 // Move `folderCursor` to the current row.
869 folderCursor.moveToPosition(i);
871 // Get the database ID of the item.
872 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
874 // If this is a folder, delete the contents first.
875 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
876 deleteBookmarkFolderContents(itemDatabaseId);
879 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);