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.database.DatabaseUtils;
28 import android.graphics.Bitmap;
29 import android.graphics.BitmapFactory;
30 import android.graphics.Typeface;
31 import android.graphics.drawable.BitmapDrawable;
32 import android.graphics.drawable.Drawable;
33 import android.os.Bundle;
34 import android.support.design.widget.FloatingActionButton;
35 import android.support.design.widget.Snackbar;
36 import android.support.v4.app.NavUtils;
37 import android.support.v4.content.ContextCompat;
38 import android.support.v4.widget.CursorAdapter;
39 import android.support.v7.app.ActionBar;
40 import android.support.v7.app.AppCompatActivity;
41 import android.support.v7.widget.Toolbar;
42 import android.util.SparseBooleanArray;
43 import android.view.ActionMode;
44 import android.view.Menu;
45 import android.view.MenuItem;
46 import android.view.View;
47 import android.view.ViewGroup;
48 import android.widget.AbsListView;
49 import android.widget.AdapterView;
50 import android.widget.CheckBox;
51 import android.widget.EditText;
52 import android.widget.ImageView;
53 import android.widget.ListView;
54 import android.widget.RadioButton;
55 import android.widget.TextView;
57 import java.io.ByteArrayOutputStream;
59 public class BookmarksActivity extends AppCompatActivity implements CreateBookmark.CreateBookmarkListener,
60 CreateBookmarkFolder.CreateBookmarkFolderListener, EditBookmark.EditBookmarkListener,
61 EditBookmarkFolder.EditBookmarkFolderListener {
62 // `bookmarksDatabaseHandler` is public static so it can be accessed from EditBookmark. It is also used in `onCreate()`,
63 // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
64 public static BookmarksDatabaseHandler bookmarksDatabaseHandler;
66 // `bookmarksListView` is public static so it can be accessed from EditBookmark.
67 // It is also used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
68 public static ListView bookmarksListView;
70 // `currentFolder` is used in `onCreate`, `onOptionsItemSelected()`, `onCreateBookmarkCreate`, `onCreateBookmarkFolderCreate`, and `onEditBookmarkSave`.
71 private String currentFolder;
73 // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
74 private ActionMode contextualActionMode;
76 // `selectedBookmarkPosition` is used in `onCreate()` and `onEditBookarkSave()`.
77 private int selectedBookmarkPosition;
79 // `appBar` is used in `onCreate()` and `updateBookmarksListView()`.
80 private ActionBar appBar;
82 // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
83 private Cursor bookmarksCursor;
85 // `oldFolderName` is used in `onCreate()` and `onEditBookmarkFolderSave()`.
86 private String oldFolderNameString;
89 protected void onCreate(Bundle savedInstanceState) {
90 super.onCreate(savedInstanceState);
91 setContentView(R.layout.bookmarks_coordinatorlayout);
93 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
94 final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
95 setSupportActionBar(bookmarksAppBar);
97 // Display the home arrow on `SupportActionBar`.
98 appBar = getSupportActionBar();
99 assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
100 appBar.setDisplayHomeAsUpEnabled(true);
103 // Initialize the database handler and the ListView.
104 // `this` specifies the context. The two `null`s do not specify the database name or a `CursorFactory`.
105 // The `0` is to specify a database version, but that is set instead using a constant in `BookmarksDatabaseHandler`.
106 bookmarksDatabaseHandler = new BookmarksDatabaseHandler(this, null, null, 0);
107 bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
109 // Set currentFolder to the home folder, which is null in the database.
112 // Display the bookmarks in the ListView.
113 updateBookmarksListView(currentFolder);
115 // Set a listener so that tapping a list item loads the URL. We need to store the activity
116 // in a variable so that we can return to the parent activity after loading the URL.
117 final Activity bookmarksActivity = this;
118 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
120 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
121 // Convert the id from long to int to match the format of the bookmarks database.
122 int databaseID = (int) id;
124 // Get the bookmark `Cursor` and move it to the first row.
125 Cursor bookmarkCursor = bookmarksDatabaseHandler.getBookmarkCursor(databaseID);
126 bookmarkCursor.moveToFirst();
128 // If the bookmark is a folder load its contents into the ListView.
129 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
130 // Update `currentFolder`.
131 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
133 // Reload the ListView with `currentFolder`.
134 updateBookmarksListView(currentFolder);
135 } else { // Load the URL into `mainWebView`.
136 // Get the bookmark URL and assign it to formattedUrlString.
137 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_URL));
139 // Load formattedUrlString and return to the main activity.
140 MainWebViewActivity.mainWebView.loadUrl(MainWebViewActivity.formattedUrlString);
141 NavUtils.navigateUpFromSameTask(bookmarksActivity);
144 // Close the `Cursor`.
145 bookmarkCursor.close();
149 // `MultiChoiceModeListener` handles long clicks.
150 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
151 // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
152 MenuItem moveBookmarkUpMenuItem;
154 // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
155 MenuItem moveBookmarkDownMenuItem;
157 // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
158 MenuItem editBookmarkMenuItem;
160 // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
161 MenuItem selectAllBookmarksMenuItem;
164 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
165 // Inflate the menu for the contextual app bar and set the title.
166 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
169 if (currentFolder.isEmpty()) {
170 // Use `R.string.bookmarks` if we are in the home folder.
171 mode.setTitle(R.string.bookmarks);
172 } else { // Use the current folder name as the title.
173 mode.setTitle(currentFolder);
176 // Get a handle for MenuItems we need to selectively disable.
177 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
178 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
179 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
180 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
186 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
191 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
192 // Get an array of the selected bookmarks.
193 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
195 // Calculate the number of selected bookmarks.
196 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
198 // List the number of selected bookmarks in the subtitle.
199 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
201 if (numberOfSelectedBookmarks == 1) {
202 // Show the `Move Up`, `Move Down`, and `Edit` option only if 1 bookmark is selected.
203 moveBookmarkUpMenuItem.setVisible(true);
204 moveBookmarkDownMenuItem.setVisible(true);
205 editBookmarkMenuItem.setVisible(true);
207 // Get the database IDs for the bookmarks.
208 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
209 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
210 // bookmarksListView is 0 indexed.
211 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
213 // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
214 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
215 moveBookmarkUpMenuItem.setEnabled(false);
216 moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_disabled);
217 } else { // Otherwise enable `moveBookmarkUpMenuItem`.
218 moveBookmarkUpMenuItem.setEnabled(true);
219 moveBookmarkUpMenuItem.setIcon(R.drawable.move_bookmark_up_enabled);
222 // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
223 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
224 moveBookmarkDownMenuItem.setEnabled(false);
225 moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_disabled);
226 } else { // Otherwise enable `moveBookmarkDownMenuItem`.
227 moveBookmarkDownMenuItem.setEnabled(true);
228 moveBookmarkDownMenuItem.setIcon(R.drawable.move_bookmark_down_enabled);
230 } else { // Hide the MenuItems because more than one bookmark is selected.
231 moveBookmarkUpMenuItem.setVisible(false);
232 moveBookmarkDownMenuItem.setVisible(false);
233 editBookmarkMenuItem.setVisible(false);
236 // Do not show `Select All` if all the bookmarks are already checked.
237 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
238 selectAllBookmarksMenuItem.setVisible(false);
240 selectAllBookmarksMenuItem.setVisible(true);
245 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
246 int menuItemId = item.getItemId();
248 // `numberOfBookmarks` is used in `R.id.move_bookmark_up_enabled`, `R.id.move_bookmark_down_enabled`, and `R.id.context_menu_select_all_bookmarks`.
249 int numberOfBookmarks;
251 // `selectedBookmarkLongArray` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
252 long[]selectedBookmarkLongArray;
253 // `selectedBookmarkDatabaseId` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
254 int selectedBookmarkDatabaseId;
255 // `selectedBookmarkNewPosition` is used in `R.id.move_bookmark_up` and `R.id.move_bookmark_down`.
256 int selectedBookmarkNewPosition;
257 // `bookmarkPositionSparseBooleanArray` is used in `R.id.edit_bookmark` and `R.id.delete_bookmark`.
258 SparseBooleanArray bookmarkPositionSparseBooleanArray;
260 switch (menuItemId) {
261 case R.id.move_bookmark_up:
262 // Get the selected bookmark database ID.
263 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
264 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
266 // Initialize `selectedBookmarkNewPosition`.
267 selectedBookmarkNewPosition = 0;
269 for (int i = 0; i < bookmarksListView.getCount(); i++) {
270 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
271 int nextBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i + 1);
273 if (databaseId == selectedBookmarkDatabaseId || nextBookmarkDatabaseId == selectedBookmarkDatabaseId) {
274 if (databaseId == selectedBookmarkDatabaseId) {
275 // Move the selected bookmark up one and store the new bookmark position.
276 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i - 1);
277 selectedBookmarkNewPosition = i - 1;
278 } else { // Move the bookmark above the selected bookmark down one.
279 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
282 // Reset the rest of the bookmarks' DISPLAY_ORDER to match the position in the ListView.
283 // This isn't necessary, but it clears out any stray values that might have crept into the database.
284 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i);
288 // Refresh the ListView.
289 updateBookmarksListView(currentFolder);
291 // Select the previously selected bookmark in the new location.
292 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
294 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
298 case R.id.move_bookmark_down:
299 // Get the selected bookmark database ID.
300 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
301 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
303 // Initialize `selectedBookmarkNewPosition`.
304 selectedBookmarkNewPosition = 0;
306 for (int i = 0; i <bookmarksListView.getCount(); i++) {
307 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
308 int previousBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i - 1);
310 if (databaseId == selectedBookmarkDatabaseId || previousBookmarkDatabaseId == selectedBookmarkDatabaseId) {
311 if (databaseId == selectedBookmarkDatabaseId) {
312 // Move the selected bookmark down one and store the new bookmark position.
313 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
314 selectedBookmarkNewPosition = i + 1;
315 } else { // Move the bookmark below the selected bookmark up one.
316 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i - 1);
319 // Reset the rest of the bookmark' DISPLAY_ORDER to match the position in the ListView.
320 // This isn't necessary, but it clears out any stray values that might have crept into the database.
321 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i);
325 // Refresh the ListView.
326 updateBookmarksListView(currentFolder);
328 // Select the previously selected bookmark in the new location.
329 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
331 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
334 case R.id.edit_bookmark:
335 // Get a handle for `contextualActionMode` so we can close it when `editBookmarkDialog` is finished.
336 contextualActionMode = mode;
338 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
339 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
340 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
342 // Move to the selected database ID and find out if it is a folder.
343 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
344 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1);
347 // Save the current folder name.
348 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
350 // Show the `EditBookmarkFolder` `AlertDialog` and name the instance `@string/edit_folder`.
351 DialogFragment editFolderDialog = new EditBookmarkFolder();
352 editFolderDialog.show(getFragmentManager(), getResources().getString(R.string.edit_folder));
354 // Show the `EditBookmark` `AlertDialog` and name the instance `@string/edit_bookmark`.
355 DialogFragment editBookmarkDialog = new EditBookmark();
356 editBookmarkDialog.show(getFragmentManager(), getResources().getString(R.string.edit_bookmark));
360 case R.id.delete_bookmark:
361 // Get an array of the selected rows.
362 final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
364 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
365 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
366 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(0);
368 updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
370 // Scroll to where the deleted bookmark was located.
371 bookmarksListView.setSelection(selectedBookmarkPosition);
373 String snackbarMessage;
375 // Determine how many items are in the array and prepare an appropriate Snackbar message.
376 if (selectedBookmarksLongArray.length == 1) {
377 snackbarMessage = getString(R.string.one_bookmark_deleted);
379 snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
383 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
384 .setAction(R.string.undo, new View.OnClickListener() {
386 public void onClick(View view) {
387 // Do nothing because everything will be handled by `onDismissed()` below.
390 .setCallback(new Snackbar.Callback() {
392 public void onDismissed(Snackbar snackbar, int event) {
394 // The user pushed the "Undo" button.
395 case Snackbar.Callback.DISMISS_EVENT_ACTION:
396 // Refresh the ListView to show the rows again.
397 updateBookmarksListView(currentFolder);
401 // The Snackbar was dismissed without the "Undo" button being pushed.
403 // Delete each selected row.
404 for (long databaseIdLong : selectedBookmarksLongArray) {
405 // Convert `databaseIdLong` to an int.
406 int databaseIdInt = (int) databaseIdLong;
408 // Delete the database row.
409 bookmarksDatabaseHandler.deleteBookmark(databaseIdInt);
417 // Close the contextual app bar.
421 case R.id.context_menu_select_all_bookmarks:
422 numberOfBookmarks = bookmarksListView.getCount();
424 for (int i = 0; i < numberOfBookmarks; i++) {
425 bookmarksListView.setItemChecked(i, true);
429 // Consume the click.
434 public void onDestroyActionMode(ActionMode mode) {
439 // Set a FloatingActionButton for creating new bookmarks.
440 FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
441 assert createBookmarkFAB != null;
442 createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
444 public void onClick(View view) {
445 // Show the `CreateBookmark` `AlertDialog` and name the instance `@string/create_bookmark`.
446 DialogFragment createBookmarkDialog = new CreateBookmark();
447 createBookmarkDialog.show(getFragmentManager(), getResources().getString(R.string.create_bookmark));
453 public boolean onCreateOptionsMenu(Menu menu) {
455 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
461 public boolean onPrepareOptionsMenu(Menu menu) {
462 super.onPrepareOptionsMenu(menu);
468 public boolean onOptionsItemSelected(MenuItem menuItem) {
469 int menuItemId = menuItem.getItemId();
471 switch (menuItemId) {
472 case android.R.id.home:
473 // Exit BookmarksActivity if currently at the home folder.
474 if (currentFolder.isEmpty()) {
475 NavUtils.navigateUpFromSameTask(this);
476 } else { // Navigate up one folder.
477 // Place the former parent folder in `currentFolder`.
478 currentFolder = bookmarksDatabaseHandler.getParentFolder(currentFolder);
480 updateBookmarksListView(currentFolder);
484 case R.id.create_folder:
485 // Show the `CreateBookmarkFolder` `AlertDialog` and name the instance `@string/create_folder`.
486 DialogFragment createBookmarkFolderDialog = new CreateBookmarkFolder();
487 createBookmarkFolderDialog.show(getFragmentManager(), getResources().getString(R.string.create_folder));
490 case R.id.options_menu_select_all_bookmarks:
491 int numberOfBookmarks = bookmarksListView.getCount();
493 for (int i = 0; i < numberOfBookmarks; i++) {
494 bookmarksListView.setItemChecked(i, true);
498 case R.id.bookmarks_database_view:
499 // Launch `BookmarksDatabaseViewActivity`.
500 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
501 startActivity(bookmarksDatabaseViewIntent);
508 public void onCancelCreateBookmark(DialogFragment dialogFragment) {
509 // Do nothing because the user selected `Cancel`.
513 public void onCreateBookmark(DialogFragment dialogFragment) {
514 // Get the `EditText`s from the `createBookmarkDialogFragment` and extract the strings.
515 EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
516 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
517 EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
518 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
520 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
521 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
522 MainWebViewActivity.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
523 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
525 // Display the new bookmark below the current items in the (0 indexed) list.
526 int newBookmarkDisplayOrder = bookmarksListView.getCount();
528 // Create the bookmark.
529 bookmarksDatabaseHandler.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
531 // Refresh the ListView. `setSelection` scrolls to the bottom of the list.
532 updateBookmarksListView(currentFolder);
533 bookmarksListView.setSelection(newBookmarkDisplayOrder);
537 public void onCancelCreateBookmarkFolder(DialogFragment dialogFragment) {
538 // Do nothing because the user selected `Cancel`.
542 public void onCreateBookmarkFolder(DialogFragment dialogFragment) {
543 // Get `create_folder_name_edit_text` and extract the string.
544 EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
545 String folderNameString = createFolderNameEditText.getText().toString();
547 // Check to see if the folder already exists.
548 Cursor bookmarkFolderCursor = bookmarksDatabaseHandler.getFolderCursor(folderNameString);
549 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
550 bookmarkFolderCursor.close();
551 if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
552 String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
553 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
554 } else { // Create the folder.
555 // Get the new folder icon.
556 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobuttion);
557 Bitmap folderIconBitmap;
558 if (defaultFolderIconRadioButton.isChecked()) {
559 // Get the default folder icon drawable and convert it to a `Bitmap`. `this` specifies the current context.
560 Drawable folderIconDrawable = ContextCompat.getDrawable(this, R.drawable.folder_blue_bitmap);
561 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
562 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
564 folderIconBitmap = MainWebViewActivity.favoriteIcon;
567 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
568 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
569 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
570 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
572 // Move all the bookmarks down one in the display order.
573 for (int i = 0; i < bookmarksListView.getCount(); i++) {
574 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
575 bookmarksDatabaseHandler.updateBookmarkDisplayOrder(databaseId, i + 1);
578 // Create the folder, placing it at the top of the ListView
579 bookmarksDatabaseHandler.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
581 // Refresh the ListView.
582 updateBookmarksListView(currentFolder);
587 public void onCancelEditBookmark(DialogFragment dialogFragment) {
588 // Do nothing because the user selected `Cancel`.
592 public void onSaveEditBookmark(DialogFragment dialogFragment) {
593 // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
594 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
595 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
597 // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
598 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
599 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
600 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
601 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
603 // Get `edit_bookmark_current_icon_radiobutton`.
604 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
606 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
607 bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
608 } else { // Update the bookmark and the favorite icon.
609 // Get the new favorite icon from the `Dialog` and convert it into a `Bitmap`.
610 ImageView newFavoriteIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_web_page_favorite_icon);
611 Drawable newFavoriteIconDrawable = newFavoriteIconImageView.getDrawable();
612 Bitmap newFavoriteIconBitmap = ((BitmapDrawable) newFavoriteIconDrawable).getBitmap();
614 // Convert `newFavoriteIconBitmap` into a Byte Array.
615 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
616 newFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
617 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
619 // Update the bookmark and the favorite icon.
620 bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
623 // Close the contextual action mode.
624 contextualActionMode.finish();
626 // Refresh the `ListView`. `setSelection` scrolls to the position of the bookmark that was edited.
627 updateBookmarksListView(currentFolder);
628 bookmarksListView.setSelection(selectedBookmarkPosition);
632 public void onCancelEditBookmarkFolder(DialogFragment dialogFragment) {
633 // Do nothing because the user selected `Cancel`.
637 public void onSaveEditBookmarkFolder(DialogFragment dialogFragment) {
638 // Get the new folder name.
639 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
640 String newFolderNameString = editFolderNameEditText.getText().toString();
642 // Check to see if the new folder name is unique.
643 Cursor bookmarkFolderCursor = bookmarksDatabaseHandler.getFolderCursor(newFolderNameString);
644 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
645 bookmarkFolderCursor.close();
646 if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
647 // Get a long array with the the databaseId of the selected folder and convert it to an `int`.
648 long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
649 int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
651 // Get the `RadioButtons` from the `Dialog`.
652 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
653 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
654 Bitmap folderIconBitmap;
656 // Prepare the favorite icon.
657 if (currentFolderIconRadioButton.isChecked()) {
658 // Update the folder name if it has changed.
659 if (!newFolderNameString.equals(oldFolderNameString)) {
660 bookmarksDatabaseHandler.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
662 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
663 updateBookmarksListView(currentFolder);
664 bookmarksListView.setSelection(selectedBookmarkPosition);
666 } else { // Prepare the new favorite icon.
667 if (defaultFolderIconRadioButton.isChecked()) {
668 // Get the default folder icon drawable and convert it to a `Bitmap`. `this` specifies the current context.
669 Drawable folderIconDrawable = ContextCompat.getDrawable(this, R.drawable.folder_blue_bitmap);
670 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
671 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
672 } else { // Use the web page favorite icon.
673 folderIconBitmap = MainWebViewActivity.favoriteIcon;
676 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
677 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
678 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
679 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
681 bookmarksDatabaseHandler.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
683 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
684 updateBookmarksListView(currentFolder);
685 bookmarksListView.setSelection(selectedBookmarkPosition);
687 } else { // Don't edit the folder because the new name is not unique.
688 String cannot_rename_folder = getResources().getString(R.string.cannot_rename_folder) + " \"" + newFolderNameString + "\"";
689 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
693 private void updateBookmarksListView(String folderName) {
694 // Get a `Cursor` with the current contents of the bookmarks database.
695 bookmarksCursor = bookmarksDatabaseHandler.getAllBookmarksCursorByDisplayOrder(folderName);
697 // Setup `bookmarksCursorAdapter` with `this` context. The `false` disables autoRequery.
698 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
700 public View newView(Context context, Cursor cursor, ViewGroup parent) {
701 // Inflate the individual item layout. `false` does not attach it to the root.
702 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
706 public void bindView(View view, Context context, Cursor cursor) {
707 // Get the favorite icon byte array from the `Cursor`.
708 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
710 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
711 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
713 // Display the bitmap in `bookmarkFavoriteIcon`.
714 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
715 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
718 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
719 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
720 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
721 bookmarkNameTextView.setText(bookmarkNameString);
723 // Make the font bold for folders.
724 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
725 // The first argument is `null` because we don't want to chage the font.
726 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
727 } else { // Reset the font to default.
728 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
733 // Update the ListView.
734 bookmarksListView.setAdapter(bookmarksCursorAdapter);
736 // Set the AppBar title.
737 if (currentFolder.isEmpty()) {
738 appBar.setTitle(R.string.bookmarks);
740 appBar.setTitle(currentFolder);
744 private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
745 // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
746 bookmarksCursor = bookmarksDatabaseHandler.getBookmarksCursorExcept(exceptIdLongArray, folderName);
748 // Setup `bookmarksCursorAdapter` with `this` context. The `false` disables autoRequery.
749 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
751 public View newView(Context context, Cursor cursor, ViewGroup parent) {
752 // Inflate the individual item layout. `false` does not attach it to the root.
753 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
757 public void bindView(View view, Context context, Cursor cursor) {
758 // Get the favorite icon byte array from the cursor.
759 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
761 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
762 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
764 // Display the bitmap in `bookmarkFavoriteIcon`.
765 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
766 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
769 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
770 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
771 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
772 bookmarkNameTextView.setText(bookmarkNameString);
774 // Make the font bold for folders.
775 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHandler.IS_FOLDER)) == 1) {
776 // The first argument is `null` because we don't want to chage the font.
777 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
778 } else { // Reset the font to default.
779 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
784 // Update the ListView.
785 bookmarksListView.setAdapter(bookmarksCursorAdapter);