]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/Webview.java
53311f7adb6f5c51e9c8a86193a74ee2e4d3bc2f
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / Webview.java
1 /**
2  * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of 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.annotation.SuppressLint;
23 import android.annotation.TargetApi;
24 import android.app.Activity;
25 import android.app.DownloadManager;
26 import android.content.ClipData;
27 import android.content.ClipboardManager;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.graphics.Bitmap;
31 import android.net.Uri;
32 import android.os.Build;
33 import android.os.Bundle;
34 import android.support.v4.app.DialogFragment;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.util.Patterns;
39 import android.view.KeyEvent;
40 import android.view.Menu;
41 import android.view.MenuItem;
42 import android.view.View;
43 import android.view.inputmethod.InputMethodManager;
44 import android.webkit.CookieManager;
45 import android.webkit.DownloadListener;
46 import android.webkit.WebChromeClient;
47 import android.webkit.WebStorage;
48 import android.webkit.WebView;
49 import android.webkit.WebViewClient;
50 import android.widget.EditText;
51 import android.widget.FrameLayout;
52 import android.widget.ImageView;
53 import android.widget.ProgressBar;
54 import android.widget.Toast;
55 import java.io.UnsupportedEncodingException;
56 import java.net.MalformedURLException;
57 import java.net.URL;
58 import java.net.URLEncoder;
59
60 public class Webview extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
61     // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
62     public static Bitmap favoriteIcon;
63
64     // mainWebView is used in onCreate and onOptionsItemSelected.
65     private WebView mainWebView;
66     // formattedUrlString is used in onCreate, onOptionsItemSelected, onCreateHomeScreenShortcutCreate, and loadUrlFromTextBox.
67     private String formattedUrlString;
68     // homepage is used in onCreate and onOptionsItemSelected.
69     private String homepage = "https://www.duckduckgo.com/";
70     // enableJavaScript is used in onCreate, onCreateOptionsMenu, and onOptionsItemSelected.
71     private boolean enableJavaScript;
72     // enableDomStorage is used in onCreate, onCreateOptionsMenu, and onOptionsItemSelected.
73     private boolean enableDomStorage;
74
75     /*  enableSaveFormData does nothing until database storage is implemented.
76     // enableSaveFormData is used in onCreate, onCreateOptionsMenu, and onOptionsItemSelected.
77     private boolean enableSaveFormData;
78     */
79
80     // cookieManager is used in onCreate and onOptionsItemSelected.
81     private CookieManager cookieManager;
82     // enableCookies is used in onCreate, onCreateOptionsMenu, and onOptionsItemSelected.
83     private boolean enableCookies;
84
85     // actionBar is used in onCreate and onOptionsItemSelected.
86     private ActionBar actionBar;
87
88     @Override
89     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
90     @SuppressLint("SetJavaScriptEnabled")
91     protected void onCreate(Bundle savedInstanceState) {
92         super.onCreate(savedInstanceState);
93         setContentView(R.layout.activity_webview);
94
95         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
96         final Activity mainWebViewActivity = this;
97
98         mainWebView = (WebView) findViewById(R.id.mainWebView);
99         actionBar = getSupportActionBar();
100
101         if (actionBar != null) {
102             // Remove the title from the action bar.
103             actionBar.setDisplayShowTitleEnabled(false);
104
105             // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
106             actionBar.setCustomView(R.layout.app_bar);
107             actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
108
109             // Set the "go" button on the keyboard to load the URL in urlTextBox.
110             EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
111             urlTextBox.setOnKeyListener(new View.OnKeyListener() {
112                 public boolean onKey(View v, int keyCode, KeyEvent event) {
113                     // If the event is a key-down event on the "enter" button, load the URL.
114                     if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
115                         // Load the URL into the mainWebView and consume the event.
116                         try {
117                             loadUrlFromTextBox();
118                         } catch (UnsupportedEncodingException e) {
119                             e.printStackTrace();
120                         }
121                         // If the enter key was pressed, consume the event.
122                         return true;
123                     } else {
124                         // If any other key was pressed, do not consume the event.
125                         return false;
126                     }
127                 }
128             });
129         }
130
131         mainWebView.setWebViewClient(new WebViewClient() {
132             // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
133             @Override
134             public boolean shouldOverrideUrlLoading(WebView view, String url) {
135                 mainWebView.loadUrl(url);
136                 return true;
137             }
138
139             /* These errors do not provide any useful information and clutter the screen.
140             public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
141                 Toast.makeText(mainWebViewActivity, "Error loading " + request + "   Error: " + error, Toast.LENGTH_SHORT).show();
142             }
143             */
144
145             // Update the URL in urlTextBox when the page starts to load.
146             @Override
147             public void onPageStarted(WebView view, String url, Bitmap favicon) {
148                 if (actionBar != null) {
149                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
150                     urlTextBox.setText(url);
151                 }
152             }
153
154             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
155             @Override
156             public void onPageFinished(WebView view, String url) {
157                 formattedUrlString = url;
158
159                 if (actionBar != null) {
160                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
161                     urlTextBox.setText(formattedUrlString);
162                 }
163             }
164         });
165
166         mainWebView.setWebChromeClient(new WebChromeClient() {
167             // Update the progress bar when a page is loading.
168             @Override
169             public void onProgressChanged(WebView view, int progress) {
170                 // Make sure that actionBar is not null.
171                 if (actionBar != null) {
172                     ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
173                     progressBar.setProgress(progress);
174                     if (progress < 100) {
175                         progressBar.setVisibility(View.VISIBLE);
176                     } else {
177                         progressBar.setVisibility(View.GONE);
178                     }
179                 }
180             }
181
182             // Set the favorite icon when it changes.
183             @Override
184             public void onReceivedIcon(WebView view, Bitmap icon) {
185                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
186                 favoriteIcon = icon;
187
188                 // Place the favorite icon in the actionBar if it is not null.
189                 if (actionBar != null) {
190                     ImageView imageViewFavoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
191                     imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
192                 }
193             }
194
195             // Enter full screen video
196             @Override
197             public void onShowCustomView(View view, CustomViewCallback callback) {
198                 if (getSupportActionBar() != null) {
199                     getSupportActionBar().hide();
200                 }
201
202                 fullScreenVideoFrameLayout.addView(view);
203                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
204
205                 mainWebView.setVisibility(View.GONE);
206
207                 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
208                 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
209                 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
210                 */
211
212                 // Set the one flag supported by API >= 14.
213                 if (Build.VERSION.SDK_INT >= 14) {
214                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
215                 }
216
217                 // Set the two flags that are supported by API >= 16.
218                 if (Build.VERSION.SDK_INT >= 16) {
219                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
220                 }
221
222                 // Set all three flags that are supported by API >= 19.
223                 if (Build.VERSION.SDK_INT >= 19) {
224                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
225                 }
226             }
227
228             // Exit full screen video
229             public void onHideCustomView() {
230                 if (getSupportActionBar() != null) {
231                     getSupportActionBar().show();
232                 }
233
234                 mainWebView.setVisibility(View.VISIBLE);
235
236                 fullScreenVideoFrameLayout.removeAllViews();
237                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
238             }
239         });
240
241         // Allow the downloading of files.
242         mainWebView.setDownloadListener(new DownloadListener() {
243             // Launch the Android download manager when a link leads to a download.
244             @Override
245             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
246                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
247                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
248
249                 // Add the URL as the description for the download.
250                 requestUri.setDescription(url);
251
252                 // Show the download notification after the download is completed if the API is 11 or greater.
253                 if (Build.VERSION.SDK_INT >= 11) {
254                     requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
255                 }
256
257                 downloadManager.enqueue(requestUri);
258                 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
259             }
260         });
261
262         // Allow pinch to zoom.
263         mainWebView.getSettings().setBuiltInZoomControls(true);
264
265         // Hide zoom controls if the API is 11 or greater.
266         if (Build.VERSION.SDK_INT >= 11) {
267             mainWebView.getSettings().setDisplayZoomControls(false);
268         }
269
270         // Set JavaScript initial status.
271         enableJavaScript = false;
272         mainWebView.getSettings().setJavaScriptEnabled(enableJavaScript);
273
274         // Set DOM Storage initial status.
275         enableDomStorage = false;
276         mainWebView.getSettings().setDomStorageEnabled(enableDomStorage);
277
278         /* Save Form Data does nothing until database storage is implemented.
279         // Set Save Form Data initial status.
280         enableSaveFormData = true;
281         mainWebView.getSettings().setSaveFormData(enableSaveFormData);
282         */
283
284         // Set Cookies initial status.
285         enableCookies = false;
286         cookieManager = CookieManager.getInstance();
287         cookieManager.setAcceptCookie(enableCookies);
288
289         // Get the intent information that started the app.
290         final Intent intent = getIntent();
291
292         if (intent.getData() != null) {
293             // Get the intent data and convert it to a string.
294             final Uri intentUriData = intent.getData();
295             formattedUrlString = intentUriData.toString();
296         }
297
298         // If formattedUrlString is null assign the homepage to it.
299         if (formattedUrlString == null) {
300             formattedUrlString = homepage;
301         }
302
303         // Load the initial website.
304         mainWebView.loadUrl(formattedUrlString);
305     }
306
307     @Override
308     protected void onNewIntent(Intent intent) {
309         // Sets the new intent as the activity intent, so that any future getIntent() picks up this one.
310         setIntent(intent);
311
312         if (intent.getData() != null) {
313             // Get the intent data and convert it to a string.
314             final Uri intentUriData = intent.getData();
315             formattedUrlString = intentUriData.toString();
316         }
317
318         // Load the website.
319         mainWebView.loadUrl(formattedUrlString);
320     }
321
322     @Override
323     public boolean onCreateOptionsMenu(Menu menu) {
324         // Inflate the menu; this adds items to the action bar if it is present.
325         getMenuInflater().inflate(R.menu.menu_webview, menu);
326
327         // Get MenuItems for checkable menu items.
328         MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
329         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
330         /* toggleSaveFormData does nothing until database storage is implemented.
331         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
332         */
333         MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
334
335         // Set the initial status of the menu item checkboxes.
336         toggleJavaScript.setChecked(enableJavaScript);
337         toggleDomStorage.setChecked(enableDomStorage);
338         /* toggleSaveFormData does nothing until database storage is implemented.
339         toggleSaveFormData.setChecked(enableSaveFormData);
340         */
341         toggleCookies.setChecked(enableCookies);
342
343         return true;
344     }
345
346     @Override
347     public boolean onPrepareOptionsMenu(Menu menu) {
348         // Enable Clear Cookies if there are any.
349         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
350         clearCookies.setEnabled(cookieManager.hasCookies());
351
352         // Enable Back if canGoBack().
353         MenuItem back = menu.findItem(R.id.back);
354         back.setEnabled(mainWebView.canGoBack());
355
356         // Enable forward if canGoForward().
357         MenuItem forward = menu.findItem(R.id.forward);
358         forward.setEnabled(mainWebView.canGoForward());
359
360         // Run all the other default commands.
361         super.onPrepareOptionsMenu(menu);
362
363         // return true displays the menu.
364         return true;
365     }
366
367     @Override
368     // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
369     @TargetApi(11)
370     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
371     @SuppressLint("SetJavaScriptEnabled")
372     // removeAllCookies is deprecated, but it is required for API < 21.
373     @SuppressWarnings("deprecation")
374     public boolean onOptionsItemSelected(MenuItem menuItem) {
375         int menuItemId = menuItem.getItemId();
376         ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
377
378         // Sets the commands that relate to the menu entries.
379         switch (menuItemId) {
380             case R.id.toggleJavaScript:
381                 if (enableJavaScript) {
382                     enableJavaScript = false;
383                     menuItem.setChecked(false);
384                     mainWebView.getSettings().setJavaScriptEnabled(false);
385                     mainWebView.reload();
386                 } else {
387                     enableJavaScript = true;
388                     menuItem.setChecked(true);
389                     mainWebView.getSettings().setJavaScriptEnabled(true);
390                     mainWebView.reload();
391                 }
392                 return true;
393
394             case R.id.toggleDomStorage:
395                 if (enableDomStorage) {
396                     enableDomStorage = false;
397                     menuItem.setChecked(false);
398                     mainWebView.getSettings().setDomStorageEnabled(false);
399                     mainWebView.reload();
400                 } else {
401                     enableDomStorage = true;
402                     menuItem.setChecked(true);
403                     mainWebView.getSettings().setDomStorageEnabled(true);
404                     mainWebView.reload();
405                 }
406                 return true;
407
408             /* toggleSaveFormData does nothing until database storage is implemented.
409             case R.id.toggleSaveFormData:
410                 if (enableSaveFormData) {
411                     enableSaveFormData = false;
412                     menuItem.setChecked(false);
413                     mainWebView.getSettings().setSaveFormData(false);
414                     mainWebView.reload();
415                 } else {
416                     enableSaveFormData = true;
417                     menuItem.setChecked(true);
418                     mainWebView.getSettings().setSaveFormData(true);
419                     mainWebView.reload();
420                 }
421                 return true;
422             */
423
424             case R.id.toggleCookies:
425                 if (enableCookies) {
426                     enableCookies = false;
427                     menuItem.setChecked(false);
428                     cookieManager.setAcceptCookie(false);
429                     mainWebView.reload();
430                 } else {
431                     enableCookies = true;
432                     menuItem.setChecked(true);
433                     cookieManager.setAcceptCookie(true);
434                     mainWebView.reload();
435                 }
436                 return true;
437
438             case R.id.clearDomStorage:
439                 WebStorage webStorage = WebStorage.getInstance();
440                 webStorage.deleteAllData();
441                 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
442                 return true;
443
444             case R.id.clearCookies:
445                 if (Build.VERSION.SDK_INT < 21) {
446                     cookieManager.removeAllCookie();
447                 } else {
448                     cookieManager.removeAllCookies(null);
449                 }
450                 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
451                 return true;
452
453             case R.id.home:
454                 mainWebView.loadUrl(homepage);
455                 return true;
456
457             case R.id.refresh:
458                 mainWebView.reload();
459                 return true;
460
461             case R.id.back:
462                 mainWebView.goBack();
463                 return true;
464
465             case R.id.forward:
466                 mainWebView.goForward();
467                 return true;
468
469             case R.id.copyURL:
470                 // Make sure that actionBar is not null.
471                 if (actionBar != null) {
472                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
473                     clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
474                 }
475                 return true;
476
477             case R.id.pasteURL:
478                 // Make sure that actionBar is not null.
479                 if (actionBar != null) {
480                     ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
481                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
482                     urlTextBox.setText(clipboardData.coerceToText(this));
483                     try {
484                         loadUrlFromTextBox();
485                     } catch (UnsupportedEncodingException e) {
486                         e.printStackTrace();
487                     }
488                 }
489                 return true;
490
491             case R.id.shareURL:
492                 // Make sure that actionBar is not null.
493                 if (actionBar != null) {
494                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
495                     Intent shareIntent = new Intent();
496                     shareIntent.setAction(Intent.ACTION_SEND);
497                     shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
498                     shareIntent.setType("text/plain");
499                     startActivity(Intent.createChooser(shareIntent, "Share URL"));
500                 }
501                 return true;
502
503             case R.id.addToHomescreen:
504                 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
505                 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
506                 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
507
508                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
509                 return true;
510
511             case R.id.downloads:
512                 // Launch the system Download Manager.
513                 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
514
515                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
516                 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
517
518                 startActivity(downloadManangerIntent);
519                 return true;
520
521             case R.id.about:
522                 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
523                 AppCompatDialogFragment aboutDialog = new AboutDialog();
524                 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
525                 return true;
526
527             case R.id.exit:
528                 // Clear DOM storage.
529                 WebStorage domStorage = WebStorage.getInstance();
530                 domStorage.deleteAllData();
531
532                 // Clear cookies.
533                 if (Build.VERSION.SDK_INT < 21) {
534                     cookieManager.removeAllCookie();
535                 } else {
536                     cookieManager.removeAllCookies(null);
537                 }
538
539                 // Destroy the internal state of the webview.
540                 mainWebView.destroy();
541
542                 // Close Privacy Browser.
543                 finish();
544                 return true;
545
546             default:
547                 return super.onOptionsItemSelected(menuItem);
548         }
549     }
550
551     @Override
552     public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
553         // Do nothing because the user selected "Cancel".
554     }
555
556     @Override
557     public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
558         // Get shortcutNameEditText from the alert dialog.
559         EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
560
561         // Create the bookmark shortcut based on formattedUrlString.
562         Intent bookmarkShortcut = new Intent();
563         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
564         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
565
566         // Place the bookmark shortcut on the home screen.
567         Intent placeBookmarkShortcut = new Intent();
568         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
569         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
570         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
571         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
572         sendBroadcast(placeBookmarkShortcut);
573     }
574
575     // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
576     @Override
577     public void onBackPressed() {
578         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
579
580         if (mainWebView.canGoBack()) {
581             mainWebView.goBack();
582         } else {
583             super.onBackPressed();
584         }
585     }
586
587     public void loadUrlFromTextBox() throws UnsupportedEncodingException {
588         // Make sure that actionBar is not null.
589         ActionBar actionBar = getSupportActionBar();
590         if (actionBar != null) {
591             final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
592             EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
593
594             // Get the text from urlTextInput and convert it to a string.
595             String unformattedUrlString = urlTextBox.getText().toString();
596             URL unformattedUrl = null;
597             Uri.Builder formattedUri = new Uri.Builder();
598
599             // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
600             if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
601
602                 // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
603                 if (!unformattedUrlString.startsWith("http")) {
604                     unformattedUrlString = "http://" + unformattedUrlString;
605                 }
606
607                 // Convert unformattedUrlString to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
608                 try {
609                     unformattedUrl = new URL(unformattedUrlString);
610                 } catch (MalformedURLException e) {
611                     e.printStackTrace();
612                 }
613
614                 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
615                 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
616                 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
617                 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
618                 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
619                 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
620
621                 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
622                 formattedUrlString = formattedUri.build().toString();
623
624             } else {
625                 // Sanitize the search input and convert it to a DuckDuckGo search.
626                 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
627                 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
628             }
629
630             mainWebView.loadUrl(formattedUrlString);
631
632             // Hides the keyboard so we can see the webpage.
633             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
634             inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
635         }
636     }
637 }