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;
22 import android.app.Activity;
23 import android.app.DialogFragment;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.database.Cursor;
27 import android.graphics.Bitmap;
28 import android.graphics.BitmapFactory;
29 import android.graphics.Typeface;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.os.Bundle;
33 import android.support.design.widget.FloatingActionButton;
34 import android.support.design.widget.Snackbar;
35 import android.support.v4.app.NavUtils;
36 import android.support.v4.content.ContextCompat;
37 import android.support.v7.app.ActionBar;
38 import android.support.v7.app.AppCompatActivity;
39 import android.support.v7.widget.Toolbar;
40 import android.util.SparseBooleanArray;
41 import android.view.ActionMode;
42 import android.view.Menu;
43 import android.view.MenuItem;
44 import android.view.View;
45 import android.view.ViewGroup;
46 import android.widget.AbsListView;
47 import android.widget.AdapterView;
48 import android.widget.CursorAdapter;
49 import android.widget.EditText;
50 import android.widget.ImageView;
51 import android.widget.ListView;
52 import android.widget.RadioButton;
53 import android.widget.TextView;
55 import java.io.ByteArrayOutputStream;
57 public class BookmarksActivity extends AppCompatActivity implements CreateBookmark.CreateBookmarkListener,
58 CreateBookmarkFolder.CreateBookmarkFolderListener, EditBookmark.EditBookmarkListener,
59 EditBookmarkFolder.EditBookmarkFolderListener, MoveToFolder.MoveToFolderListener {
60 // `bookmarksDatabaseHandler` is public static so it can be accessed from `EditBookmark` and `MoveToFolder`. It is also used in `onCreate()`,
61 // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
62 public static BookmarksDatabaseHandler bookmarksDatabaseHandler;
64 // `bookmarksListView` is public static so it can be accessed from `EditBookmark`.
65 // It is also used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
66 public static ListView bookmarksListView;
68 // `currentFolder` is public static so it can be accessed from `MoveToFolder`.
69 // It is used in `onCreate`, `onOptionsItemSelected()`, `onCreateBookmarkCreate`, `onCreateBookmarkFolderCreate`, and `onEditBookmarkSave`.
70 public static String currentFolder;
72 // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
73 private ActionMode contextualActionMode;
75 // `selectedBookmarkPosition` is used in `onCreate()` and `onEditBookarkSave()`.
76 private int selectedBookmarkPosition;
78 // `appBar` is used in `onCreate()` and `updateBookmarksListView()`.
79 private ActionBar appBar;
81 // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
82 private Cursor bookmarksCursor;
84 // `oldFolderName` is used in `onCreate()` and `onEditBookmarkFolderSave()`.
85 private String oldFolderNameString;
88 protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.bookmarks_coordinatorlayout);
92 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
93 final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
94 setSupportActionBar(bookmarksAppBar);
96 // Display the home arrow on `SupportActionBar`.
97 appBar = getSupportActionBar();
98 assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
99 appBar.setDisplayHomeAsUpEnabled(true);
102 // Initialize the database handler and the ListView.
103 // `this` specifies the context. The two `null`s do not specify the database name or a `CursorFactory`.
104 // The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHandler`.
105 bookmarksDatabaseHandler = new BookmarksDatabaseHandler(this, null, null, 0);
106 bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
108 // Set currentFolder to the home folder, which is null in the database.
111 // Display the bookmarks in the ListView.
112 updateBookmarksListView(currentFolder);
114 // Set a listener so that tapping a list item loads the URL. We need to store the activity
115 // in a variable so that we can return to the parent activity after loading the URL.
116 final Activity bookmarksActivity = this;
117 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
119 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
120 // Convert the id from long to int to match the format of the bookmarks database.
121 int databaseID = (int) id;
123 // Get the bookmark `Cursor` and move it to the first row.
124 Cursor bookmarkCursor = bookmarksDatabaseHandler.getBookmarkCursor(databaseID);
125 bookmarkCursor.moveToFirst();
127 // If the bookmark is a folder load its contents into the ListView.
128 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
129 // Update `currentFolder`.
130 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
132 // Reload the ListView with `currentFolder`.
133 updateBookmarksListView(currentFolder);
134 } else { // Load the URL into `mainWebView`.
135 // Get the bookmark URL and assign it to formattedUrlString.
136 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_URL));
138 // Load formattedUrlString and return to the main activity.
139 MainWebViewActivity.mainWebView.loadUrl(MainWebViewActivity.formattedUrlString);
140 NavUtils.navigateUpFromSameTask(bookmarksActivity);
143 // Close the `Cursor`.
144 bookmarkCursor.close();
148 // `MultiChoiceModeListener` handles long clicks.
149 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
150 // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
151 MenuItem moveBookmarkUpMenuItem;
153 // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
154 MenuItem moveBookmarkDownMenuItem;
156 // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
157 MenuItem editBookmarkMenuItem;
159 // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
160 MenuItem selectAllBookmarksMenuItem;
163 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
164 // Inflate the menu for the contextual app bar and set the title.
165 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
168 if (currentFolder.isEmpty()) {
169 // Use `R.string.bookmarks` if we are in the home folder.
170 mode.setTitle(R.string.bookmarks);
171 } else { // Use the current folder name as the title.
172 mode.setTitle(currentFolder);
175 // Get a handle for MenuItems we need to selectively disable.
176 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
177 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
178 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
179 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
181 // Get a handle for `contextualActionMode` so we can close it programatically.
182 contextualActionMode = mode;
188 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
193 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
194 // Get an array of the selected bookmarks.
195 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
197 // Calculate the number of selected bookmarks.
198 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
200 // Sometimes Android forgets to close the contextual app bar when all the items are deselected.
201 if (numberOfSelectedBookmarks == 0) {
205 // List the number of selected bookmarks in the subtitle.
206 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
208 if (numberOfSelectedBookmarks == 1) {
209 // Show the `Move Up`, `Move Down`, and `Edit` option only if 1 bookmark is selected.
210 moveBookmarkUpMenuItem.setVisible(true);
211 moveBookmarkDownMenuItem.setVisible(true);
212 editBookmarkMenuItem.setVisible(true);
214 // Get the database IDs for the bookmarks.
215 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
216 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
217 // bookmarksListView is 0 indexed.
218 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
220 // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
221 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
222 moveBookmarkUpMenuItem.setEnabled(false);
223 moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_disabled);
224 } else { // Otherwise enable `moveBookmarkUpMenuItem`.
225 moveBookmarkUpMenuItem.setEnabled(true);
226 moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_enabled);
229 // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
230 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
231 moveBookmarkDownMenuItem.setEnabled(false);
232 moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_disabled);
233 } else { // Otherwise enable `moveBookmarkDownMenuItem`.
234 moveBookmarkDownMenuItem.setEnabled(true);
235 moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_enabled);
237 } else { // Hide the MenuItems because more than one bookmark is selected.
238 moveBookmarkUpMenuItem.setVisible(false);
239 moveBookmarkDownMenuItem.setVisible(false);
240 editBookmarkMenuItem.setVisible(false);
243 // Do not show `Select All` if all the bookmarks are already checked.
244 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
245 selectAllBookmarksMenuItem.setVisible(false);
247 selectAllBookmarksMenuItem.setVisible(true);
252 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
253 int menuItemId = item.getItemId();
255 // `numberOfBookmarks` is used in `R.id.move_bookmark_up_enabled`, `R.id.move_bookmark_down_enabled`, and `R.id.context_menu_select_all_bookmarks`.
256 int numberOfBookmarks;
258 // `selectedBookmarkLongArray` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
259 long[]selectedBookmarkLongArray;
260 // `selectedBookmarkDatabaseId` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
261 int selectedBookmarkDatabaseId;
262 // `selectedBookmarkNewPosition` is used in `R.id.move_bookmark_up` and `R.id.move_bookmark_down`.
263 int selectedBookmarkNewPosition;
264 // `bookmarkPositionSparseBooleanArray` is used in `R.id.edit_bookmark` and `R.id.delete_bookmark`.
265 SparseBooleanArray bookmarkPositionSparseBooleanArray;
267 switch (menuItemId) {
268 case R.id.move_bookmark_up:
269 // Get the selected bookmark database ID.
270 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
271 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
273 // Initialize `selectedBookmarkNewPosition`.
274 selectedBookmarkNewPosition = 0;
276 for (int i = 0; i < bookmarksListView.getCount(); i++) {
277 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
278 int nextBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i + 1);
280 if (databaseId == selectedBookmarkDatabaseId || nextBookmarkDatabaseId == selectedBookmarkDatabaseId) {
281 if (databaseId == selectedBookmarkDatabaseId) {
282 // Move the selected bookmark up one and store the new bookmark position.
283 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i - 1);
284 selectedBookmarkNewPosition = i - 1;
285 } else { // Move the bookmark above the selected bookmark down one.
286 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
289 // Reset the rest of the bookmarks' DISPLAY_ORDER to match the position in the ListView.
290 // This isn't necessary, but it clears out any stray values that might have crept into the database.
291 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i);
295 // Refresh the ListView.
296 updateBookmarksListView(currentFolder);
298 // Select the previously selected bookmark in the new location.
299 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
301 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
305 case R.id.move_bookmark_down:
306 // Get the selected bookmark database ID.
307 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
308 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
310 // Initialize `selectedBookmarkNewPosition`.
311 selectedBookmarkNewPosition = 0;
313 for (int i = 0; i <bookmarksListView.getCount(); i++) {
314 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
315 int previousBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i - 1);
317 if (databaseId == selectedBookmarkDatabaseId || previousBookmarkDatabaseId == selectedBookmarkDatabaseId) {
318 if (databaseId == selectedBookmarkDatabaseId) {
319 // Move the selected bookmark down one and store the new bookmark position.
320 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
321 selectedBookmarkNewPosition = i + 1;
322 } else { // Move the bookmark below the selected bookmark up one.
323 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i - 1);
326 // Reset the rest of the bookmark' DISPLAY_ORDER to match the position in the ListView.
327 // This isn't necessary, but it clears out any stray values that might have crept into the database.
328 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i);
332 // Refresh the ListView.
333 updateBookmarksListView(currentFolder);
335 // Select the previously selected bookmark in the new location.
336 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
338 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
341 case R.id.move_to_folder:
342 // Show the `MoveToFolder` `AlertDialog` and name the instance `@string/move_to_folder
343 DialogFragment moveToFolderDialog = new MoveToFolder();
344 moveToFolderDialog.show(getFragmentManager(), getResources().getString(R.string.move_to_folder));
347 case R.id.edit_bookmark:
348 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
349 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
350 for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
351 // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
352 if (bookmarkPositionSparseBooleanArray.valueAt(i))
353 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
356 // Move to the selected database ID and find out if it is a folder.
357 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
358 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1);
361 // Save the current folder name.
362 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
364 // Show the `EditBookmarkFolder` `AlertDialog` and name the instance `@string/edit_folder`.
365 DialogFragment editFolderDialog = new EditBookmarkFolder();
366 editFolderDialog.show(getFragmentManager(), getResources().getString(R.string.edit_folder));
368 // Show the `EditBookmark` `AlertDialog` and name the instance `@string/edit_bookmark`.
369 DialogFragment editBookmarkDialog = new EditBookmark();
370 editBookmarkDialog.show(getFragmentManager(), getResources().getString(R.string.edit_bookmark));
374 case R.id.delete_bookmark:
375 // Get an array of the selected rows.
376 final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
378 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
379 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
380 for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
381 // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
382 if (bookmarkPositionSparseBooleanArray.valueAt(i))
383 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
386 updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
388 // Scroll to where the deleted bookmark was located.
389 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
391 String snackbarMessage;
393 // Determine how many items are in the array and prepare an appropriate Snackbar message.
394 if (selectedBookmarksLongArray.length == 1) {
395 snackbarMessage = getString(R.string.one_bookmark_deleted);
397 snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
401 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
402 .setAction(R.string.undo, new View.OnClickListener() {
404 public void onClick(View view) {
405 // Do nothing because everything will be handled by `onDismissed()` below.
408 .setCallback(new Snackbar.Callback() {
410 public void onDismissed(Snackbar snackbar, int event) {
412 // The user pushed the "Undo" button.
413 case Snackbar.Callback.DISMISS_EVENT_ACTION:
414 // Refresh the ListView to show the rows again.
415 updateBookmarksListView(currentFolder);
417 // Scroll to where the deleted bookmark was located.
418 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
422 // The Snackbar was dismissed without the "Undo" button being pushed.
424 // Delete each selected row.
425 for (long databaseIdLong : selectedBookmarksLongArray) {
426 // Convert `databaseIdLong` to an int.
427 int databaseIdInt = (int) databaseIdLong;
429 if (bookmarksDatabaseHandler.isFolder(databaseIdInt)) {
430 deleteBookmarkFolderContents(databaseIdInt);
433 // Delete `databaseIdInt`.
434 bookmarksDatabaseHandler.deleteBookmark(databaseIdInt);
442 // Close the contextual app bar.
446 case R.id.context_menu_select_all_bookmarks:
447 numberOfBookmarks = bookmarksListView.getCount();
449 for (int i = 0; i < numberOfBookmarks; i++) {
450 bookmarksListView.setItemChecked(i, true);
454 // Consume the click.
459 public void onDestroyActionMode(ActionMode mode) {
464 // Set a FloatingActionButton for creating new bookmarks.
465 FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
466 assert createBookmarkFAB != null;
467 createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
469 public void onClick(View view) {
470 // Show the `CreateBookmark` `AlertDialog` and name the instance `@string/create_bookmark`.
471 DialogFragment createBookmarkDialog = new CreateBookmark();
472 createBookmarkDialog.show(getFragmentManager(), getResources().getString(R.string.create_bookmark));
478 public boolean onCreateOptionsMenu(Menu menu) {
480 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
486 public boolean onPrepareOptionsMenu(Menu menu) {
487 super.onPrepareOptionsMenu(menu);
493 public boolean onOptionsItemSelected(MenuItem menuItem) {
494 int menuItemId = menuItem.getItemId();
496 switch (menuItemId) {
497 case android.R.id.home:
498 // Exit BookmarksActivity if currently at the home folder.
499 if (currentFolder.isEmpty()) {
500 NavUtils.navigateUpFromSameTask(this);
501 } else { // Navigate up one folder.
502 // Place the former parent folder in `currentFolder`.
503 currentFolder = bookmarksDatabaseHandler.getParentFolder(currentFolder);
505 updateBookmarksListView(currentFolder);
509 case R.id.create_folder:
510 // Show the `CreateBookmarkFolder` `AlertDialog` and name the instance `@string/create_folder`.
511 DialogFragment createBookmarkFolderDialog = new CreateBookmarkFolder();
512 createBookmarkFolderDialog.show(getFragmentManager(), getResources().getString(R.string.create_folder));
515 case R.id.options_menu_select_all_bookmarks:
516 int numberOfBookmarks = bookmarksListView.getCount();
518 for (int i = 0; i < numberOfBookmarks; i++) {
519 bookmarksListView.setItemChecked(i, true);
523 case R.id.bookmarks_database_view:
524 // Launch `BookmarksDatabaseViewActivity`.
525 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
526 startActivity(bookmarksDatabaseViewIntent);
533 public void onCancelCreateBookmark(DialogFragment dialogFragment) {
534 // Do nothing because the user selected `Cancel`.
538 public void onCreateBookmark(DialogFragment dialogFragment) {
539 // Get the `EditText`s from the `createBookmarkDialogFragment` and extract the strings.
540 EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
541 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
542 EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
543 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
545 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
546 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
547 MainWebViewActivity.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
548 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
550 // Display the new bookmark below the current items in the (0 indexed) list.
551 int newBookmarkDisplayOrder = bookmarksListView.getCount();
553 // Create the bookmark.
554 bookmarksDatabaseHandler.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
556 // Refresh the ListView. `setSelection` scrolls to the bottom of the list.
557 updateBookmarksListView(currentFolder);
558 bookmarksListView.setSelection(newBookmarkDisplayOrder);
562 public void onCancelCreateBookmarkFolder(DialogFragment dialogFragment) {
563 // Do nothing because the user selected `Cancel`.
567 public void onCreateBookmarkFolder(DialogFragment dialogFragment) {
568 // Get `create_folder_name_edit_text` and extract the string.
569 EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
570 String folderNameString = createFolderNameEditText.getText().toString();
572 // Check to see if the folder already exists.
573 Cursor bookmarkFolderCursor = bookmarksDatabaseHandler.getFolderCursor(folderNameString);
574 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
575 bookmarkFolderCursor.close();
576 if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
577 String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
578 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
579 } else { // Create the folder.
580 // Get the new folder icon.
581 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobuttion);
582 Bitmap folderIconBitmap;
583 if (defaultFolderIconRadioButton.isChecked()) {
584 // Get the default folder icon drawable and convert it to a `Bitmap`. `this` specifies the current context.
585 Drawable folderIconDrawable = ContextCompat.getDrawable(this, R.drawable.folder_blue_bitmap);
586 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
587 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
589 folderIconBitmap = MainWebViewActivity.favoriteIcon;
592 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
593 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
594 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
595 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
597 // Move all the bookmarks down one in the display order.
598 for (int i = 0; i < bookmarksListView.getCount(); i++) {
599 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
600 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
603 // Create the folder, placing it at the top of the ListView
604 bookmarksDatabaseHandler.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
606 // Refresh the ListView.
607 updateBookmarksListView(currentFolder);
612 public void onCancelEditBookmark(DialogFragment dialogFragment) {
613 // Do nothing because the user selected `Cancel`.
617 public void onSaveEditBookmark(DialogFragment dialogFragment) {
618 // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
619 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
620 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
622 // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
623 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
624 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
625 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
626 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
628 // Get `edit_bookmark_current_icon_radiobutton`.
629 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
631 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
632 bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
633 } else { // Update the bookmark and the favorite icon.
634 // Get the new favorite icon from the `Dialog` and convert it into a `Bitmap`.
635 ImageView newFavoriteIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_web_page_favorite_icon);
636 Drawable newFavoriteIconDrawable = newFavoriteIconImageView.getDrawable();
637 Bitmap newFavoriteIconBitmap = ((BitmapDrawable) newFavoriteIconDrawable).getBitmap();
639 // Convert `newFavoriteIconBitmap` into a Byte Array.
640 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
641 newFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
642 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
644 // Update the bookmark and the favorite icon.
645 bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
648 // Close the contextual action mode.
649 contextualActionMode.finish();
651 // Refresh the `ListView`. `setSelection` scrolls to the position of the bookmark that was edited.
652 updateBookmarksListView(currentFolder);
653 bookmarksListView.setSelection(selectedBookmarkPosition);
657 public void onCancelEditBookmarkFolder(DialogFragment dialogFragment) {
658 // Do nothing because the user selected `Cancel`.
662 public void onSaveEditBookmarkFolder(DialogFragment dialogFragment) {
663 // Get the new folder name.
664 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
665 String newFolderNameString = editFolderNameEditText.getText().toString();
667 // Check to see if the new folder name is unique.
668 Cursor bookmarkFolderCursor = bookmarksDatabaseHandler.getFolderCursor(newFolderNameString);
669 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
670 bookmarkFolderCursor.close();
671 if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
672 // Get a long array with the the database ID of the selected folder and convert it to an `int`.
673 long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
674 int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
676 // Get the `RadioButtons` from the `Dialog`.
677 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
678 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
679 Bitmap folderIconBitmap;
681 // Prepare the favorite icon.
682 if (currentFolderIconRadioButton.isChecked()) {
683 // Update the folder name if it has changed.
684 if (!newFolderNameString.equals(oldFolderNameString)) {
685 bookmarksDatabaseHandler.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
687 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
688 updateBookmarksListView(currentFolder);
689 bookmarksListView.setSelection(selectedBookmarkPosition);
691 } else { // Prepare the new favorite icon.
692 if (defaultFolderIconRadioButton.isChecked()) {
693 // Get the default folder icon drawable and convert it to a `Bitmap`. `this` specifies the current context.
694 Drawable folderIconDrawable = ContextCompat.getDrawable(this, R.drawable.folder_blue_bitmap);
695 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
696 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
697 } else { // Use the web page favorite icon.
698 folderIconBitmap = MainWebViewActivity.favoriteIcon;
701 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
702 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
703 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
704 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
706 bookmarksDatabaseHandler.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
708 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
709 updateBookmarksListView(currentFolder);
710 bookmarksListView.setSelection(selectedBookmarkPosition);
712 } else { // Don't edit the folder because the new name is not unique.
713 String cannot_rename_folder = getResources().getString(R.string.cannot_rename_folder) + " \"" + newFolderNameString + "\"";
714 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
719 public void onCancelMoveToFolder(DialogFragment dialogFragment) {
720 // Do nothing because the user selected `Cancel`.
724 public void onMoveToFolder(DialogFragment dialogFragment) {
725 // Get the new folder database id.
726 ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
727 long[] newFolderLongArray = folderListView.getCheckedItemIds();
729 if (newFolderLongArray.length == 0) { // No new folder was selected.
730 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_LONG).show();
731 } else { // Move the selected bookmarks.
732 // Get the new folder database ID.
733 int newFolderDatabaseId = (int) newFolderLongArray[0];
735 // Instantiate `newFolderName`.
736 String newFolderName;
738 if (newFolderDatabaseId == 0) {
739 // The new folder is the home folder, represented as `""` in the database.
742 // Get the new folder name from the database.
743 newFolderName = bookmarksDatabaseHandler.getFolderName(newFolderDatabaseId);
746 // Get a long array with the the database ID of the selected bookmarks.
747 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
748 for (long databaseIdLong : selectedBookmarksLongArray) {
749 // Get `databaseIdInt` for each selected bookmark.
750 int databaseIdInt = (int) databaseIdLong;
752 // Move the selected bookmark to the new folder.
753 bookmarksDatabaseHandler.moveToFolder(databaseIdInt, newFolderName);
756 // Refresh the `ListView`.
757 updateBookmarksListView(currentFolder);
759 // Close the contextual app bar.
760 contextualActionMode.finish();
764 private void updateBookmarksListView(String folderName) {
765 // Get a `Cursor` with the current contents of the bookmarks database.
766 bookmarksCursor = bookmarksDatabaseHandler.getAllBookmarksCursorByDisplayOrder(folderName);
768 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables autoRequery.
769 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
771 public View newView(Context context, Cursor cursor, ViewGroup parent) {
772 // Inflate the individual item layout. `false` does not attach it to the root.
773 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
777 public void bindView(View view, Context context, Cursor cursor) {
778 // Get the favorite icon byte array from the `Cursor`.
779 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
781 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
782 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
784 // Display the bitmap in `bookmarkFavoriteIcon`.
785 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
786 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
789 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
790 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
791 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
792 bookmarkNameTextView.setText(bookmarkNameString);
794 // Make the font bold for folders.
795 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
796 // The first argument is `null` because we don't want to chage the font.
797 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
798 } else { // Reset the font to default.
799 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
804 // Update the ListView.
805 bookmarksListView.setAdapter(bookmarksCursorAdapter);
807 // Set the AppBar title.
808 if (currentFolder.isEmpty()) {
809 appBar.setTitle(R.string.bookmarks);
811 appBar.setTitle(currentFolder);
815 private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
816 // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
817 bookmarksCursor = bookmarksDatabaseHandler.getBookmarksCursorExcept(exceptIdLongArray, folderName);
819 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables autoRequery.
820 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
822 public View newView(Context context, Cursor cursor, ViewGroup parent) {
823 // Inflate the individual item layout. `false` does not attach it to the root.
824 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
828 public void bindView(View view, Context context, Cursor cursor) {
829 // Get the favorite icon byte array from the cursor.
830 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
832 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
833 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
835 // Display the bitmap in `bookmarkFavoriteIcon`.
836 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
837 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
840 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
841 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
842 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
843 bookmarkNameTextView.setText(bookmarkNameString);
845 // Make the font bold for folders.
846 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
847 // The first argument is `null` because we don't want to chage the font.
848 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
849 } else { // Reset the font to default.
850 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
855 // Update the ListView.
856 bookmarksListView.setAdapter(bookmarksCursorAdapter);
859 private void deleteBookmarkFolderContents(int databaseId) {
860 // Get the name of the folder.
861 String folderName = bookmarksDatabaseHandler.getFolderName(databaseId);
863 // Get the contents of the folder.
864 Cursor folderCursor = bookmarksDatabaseHandler.getAllBookmarksCursorByDisplayOrder(folderName);
866 for (int i = 0; i < folderCursor.getCount(); i++) {
867 // Move `folderCursor` to the current row.
868 folderCursor.moveToPosition(i);
870 // Get the database ID of the item.
871 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHandler._ID));
873 // If this is a folder, delete the contents first.
874 if (bookmarksDatabaseHandler.isFolder(itemDatabaseId)) {
875 deleteBookmarkFolderContents(itemDatabaseId);
878 bookmarksDatabaseHandler.deleteBookmark(itemDatabaseId);