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.database.Cursor;
26 import android.graphics.Bitmap;
27 import android.graphics.BitmapFactory;
28 import android.graphics.drawable.BitmapDrawable;
29 import android.graphics.drawable.Drawable;
30 import android.os.Bundle;
31 import android.support.design.widget.FloatingActionButton;
32 import android.support.design.widget.Snackbar;
33 import android.support.v4.app.NavUtils;
34 import android.support.v4.widget.CursorAdapter;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.widget.Toolbar;
38 import android.view.ActionMode;
39 import android.view.Menu;
40 import android.view.MenuItem;
41 import android.view.View;
42 import android.view.ViewGroup;
43 import android.widget.AbsListView;
44 import android.widget.AdapterView;
45 import android.widget.CheckBox;
46 import android.widget.EditText;
47 import android.widget.ImageView;
48 import android.widget.ListView;
49 import android.widget.TextView;
51 import java.io.ByteArrayOutputStream;
53 public class BookmarksActivity extends AppCompatActivity implements CreateBookmark.CreateBookmarkListener, EditBookmark.EditBookmarkListener {
54 // `bookmarksDatabaseHandler` is public static so it can be accessed from EditBookmark. It is also used in `onCreate()`,
55 // `onCreateBookmarkCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
56 public static BookmarksDatabaseHandler bookmarksDatabaseHandler;
58 // `bookmarksListView` is public static so it can be accessed from EditBookmark.
59 // It is also used in `onCreate()`, `updateBookmarksListView()`, and `updateBookmarksListViewExcept()`.
60 public static ListView bookmarksListView;
62 // `contextualActionMode` is used in `onCreate()` and `onEditBookmarkSave()`.
63 private ActionMode contextualActionMode;
66 protected void onCreate(Bundle savedInstanceState) {
67 super.onCreate(savedInstanceState);
68 setContentView(R.layout.bookmarks_coordinatorlayout);
70 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
71 final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
72 setSupportActionBar(bookmarksAppBar);
74 // Display the home arrow on supportAppBar.
75 final ActionBar appBar = getSupportActionBar();
76 assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
77 appBar.setDisplayHomeAsUpEnabled(true);
79 // Initialize the database handler and the ListView.
80 // `this` specifies the context. The two `null`s do not specify the database name or a `CursorFactory`.
81 // The `0` is to specify a database version, but that is set instead using a constant in BookmarksDatabaseHandler.
82 bookmarksDatabaseHandler = new BookmarksDatabaseHandler(this, null, null, 0);
83 bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
85 // Display the bookmarks in the ListView.
86 updateBookmarksListView();
88 // Set a listener so that tapping a list item loads the URL. We need to store the activity
89 // in a variable so that we can return to the parent activity after loading the URL.
90 final Activity bookmarksActivity = this;
91 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
93 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
94 // Convert the id from long to int to match the format of the bookmarks database.
95 int databaseID = (int) id;
97 // Get the bookmark URL and assign it to formattedUrlString.
98 MainWebViewActivity.formattedUrlString = bookmarksDatabaseHandler.getBookmarkURL(databaseID);
100 // Load formattedUrlString and return to the main activity.
101 MainWebViewActivity.mainWebView.loadUrl(MainWebViewActivity.formattedUrlString);
102 NavUtils.navigateUpFromSameTask(bookmarksActivity);
106 // `MultiChoiceModeListener` handles long clicks.
107 bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
108 // `editBookmarkMenuItem` is used in `onCreateActionMode()` and `onItemCheckedStateChanged`.
109 MenuItem editBookmarkMenuItem;
111 // `selectAllBookmarks` is used in `onCreateActionMode()` and `onItemCheckedStateChanges`.
112 MenuItem selectAllBookmarks;
115 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
116 // Inflate the menu for the contextual app bar and set the title.
117 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
118 mode.setTitle(R.string.bookmarks);
120 // Get a handle for `R.id.edit_bookmark` and `R.id.select_all_bookmarks`.
121 editBookmarkMenuItem = menu.findItem(R.id.edit_bookmark);
122 selectAllBookmarks = menu.findItem(R.id.context_menu_select_all_bookmarks);
128 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
133 public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
134 // Get an array of the selected bookmarks.
135 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
137 // Calculate the number of selected bookmarks.
138 int numberOfSelectedBookmarks = selectedBookmarksLongArray.length;
140 // List the number of selected bookmarks in the subtitle.
141 mode.setSubtitle(numberOfSelectedBookmarks + " " + getString(R.string.selected));
143 // Show the `Edit` option only if 1 bookmark is selected.
144 if (numberOfSelectedBookmarks < 2) {
145 editBookmarkMenuItem.setVisible(true);
147 editBookmarkMenuItem.setVisible(false);
150 // Do not show `Select All` if all the bookmarks are already checked.
151 if (bookmarksListView.getCheckedItemIds().length == bookmarksListView.getCount()) {
152 selectAllBookmarks.setVisible(false);
154 selectAllBookmarks.setVisible(true);
159 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
160 int menuItemId = item.getItemId();
162 switch (menuItemId) {
163 case R.id.edit_bookmark:
164 // Show the `EditBookmark` `AlertDialog` and name the instance `@string/edit_bookmark`.
165 DialogFragment editBookmarkDialog = new EditBookmark();
166 editBookmarkDialog.show(getFragmentManager(), "@string/edit_bookmark");
168 contextualActionMode = mode;
171 case R.id.delete_bookmark:
172 // Get an array of the selected rows.
173 final long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
175 String snackbarMessage;
177 // Determine how many items are in the array and prepare an appropriate Snackbar message.
178 if (selectedBookmarksLongArray.length == 1) {
179 snackbarMessage = getString(R.string.one_bookmark_deleted);
181 snackbarMessage = selectedBookmarksLongArray.length + " " + getString(R.string.bookmarks_deleted);
184 updateBookmarksListViewExcept(selectedBookmarksLongArray);
187 Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
188 .setAction(R.string.undo, new View.OnClickListener() {
190 public void onClick(View view) {
191 // Do nothing because everything will be handled by `onDismissed()` below.
194 .setCallback(new Snackbar.Callback() {
196 public void onDismissed(Snackbar snackbar, int event) {
198 // The user pushed the "Undo" button.
199 case Snackbar.Callback.DISMISS_EVENT_ACTION:
200 // Refresh the ListView to show the rows again.
201 updateBookmarksListView();
205 // The Snackbar was dismissed without the "Undo" button being pushed.
207 // Delete each selected row.
208 for (long databaseIdLong : selectedBookmarksLongArray) {
209 // Convert `databaseIdLong` to an int.
210 int databaseIdInt = (int) databaseIdLong;
212 // Delete the database row.
213 bookmarksDatabaseHandler.deleteBookmark(databaseIdInt);
221 // Close the contextual app bar.
225 case R.id.context_menu_select_all_bookmarks:
226 int numberOfBookmarks = bookmarksListView.getCount();
228 for (int i = 0; i < numberOfBookmarks; i++) {
229 bookmarksListView.setItemChecked(i, true);
233 // Consume the click.
238 public void onDestroyActionMode(ActionMode mode) {
243 // Set a FloatingActionButton for creating new bookmarks.
244 FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
245 assert createBookmarkFAB != null;
246 createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
248 public void onClick(View view) {
249 // Show the `CreateBookmark` `AlertDialog` and name the instance `@string/create_bookmark`.
250 DialogFragment createBookmarkDialog = new CreateBookmark();
251 createBookmarkDialog.show(getFragmentManager(), "@string/create_bookmark");
257 public boolean onCreateOptionsMenu(Menu menu) {
259 getMenuInflater().inflate(R.menu.bookmarks_options_menu, menu);
265 public boolean onPrepareOptionsMenu(Menu menu) {
266 super.onPrepareOptionsMenu(menu);
272 public boolean onOptionsItemSelected(MenuItem menuItem) {
273 int menuItemId = menuItem.getItemId();
275 switch (menuItemId) {
276 case android.R.id.home:
277 NavUtils.navigateUpFromSameTask(this);
280 case R.id.options_menu_select_all_bookmarks:
281 int numberOfBookmarks = bookmarksListView.getCount();
283 for (int i = 0; i < numberOfBookmarks; i++) {
284 bookmarksListView.setItemChecked(i, true);
292 public void onCreateBookmarkCancel(DialogFragment createBookmarkDialogFragment) {
293 // Do nothing because the user selected `Cancel`.
297 public void onCreateBookmarkCreate(DialogFragment createBookmarkDialogFragment) {
298 // Get the `EditText`s from the `createBookmarkDialogFragment` and extract the strings.
299 EditText createBookmarkNameEditText = (EditText) createBookmarkDialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
300 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
301 EditText createBookmarkUrlEditText = (EditText) createBookmarkDialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
302 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
304 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
305 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
306 MainWebViewActivity.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
307 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
309 // Create the bookmark.
310 bookmarksDatabaseHandler.createBookmark(bookmarkNameString, bookmarkUrlString, favoriteIconByteArray);
312 // Refresh the ListView.
313 updateBookmarksListView();
317 public void onEditBookmarkCancel(DialogFragment editBookmarkDialogFragment) {
318 // Do nothing because the user selected `Cancel`.
322 public void onEditBookmarkSave(DialogFragment editBookmarkDialogFragment) {
323 // Get the `EditText`s from the `editBookmarkDialogFragment` and extract the strings.
324 EditText editBookmarkNameEditText = (EditText) editBookmarkDialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
325 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
326 EditText editBookmarkUrlEditText = (EditText) editBookmarkDialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
327 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
329 CheckBox useNewFavoriteIconBitmap = (CheckBox) editBookmarkDialogFragment.getDialog().findViewById(R.id.edit_bookmark_use_new_favorite_icon_checkbox);
330 byte[] favoriteIconByteArray;
332 // Get a long array with the the databaseId of the selected bookmark and convert it to an `int`.
333 long[] selectedBookmarksLongArray = bookmarksListView.getCheckedItemIds();
334 int selectedBookmarkDatabaseId = (int) selectedBookmarksLongArray[0];
336 if (useNewFavoriteIconBitmap.isChecked()) {
337 ImageView newFavoriteIconImageView = (ImageView) editBookmarkDialogFragment.getDialog().findViewById(R.id.edit_bookmark_new_favorite_icon);
338 Drawable favoriteIconDrawable = newFavoriteIconImageView.getDrawable();
339 Bitmap favoriteIconBitmap = ((BitmapDrawable) favoriteIconDrawable).getBitmap();
340 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
341 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
342 favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
343 bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, favoriteIconByteArray);
346 // Update the bookmark.
347 bookmarksDatabaseHandler.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
350 contextualActionMode.finish();
352 // Refresh the `ListView`.
353 updateBookmarksListView();
356 private void updateBookmarksListView() {
357 // Get a Cursor with the current contents of the bookmarks database.
358 final Cursor bookmarksCursor = bookmarksDatabaseHandler.getAllBookmarksCursor();
360 // Setup bookmarksCursorAdapter with `this` context. The `false` disables autoRequery.
361 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
363 public View newView(Context context, Cursor cursor, ViewGroup parent) {
364 // Inflate the individual item layout. `false` does not attach it to the root.
365 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
369 public void bindView(View view, Context context, Cursor cursor) {
370 // Get the favorite icon byte array from the `Cursor`.
371 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
373 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
374 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
376 // Display the bitmap in `bookmarkFavoriteIcon`.
377 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
378 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
381 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
382 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
383 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
384 assert bookmarkNameTextView != null; // This assert removes the warning that bookmarkNameTextView might be null.
385 bookmarkNameTextView.setText(bookmarkNameString);
389 // Update the ListView.
390 bookmarksListView.setAdapter(bookmarksCursorAdapter);
393 private void updateBookmarksListViewExcept(long[] exceptIdLongArray) {
394 // Get a Cursor with the current contents of the bookmarks database except for the specified database IDs.
395 final Cursor bookmarksCursor = bookmarksDatabaseHandler.getBookmarksCursorExcept(exceptIdLongArray);
397 // Setup bookmarksCursorAdapter with `this` context. The `false` disables autoRequery.
398 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
400 public View newView(Context context, Cursor cursor, ViewGroup parent) {
401 // Inflate the individual item layout. `false` does not attach it to the root.
402 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
406 public void bindView(View view, Context context, Cursor cursor) {
407 // Get the favorite icon byte array from the cursor.
408 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITE_ICON));
410 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
411 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
413 // Display the bitmap in `bookmarkFavoriteIcon`.
414 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
415 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
418 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
419 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
420 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
421 assert bookmarkNameTextView != null; // This assert removes the warning that bookmarkNameTextView might be null.
422 bookmarkNameTextView.setText(bookmarkNameString);
426 // Update the ListView.
427 bookmarksListView.setAdapter(bookmarksCursorAdapter);