]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/BookmarksActivity.java
Add the ability to delete bookmarks.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / BookmarksActivity.java
1 /**
2  * Copyright 2016 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser;
21
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.os.Bundle;
29 import android.support.design.widget.FloatingActionButton;
30 import android.support.design.widget.Snackbar;
31 import android.support.v4.app.NavUtils;
32 import android.support.v4.widget.CursorAdapter;
33 import android.support.v7.app.ActionBar;
34 import android.support.v7.app.AppCompatActivity;
35 import android.support.v7.widget.Toolbar;
36 import android.view.ActionMode;
37 import android.view.Menu;
38 import android.view.MenuItem;
39 import android.view.View;
40 import android.view.ViewGroup;
41 import android.widget.AbsListView;
42 import android.widget.AdapterView;
43 import android.widget.EditText;
44 import android.widget.ImageView;
45 import android.widget.ListView;
46 import android.widget.TextView;
47
48 import java.io.ByteArrayOutputStream;
49
50 public class BookmarksActivity extends AppCompatActivity implements CreateBookmark.CreateBookmarkListener {
51     private BookmarksDatabaseHandler bookmarksDatabaseHandler;
52     private ListView bookmarksListView;
53
54     // deleteBookmarkMenuItem is used in onCreate() and onPrepareOptionsMenu().
55     private MenuItem deleteBookmarkMenuItem;
56
57     @Override
58     protected void onCreate(Bundle savedInstanceState) {
59         super.onCreate(savedInstanceState);
60         setContentView(R.layout.bookmarks_coordinatorlayout);
61
62         // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
63         final Toolbar bookmarksAppBar = (Toolbar) findViewById(R.id.bookmarks_toolbar);
64         setSupportActionBar(bookmarksAppBar);
65
66         // Display the home arrow on supportAppBar.
67         final ActionBar appBar = getSupportActionBar();
68         assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
69         appBar.setDisplayHomeAsUpEnabled(true);
70
71         // Initialize the database handler and the ListView.
72         bookmarksDatabaseHandler = new BookmarksDatabaseHandler(this, null, null, 0);
73         bookmarksListView = (ListView) findViewById(R.id.bookmarks_listview);
74
75         // Display the bookmarks in the ListView.
76         updateBookmarksListView();
77
78         // 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.
79         final Activity bookmarksActivity = this;
80         bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
81             @Override
82             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
83                 // Convert the id from long to int to match the format of the bookmarks database.
84                 int databaseID = (int) id;
85
86                 // Get the bookmark URL and assign it to formattedUrlString.
87                 MainWebViewActivity.formattedUrlString = bookmarksDatabaseHandler.getBookmarkURL(databaseID);
88
89                 //  Load formattedUrlString and return to the main activity.
90                 MainWebViewActivity.mainWebView.loadUrl(MainWebViewActivity.formattedUrlString);
91                 NavUtils.navigateUpFromSameTask(bookmarksActivity);
92             }
93         });
94
95         // registerForContextMenu(bookmarksListView);
96
97         bookmarksListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
98             @Override
99             public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
100                 String numberSelectedString;
101                 long[] selectedItemsLongArray = bookmarksListView.getCheckedItemIds();
102
103                 numberSelectedString = selectedItemsLongArray.length + " " + getString(R.string.selected);
104
105                 mode.setSubtitle(numberSelectedString);
106             }
107
108             @Override
109             public boolean onCreateActionMode(ActionMode mode, Menu menu) {
110                 // Inflate the menu for the contextual app bar.
111                 getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
112
113                 mode.setTitle(R.string.bookmarks);
114
115                 return true;
116             }
117
118             @Override
119             public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
120                 return false;
121             }
122
123             @Override
124             public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
125                 int menuItemId = item.getItemId();
126
127                 switch (menuItemId) {
128                     case R.id.delete_bookmark:
129                         // Get an array of the selected rows.
130                         final long[] selectedItemsLongArray = bookmarksListView.getCheckedItemIds();
131
132                         String snackbarMessage;
133
134                         // Determine how many items are in the array and prepare an appropriate Snackbar message.
135                         if (selectedItemsLongArray.length == 1) {
136                             snackbarMessage = getString(R.string.one_bookmark_deleted);
137                         } else {
138                             snackbarMessage = selectedItemsLongArray.length + " " + getString(R.string.bookmarks_deleted);
139                         }
140
141                         updateBookmarksListViewExcept(selectedItemsLongArray);
142
143                         // Show a SnackBar.
144                         Snackbar.make(findViewById(R.id.bookmarks_coordinatorlayout), snackbarMessage, Snackbar.LENGTH_LONG)
145                                 .setAction(R.string.undo, new View.OnClickListener() {
146                                     @Override
147                                     public void onClick(View view) {
148                                         // Do nothing because everything will be handled by `onDismissed()` below.
149                                     }
150                                 })
151                                 .setCallback(new Snackbar.Callback() {
152                                     @Override
153                                     public void onDismissed(Snackbar snackbar, int event) {
154                                         switch (event) {
155                                             // The user pushed the "Undo" button.
156                                             case Snackbar.Callback.DISMISS_EVENT_ACTION:
157                                                 // Refresh the ListView to show the rows again.
158                                                 updateBookmarksListView();
159
160                                                 break;
161
162                                             // The Snackbar was dismissed without the "Undo" button being pushed.
163                                             default:
164                                                 // Delete each selected row.
165                                                 for (long databaseIdLong : selectedItemsLongArray) {
166                                                     // Convert `databaseIdLong` to an int.
167                                                     int databaseIdInt = (int) databaseIdLong;
168
169                                                     // Delete the database row.
170                                                     bookmarksDatabaseHandler.deleteBookmark(databaseIdInt);
171                                                 }
172                                                 break;
173                                         }
174                                     }
175                                 })
176                                 .show();
177
178                         // Close the contextual app bar.
179                         mode.finish();
180                 }
181                 return true;
182             }
183
184             @Override
185             public void onDestroyActionMode(ActionMode mode) {
186
187             }
188         });
189
190         // Set a FloatingActionButton for creating new bookmarks.
191         FloatingActionButton createBookmarkFAB = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
192         assert createBookmarkFAB != null;
193         createBookmarkFAB.setOnClickListener(new View.OnClickListener() {
194             @Override
195             public void onClick(View view) {
196                 // Show the CreateBookmark AlertDialog and name the instance "@string/create_bookmark".
197                 DialogFragment createBookmarkDialog = new CreateBookmark();
198                 createBookmarkDialog.show(getFragmentManager(), "@string/create_bookmark");
199             }
200         });
201     }
202
203     /*
204     @Override
205     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
206         super.onCreateContextMenu(menu, v, menuInfo);
207         getMenuInflater().inflate(R.menu.bookmarks_context_menu, menu);
208     } */
209
210     /*@Override
211     public boolean onCreateOptionsMenu(Menu menu) {
212         getMenuInflater().inflate(R.menu.menu_bookmarks_options, menu);
213
214         return true;
215     }
216
217     @Override
218     public boolean onPrepareOptionsMenu(Menu menu) {
219         // Disable the delete icon.
220         deleteBookmarkMenuItem = menu.findItem(R.id.delete_bookmark);
221         deleteBookmarkMenuItem.setVisible(false);
222
223         // Run all the other default commands.
224         super.onPrepareOptionsMenu(menu);
225
226         // `return true` displays the menu;
227         return true;
228     }*/
229
230     @Override
231     public void onCreateBookmarkCancel(DialogFragment createBookmarkDialogFragment) {
232         // Do nothing because the user selected "Cancel".
233     }
234
235     @Override
236     public void onCreateBookmarkCreate(DialogFragment createBookmarkDialogFragment) {
237         // Get the EditTexts from the DialogFragment and extract the strings.
238         EditText createBookmarkNameEditText = (EditText) createBookmarkDialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
239         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
240         EditText createBookmarkURLEditText = (EditText) createBookmarkDialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
241         String bookmarkURLString = createBookmarkURLEditText.getText().toString();
242
243         // Convert the favoriteIcon Bitmap to a byte array.
244         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
245         MainWebViewActivity.favoriteIcon.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
246         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
247
248         // Create the bookmark.
249         bookmarksDatabaseHandler.createBookmark(bookmarkNameString, bookmarkURLString, favoriteIconByteArray);
250
251         // Refresh the ListView.
252         updateBookmarksListView();
253     }
254
255     private void updateBookmarksListView() {
256         // Get a Cursor with the current contents of the bookmarks database.
257         final Cursor bookmarksCursor = bookmarksDatabaseHandler.getBookmarksCursor();
258
259         // Setup bookmarksCursorAdapter with `this` context.  The `false` disables autoRequery.
260         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
261             @Override
262             public View newView(Context context, Cursor cursor, ViewGroup parent) {
263                 // Inflate the individual item layout.  `false` does not attach it to the root.
264                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
265             }
266
267             @Override
268             public void bindView(View view, Context context, Cursor cursor) {
269                 // Get the favorite icon byte array from the cursor.
270                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITEICON));
271
272                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
273                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
274
275                 // Display the bitmap in `bookmarkFavoriteIcon`.
276                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
277                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
278
279
280                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
281                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
282                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
283                 assert bookmarkNameTextView != null;  // This assert removes the warning that bookmarkNameTextView might be null.
284                 bookmarkNameTextView.setText(bookmarkNameString);
285             }
286         };
287
288         // Update the ListView.
289         bookmarksListView.setAdapter(bookmarksCursorAdapter);
290     }
291
292     private void updateBookmarksListViewExcept(long[] exceptIdLongArray) {
293         // Get a Cursor with the current contents of the bookmarks database except for the specified database IDs.
294         final Cursor bookmarksCursor = bookmarksDatabaseHandler.getBookmarksCursorExcept(exceptIdLongArray);
295
296         // Setup bookmarksCursorAdapter with `this` context.  The `false` disables autoRequery.
297         CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
298             @Override
299             public View newView(Context context, Cursor cursor, ViewGroup parent) {
300                 // Inflate the individual item layout.  `false` does not attach it to the root.
301                 return getLayoutInflater().inflate(R.layout.bookmarks_item_linearlayout, parent, false);
302             }
303
304             @Override
305             public void bindView(View view, Context context, Cursor cursor) {
306                 // Get the favorite icon byte array from the cursor.
307                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHandler.FAVORITEICON));
308
309                 // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
310                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
311
312                 // Display the bitmap in `bookmarkFavoriteIcon`.
313                 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
314                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
315
316
317                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
318                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHandler.BOOKMARK_NAME));
319                 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
320                 assert bookmarkNameTextView != null;  // This assert removes the warning that bookmarkNameTextView might be null.
321                 bookmarkNameTextView.setText(bookmarkNameString);
322             }
323         };
324
325         // Update the ListView.
326         bookmarksListView.setAdapter(bookmarksCursorAdapter);
327     }
328 }