2 * Copyright © 2016-2017 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.app.Activity;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.database.Cursor;
26 import android.graphics.Bitmap;
27 import android.graphics.BitmapFactory;
28 import android.graphics.Typeface;
29 import android.graphics.drawable.BitmapDrawable;
30 import android.graphics.drawable.Drawable;
31 import android.os.Bundle;
32 import android.support.design.widget.FloatingActionButton;
33 import android.support.design.widget.Snackbar;
34 import android.support.v4.app.NavUtils;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.support.v7.widget.Toolbar;
39 import android.util.SparseBooleanArray;
40 import android.view.ActionMode;
41 import android.view.Menu;
42 import android.view.MenuItem;
43 import android.view.View;
44 import android.view.ViewGroup;
45 import android.widget.AbsListView;
46 import android.widget.AdapterView;
47 import android.widget.CursorAdapter;
48 import android.widget.EditText;
49 import android.widget.ImageView;
50 import android.widget.ListView;
51 import android.widget.RadioButton;
52 import android.widget.TextView;
54 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
55 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
56 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
57 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
58 import com.stoutner.privacybrowser.dialogs.MoveToFolderDialog;
59 import com.stoutner.privacybrowser.R;
60 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
62 import java.io.ByteArrayOutputStream;
64 public class BookmarksActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
65 MoveToFolderDialog.MoveToFolderListener {
67 // `bookmarksDatabaseHelper` is public static so it can be accessed from `EditBookmarkDialog` and `MoveToFolderDialog`. It is also used in `onCreate()`,
68 // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
69 public static BookmarksDatabaseHelper bookmarksDatabaseHelper;
71 // `currentFolder` is public static so it can be accessed from `MoveToFolderDialog`.
72 // It is used in `onCreate`, `onOptionsItemSelected()`, `onCreateBookmarkCreate`, `onCreateBookmarkFolderCreate`, and `onEditBookmarkSave`.
73 public static String currentFolder;
75 // `checkedItemIds` is public static so it can be accessed from `EditBookmarkDialog`, `EditBookmarkFolderDialog`, and `MoveToFolderDialog`.
76 // It is also used in `onActionItemClicked`.
77 public static long[] checkedItemIds;
80 // `bookmarksListView` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
81 private ListView bookmarksListView;
83 // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
84 private ActionMode contextualActionMode;
86 // `selectedBookmarkPosition` is used in `onCreate()` and `onEditBookmarkSave()`.
87 private int selectedBookmarkPosition;
89 // `appBar` is used in `onCreate()` and `updateBookmarksListView()`.
90 private ActionBar appBar;
92 // `bookmarksCursor` is used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
93 private Cursor bookmarksCursor;
95 // `oldFolderName` is used in `onCreate()` and `onEditBookmarkFolderSave()`.
96 private String oldFolderNameString;
99 protected void onCreate(Bundle savedInstanceState) {
100 // Set the activity theme.
101 if (MainWebViewActivity.darkTheme) {
102 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
104 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
107 // Run the default commands.
108 super.onCreate(savedInstanceState);
110 // Set the content view.
111 setContentView(R.layout.bookmarks_coordinatorlayout);
113 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
114 final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
115 setSupportActionBar(bookmarksAppBar);
117 // Display the home arrow on `SupportActionBar`.
118 appBar = getSupportActionBar();
119 assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that `appBar` might be null.
120 appBar.setDisplayHomeAsUpEnabled(true);
123 // Initialize the database handler and the `ListView`. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
124 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
125 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
126 bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
128 // Set currentFolder to the home folder, which is `""` in the database.
131 // Display the bookmarks in the ListView.
132 updateBookmarksListView(currentFolder);
134 // Set a listener so that tapping a list item loads the URL. We need to store the activity in a variable so that we can return to the parent activity after loading the URL.
135 final Activity bookmarksActivity = this;
136 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
138 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
139 // Convert the id from long to int to match the format of the bookmarks database.
140 int databaseID = (int) id;
142 // Get the bookmark `Cursor` for this ID and move it to the first row.
143 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
144 bookmarkCursor.moveToFirst();
146 // If the bookmark is a folder load its contents into the ListView.
147 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
148 // Update `currentFolder`.
149 currentFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
151 // Reload the ListView with `currentFolder`.
152 updateBookmarksListView(currentFolder);
153 } else { // Load the URL into `mainWebView`.
154 // Get the bookmark URL and assign it to formattedUrlString. `mainWebView` will automatically reload when `BookmarksActivity` closes.
155 MainWebViewActivity.formattedUrlString = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
157 NavUtils.navigateUpFromSameTask(bookmarksActivity);
160 // Close the `Cursor`.
161 bookmarkCursor.close();
165 // `MultiChoiceModeListener` handles long clicks.
166 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
167 // `moveBookmarkUpMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
168 MenuItem moveBookmarkUpMenuItem;
170 // `moveBookmarkDownMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
171 MenuItem moveBookmarkDownMenuItem;
173 // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
174 MenuItem editBookmarkMenuItem;
176 // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
177 MenuItem selectAllBookmarksMenuItem;
180 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
181 // Inflate the menu for the contextual app bar and set the title.
182 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
185 if (currentFolder.isEmpty()) {
186 // Use `R.string.bookmarks` if we are in the home folder.
187 mode.setTitle(R.string.bookmarks);
188 } else { // Use the current folder name as the title.
189 mode.setTitle(currentFolder);
192 // Get a handle for MenuItems we need to selectively disable.
193 moveBookmarkUpMenuItem = menu.findItem(R.id.move_bookmark_up);
194 moveBookmarkDownMenuItem = menu.findItem(R.id.move_bookmark_down);
195 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
196 selectAllBookmarksMenuItem = menu.findItem(R.id.context_menu_select_all_bookmarks);
198 // Store `contextualActionMode` so we can close it programatically.
199 contextualActionMode = mode;
205 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
210 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
211 // Get an array of the selected bookmarks.
212 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
214 // Calculate the number of selected bookmarks.
215 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
217 // Adjust the `mode` and the menu for the number of selected bookmarks.
218 if (numberOfSelectedBookmarks == 0) {
220 } else if (numberOfSelectedBookmarks == 1) {
221 // List the number of selected bookmarks in the subtitle.
222 mode.setSubtitle(getString(R.string.one_selected));
224 // Show the `Move Up`, `Move Down`, and `Edit` options.
225 moveBookmarkUpMenuItem.setVisible(true);
226 moveBookmarkDownMenuItem.setVisible(true);
227 editBookmarkMenuItem.setVisible(true);
229 // Get the database IDs for the bookmarks.
230 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
231 int firstBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(0);
232 // bookmarksListView is 0 indexed.
233 int lastBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(bookmarksListView.getCount() - 1);
235 // Disable `moveBookmarkUpMenuItem` if the selected bookmark is at the top of the ListView.
236 if (selectedBookmarkDatabaseId == firstBookmarkDatabaseId) {
237 moveBookmarkUpMenuItem.setEnabled(false);
238 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_disabled);
239 } else { // Otherwise enable `moveBookmarkUpMenuItem`.
240 moveBookmarkUpMenuItem.setEnabled(true);
242 // Set the icon according to the theme.
243 if (MainWebViewActivity.darkTheme) {
244 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_dark);
246 moveBookmarkUpMenuItem.setIcon(R.drawable.move_up_enabled_light);
250 // Disable `moveBookmarkDownMenuItem` if the selected bookmark is at the bottom of the ListView.
251 if (selectedBookmarkDatabaseId == lastBookmarkDatabaseId) {
252 moveBookmarkDownMenuItem.setEnabled(false);
253 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_disabled);
254 } else { // Otherwise enable `moveBookmarkDownMenuItem`.
255 moveBookmarkDownMenuItem.setEnabled(true);
257 // Set the icon according to the theme.
258 if (MainWebViewActivity.darkTheme) {
259 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_dark);
261 moveBookmarkDownMenuItem.setIcon(R.drawable.move_down_enabled_light);
264 } else { // More than one bookmark is selected.
265 // List the number of selected bookmarks in the subtitle.
266 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
268 // Hide non-applicable `MenuItems`.
269 moveBookmarkUpMenuItem.setVisible(false);
270 moveBookmarkDownMenuItem.setVisible(false);
271 editBookmarkMenuItem.setVisible(false);
274 // Do not show `Select All` if all the bookmarks are already checked.
275 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
276 selectAllBookmarksMenuItem.setVisible(false);
278 selectAllBookmarksMenuItem.setVisible(true);
283 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
284 int menuItemId = item.getItemId();
286 // `numberOfBookmarks` is used in `R.id.move_bookmark_up_enabled`, `R.id.move_bookmark_down_enabled`, and `R.id.context_menu_select_all_bookmarks`.
287 int numberOfBookmarks;
289 // `selectedBookmarkLongArray` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
290 long[]selectedBookmarkLongArray;
291 // `selectedBookmarkDatabaseId` is used in `R.id.move_bookmark_up`, `R.id.move_bookmark_down`, and `R.id.edit_bookmark`.
292 int selectedBookmarkDatabaseId;
293 // `selectedBookmarkNewPosition` is used in `R.id.move_bookmark_up` and `R.id.move_bookmark_down`.
294 int selectedBookmarkNewPosition;
295 // `bookmarkPositionSparseBooleanArray` is used in `R.id.edit_bookmark` and `R.id.delete_bookmark`.
296 SparseBooleanArray bookmarkPositionSparseBooleanArray;
298 switch (menuItemId) {
299 case R.id.move_bookmark_up:
300 // Get the selected bookmark database ID.
301 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
302 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
304 // Initialize `selectedBookmarkNewPosition`.
305 selectedBookmarkNewPosition = 0;
307 for (int i = 0; i < bookmarksListView.getCount(); i++) {
308 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
309 int nextBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i + 1);
311 if (databaseId == selectedBookmarkDatabaseId || nextBookmarkDatabaseId == selectedBookmarkDatabaseId) {
312 if (databaseId == selectedBookmarkDatabaseId) {
313 // Move the selected bookmark up one and store the new bookmark position.
314 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i - 1);
315 selectedBookmarkNewPosition = i - 1;
316 } else { // Move the bookmark above the selected bookmark down one.
317 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
320 // Reset the rest of the bookmarks' DISPLAY_ORDER to match the position in the ListView.
321 // This isn't necessary, but it clears out any stray values that might have crept into the database.
322 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i);
326 // Refresh the ListView.
327 updateBookmarksListView(currentFolder);
329 // Select the previously selected bookmark in the new location.
330 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
332 // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
333 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
337 case R.id.move_bookmark_down:
338 // Get the selected bookmark database ID.
339 selectedBookmarkLongArray = bookmarksListView.getCheckedItemIds();
340 selectedBookmarkDatabaseId = (int) selectedBookmarkLongArray[0];
342 // Initialize `selectedBookmarkNewPosition`.
343 selectedBookmarkNewPosition = 0;
345 for (int i = 0; i <bookmarksListView.getCount(); i++) {
346 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
347 int previousBookmarkDatabaseId = (int) bookmarksListView.getItemIdAtPosition(i - 1);
349 if (databaseId == selectedBookmarkDatabaseId || previousBookmarkDatabaseId == selectedBookmarkDatabaseId) {
350 if (databaseId == selectedBookmarkDatabaseId) {
351 // Move the selected bookmark down one and store the new bookmark position.
352 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
353 selectedBookmarkNewPosition = i + 1;
354 } else { // Move the bookmark below the selected bookmark up one.
355 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i - 1);
358 // Reset the rest of the bookmark' DISPLAY_ORDER to match the position in the ListView.
359 // This isn't necessary, but it clears out any stray values that might have crept into the database.
360 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i);
364 // Refresh the ListView.
365 updateBookmarksListView(currentFolder);
367 // Select the previously selected bookmark in the new location.
368 bookmarksListView.setItemChecked(selectedBookmarkNewPosition, true);
370 // Scroll `bookmarksListView` to five items above `selectedBookmarkNewPosition`.
371 bookmarksListView.setSelection(selectedBookmarkNewPosition - 5);
374 case R.id.move_to_folder:
375 // Store `checkedItemIds` for use by the `AlertDialog`.
376 checkedItemIds = bookmarksListView.getCheckedItemIds();
378 // Show the `MoveToFolderDialog` `AlertDialog` and name the instance `@string/move_to_folder
379 AppCompatDialogFragment moveToFolderDialog = new MoveToFolderDialog();
380 moveToFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.move_to_folder));
383 case R.id.edit_bookmark:
384 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
385 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
386 for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
387 // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
388 if (bookmarkPositionSparseBooleanArray.valueAt(i))
389 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
392 // Move to the selected database ID and find out if it is a folder.
393 bookmarksCursor.moveToPosition(selectedBookmarkPosition);
394 boolean isFolder = (bookmarksCursor.getInt(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1);
396 // Store `checkedItemIds` for use by the `AlertDialog`.
397 checkedItemIds = bookmarksListView.getCheckedItemIds();
400 // Save the current folder name.
401 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
403 // Show the `EditBookmarkFolderDialog` `AlertDialog` and name the instance `@string/edit_folder`.
404 AppCompatDialogFragment editFolderDialog = new EditBookmarkFolderDialog();
405 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
407 // Show the `EditBookmarkDialog` `AlertDialog` and name the instance `@string/edit_bookmark`.
408 AppCompatDialogFragment editBookmarkDialog = new EditBookmarkDialog();
409 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
413 case R.id.delete_bookmark:
414 // Get an array of the selected rows.
415 final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
417 // Get a handle for `selectedBookmarkPosition` so we can scroll to it after refreshing the ListView.
418 bookmarkPositionSparseBooleanArray = bookmarksListView.getCheckedItemPositions();
419 for (int i = 0; i < bookmarkPositionSparseBooleanArray.size(); i++) {
420 // Find the bookmark that is selected and save the position to `selectedBookmarkPosition`.
421 if (bookmarkPositionSparseBooleanArray.valueAt(i))
422 selectedBookmarkPosition = bookmarkPositionSparseBooleanArray.keyAt(i);
425 updateBookmarksListViewExcept(selectedBookmarksLongArray, currentFolder);
427 // Scroll to where the deleted bookmark was located.
428 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
430 // Initialize `snackbarMessage`.
431 String snackbarMessage;
433 // Determine how many items are in the array and prepare an appropriate Snackbar message.
434 if (selectedBookmarksLongArray.length == 1) {
435 snackbarMessage = getString(R.string.one_bookmark_deleted);
437 snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
441 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
442 .setAction(R.string.undo, new View.OnClickListener() {
444 public void onClick(View view) {
445 // Do nothing because everything will be handled by `onDismissed()` below.
448 .addCallback(new Snackbar.Callback() {
450 public void onDismissed(Snackbar snackbar, int event) {
452 // The user pushed the `Undo` button.
453 case Snackbar.Callback.DISMISS_EVENT_ACTION:
454 // Refresh the ListView to show the rows again.
455 updateBookmarksListView(currentFolder);
457 // Scroll to where the deleted bookmark was located.
458 bookmarksListView.setSelection(selectedBookmarkPosition - 5);
461 // The `Snackbar` was dismissed without the `Undo` button being pushed.
463 // Delete each selected row.
464 for (long databaseIdLong : selectedBookmarksLongArray) {
465 // Convert `databaseIdLong` to an int.
466 int databaseIdInt = (int) databaseIdLong;
468 if (bookmarksDatabaseHelper.isFolder(databaseIdInt)) {
469 deleteBookmarkFolderContents(databaseIdInt);
472 // Delete `databaseIdInt`.
473 bookmarksDatabaseHelper.deleteBookmark(databaseIdInt);
481 // Close the contextual app bar.
485 case R.id.context_menu_select_all_bookmarks:
486 numberOfBookmarks = bookmarksListView.getCount();
488 for (int i = 0; i < numberOfBookmarks; i++) {
489 bookmarksListView.setItemChecked(i, true);
493 // Consume the click.
498 public void onDestroyActionMode(ActionMode mode) {
503 // Set a FloatingActionButton for creating new bookmarks.
504 FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
505 createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
507 public void onClick(View view) {
508 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
509 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
510 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
516 public boolean onCreateOptionsMenu(Menu menu) {
518 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
525 public boolean onOptionsItemSelected(MenuItem menuItem) {
526 // Get the ID of the `MenuItem` that was selected.
527 int menuItemId = menuItem.getItemId();
529 switch (menuItemId) {
530 case android.R.id.home: // The home arrow is identified as `android.R.id.home`, not just `R.id.home`.
531 if (currentFolder.isEmpty()) { // Exit BookmarksActivity if currently in the home folder.
532 NavUtils.navigateUpFromSameTask(this);
533 } else { // Navigate up one folder.
534 // Place the former parent folder in `currentFolder`.
535 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
537 // Update `bookmarksListView`.
538 updateBookmarksListView(currentFolder);
542 case R.id.create_folder:
543 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
544 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
545 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
548 case R.id.options_menu_select_all_bookmarks:
549 int numberOfBookmarks = bookmarksListView.getCount();
551 for (int i = 0; i < numberOfBookmarks; i++) {
552 bookmarksListView.setItemChecked(i, true);
556 case R.id.bookmarks_database_view:
557 // Launch `BookmarksDatabaseViewActivity`.
558 Intent bookmarksDatabaseViewIntent = new Intent(this, BookmarksDatabaseViewActivity.class);
559 startActivity(bookmarksDatabaseViewIntent);
566 public void onBackPressed() {
567 if (currentFolder.isEmpty()) { // Exit BookmarksActivity if currently in the home folder.
568 super.onBackPressed();
569 } else { // Navigate up one folder.
570 // Place the former parent folder in `currentFolder`.
571 currentFolder = bookmarksDatabaseHelper.getParentFolder(currentFolder);
573 // Reload the `ListView`.
574 updateBookmarksListView(currentFolder);
579 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
580 // Get the `EditTexts` from the `dialogFragment`.
581 EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
582 EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
584 // Extract the strings from the `EditTexts`.
585 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
586 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
588 // Convert the favoriteIcon Bitmap to a byte array.
589 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
590 // `0` is for lossless compression (the only option for a PNG).
591 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
592 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
594 // Display the new bookmark below the current items in the (0 indexed) list.
595 int newBookmarkDisplayOrder = bookmarksListView.getCount();
597 // Create the bookmark.
598 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentFolder, favoriteIconByteArray);
600 // Refresh the `ListView`. `setSelection` scrolls to the bottom of the list.
601 updateBookmarksListView(currentFolder);
602 bookmarksListView.setSelection(newBookmarkDisplayOrder);
606 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
607 // Get `create_folder_name_edit_text` and extract the string.
608 EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
609 String folderNameString = createFolderNameEditText.getText().toString();
611 // Check to see if the folder already exists.
612 Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(folderNameString);
613 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
614 bookmarkFolderCursor.close();
615 if (folderNameString.isEmpty() || (existingFoldersWithNewName > 0)) {
616 String cannotCreateFolder = getResources().getString(R.string.cannot_create_folder) + " \"" + folderNameString + "\"";
617 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannotCreateFolder, Snackbar.LENGTH_INDEFINITE).show();
618 } else { // Create the folder.
619 // Get the new folder icon `Bitmap`.
620 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
621 Bitmap folderIconBitmap;
622 if (defaultFolderIconRadioButton.isChecked()) {
623 // Get the default folder icon `ImageView` from the `Dialog` and convert it to a `Bitmap`.
624 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
625 Drawable folderIconDrawable = folderIconImageView.getDrawable();
626 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
627 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
628 } else { // Assign `favoriteIcon` from the `WebView`.
629 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
632 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
633 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
634 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
635 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
637 // Move all the bookmarks down one in the display order.
638 for (int i = 0; i < bookmarksListView.getCount(); i++) {
639 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
640 bookmarksDatabaseHelper.updateBookmarkDisplayOrder(databaseId, i + 1);
643 // Create the folder, placing it at the top of the ListView
644 bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentFolder, folderIconByteArray);
646 // Refresh the ListView.
647 updateBookmarksListView(currentFolder);
652 public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment) {
653 // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
654 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
655 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
657 // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
658 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
659 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
660 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
661 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
663 // Get `edit_bookmark_current_icon_radiobutton`.
664 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
666 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
667 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
668 } else { // Update the bookmark using the `WebView` favorite icon.
669 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
670 MainWebViewActivity.favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
671 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
673 // Update the bookmark and the favorite icon.
674 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
677 // Close the contextual action mode.
678 contextualActionMode.finish();
680 // Refresh the `ListView`. `setSelection` scrolls to the position of the bookmark that was edited.
681 updateBookmarksListView(currentFolder);
682 bookmarksListView.setSelection(selectedBookmarkPosition);
686 public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment) {
687 // Get the new folder name.
688 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
689 String newFolderNameString = editFolderNameEditText.getText().toString();
691 // Check to see if the new folder name is unique.
692 Cursor bookmarkFolderCursor = bookmarksDatabaseHelper.getFolderCursor(newFolderNameString);
693 int existingFoldersWithNewName = bookmarkFolderCursor.getCount();
694 bookmarkFolderCursor.close();
695 if ( ((existingFoldersWithNewName == 0) || newFolderNameString.equals(oldFolderNameString)) && !newFolderNameString.isEmpty()) {
696 // Get a long array with the the database ID of the selected folder and convert it to an `int`.
697 long[] selectedFolderLongArray = bookmarksListView.getCheckedItemIds();
698 int selectedFolderDatabaseId = (int) selectedFolderLongArray[0];
700 // Get the `RadioButtons` from the `Dialog`.
701 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
702 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
704 // Check if the favorite icon has changed.
705 if (currentFolderIconRadioButton.isChecked()) {
706 // Update the folder name if it has changed without modifying the favorite icon.
707 if (!newFolderNameString.equals(oldFolderNameString)) {
708 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
710 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
711 updateBookmarksListView(currentFolder);
712 bookmarksListView.setSelection(selectedBookmarkPosition);
714 } else { // Update the folder icon.
715 // Get the new folder icon `Bitmap`.
716 Bitmap folderIconBitmap;
717 if (defaultFolderIconRadioButton.isChecked()) {
718 // Get the default folder icon `ImageView` from the `Drawable` and convert it to a `Bitmap`.
719 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
720 Drawable folderIconDrawable = folderIconImageView.getDrawable();
721 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
722 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
723 } else { // Get the web page icon `ImageView` from the `Dialog`.
724 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
727 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
728 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
729 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
730 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
732 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
734 // Refresh the `ListView`. `setSelection` scrolls to the position of the folder that was edited.
735 updateBookmarksListView(currentFolder);
736 bookmarksListView.setSelection(selectedBookmarkPosition);
738 } else { // Don't edit the folder because the new name is not unique.
739 String cannot_rename_folder = getResources().getString(R.string.cannot_save_folder) + " \"" + newFolderNameString + "\"";
740 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), cannot_rename_folder, Snackbar.LENGTH_INDEFINITE).show();
743 // Close the contextual action mode.
744 contextualActionMode.finish();
748 public void onMoveToFolder(AppCompatDialogFragment dialogFragment) {
749 // Get the new folder database id.
750 ListView folderListView = (ListView) dialogFragment.getDialog().findViewById(R.id.move_to_folder_listview);
751 long[] newFolderLongArray = folderListView.getCheckedItemIds();
753 if (newFolderLongArray.length == 0) { // No new folder was selected.
754 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), getString(R.string.cannot_move_bookmarks), Snackbar.LENGTH_INDEFINITE).show();
755 } else { // Move the selected bookmarks.
756 // Get the new folder database ID.
757 int newFolderDatabaseId = (int) newFolderLongArray[0];
759 // Instantiate `newFolderName`.
760 String newFolderName;
762 if (newFolderDatabaseId == 0) {
763 // The new folder is the home folder, represented as `""` in the database.
766 // Get the new folder name from the database.
767 newFolderName = bookmarksDatabaseHelper.getFolderName(newFolderDatabaseId);
770 // Get a long array with the the database ID of the selected bookmarks.
771 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
772 for (long databaseIdLong : selectedBookmarksLongArray) {
773 // Get `databaseIdInt` for each selected bookmark.
774 int databaseIdInt = (int) databaseIdLong;
776 // Move the selected bookmark to the new folder.
777 bookmarksDatabaseHelper.moveToFolder(databaseIdInt, newFolderName);
780 // Refresh the `ListView`.
781 updateBookmarksListView(currentFolder);
783 // Close the contextual app bar.
784 contextualActionMode.finish();
788 private void updateBookmarksListView(String folderName) {
789 // Get a `Cursor` with the current contents of the bookmarks database.
790 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
792 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables `autoRequery`.
793 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
795 public View newView(Context context, Cursor cursor, ViewGroup parent) {
796 // Inflate the individual item layout. `false` does not attach it to the root.
797 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
801 public void bindView(View view, Context context, Cursor cursor) {
802 // Get the favorite icon byte array from the `Cursor`.
803 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
805 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
806 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
808 // Display the bitmap in `bookmarkFavoriteIcon`.
809 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
810 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
813 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
814 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
815 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
816 bookmarkNameTextView.setText(bookmarkNameString);
818 // Make the font bold for folders.
819 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
820 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
821 } else { // Reset the font to default for normal bookmarks.
822 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
827 // Update the ListView.
828 bookmarksListView.setAdapter(bookmarksCursorAdapter);
830 // Set the AppBar title.
831 if (currentFolder.isEmpty()) {
832 appBar.setTitle(R.string.bookmarks);
834 appBar.setTitle(currentFolder);
838 private void updateBookmarksListViewExcept(long[] exceptIdLongArray, String folderName) {
839 // Get a `Cursor` with the current contents of the bookmarks database except for the specified database IDs.
840 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksCursorExcept(exceptIdLongArray, folderName);
842 // Setup `bookmarksCursorAdapter` with `this` context. `false` disables autoRequery.
843 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
845 public View newView(Context context, Cursor cursor, ViewGroup parent) {
846 // Inflate the individual item layout. `false` does not attach it to the root.
847 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
851 public void bindView(View view, Context context, Cursor cursor) {
852 // Get the favorite icon byte array from the cursor.
853 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
855 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
856 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
858 // Display the bitmap in `bookmarkFavoriteIcon`.
859 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
860 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
863 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
864 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
865 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
866 bookmarkNameTextView.setText(bookmarkNameString);
868 // Make the font bold for folders.
869 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
870 // The first argument is `null` because we don't want to change the font.
871 bookmarkNameTextView.setTypeface(null, Typeface.BOLD);
872 } else { // Reset the font to default.
873 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
878 // Update the `ListView`.
879 bookmarksListView.setAdapter(bookmarksCursorAdapter);
882 private void deleteBookmarkFolderContents(int databaseId) {
883 // Get the name of the folder.
884 String folderName = bookmarksDatabaseHelper.getFolderName(databaseId);
886 // Get the contents of the folder.
887 Cursor folderCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(folderName);
889 for (int i = 0; i < folderCursor.getCount(); i++) {
890 // Move `folderCursor` to the current row.
891 folderCursor.moveToPosition(i);
893 // Get the database ID of the item.
894 int itemDatabaseId = folderCursor.getInt(folderCursor.getColumnIndex(BookmarksDatabaseHelper._ID));
896 // If this is a folder, delete the contents first.
897 if (bookmarksDatabaseHelper.isFolder(itemDatabaseId)) {
898 deleteBookmarkFolderContents(itemDatabaseId);
901 bookmarksDatabaseHelper.deleteBookmark(itemDatabaseId);