How to save URLs to view later on - java

I have an application with a WebView.
But I want to make it save URLs, for example: when the application starts, it opens google.com. So if I want to type something in and save that search or website, I want it to have a button: "Save site" and "Load site". How do I do this as simple as possible?
I am using this code so far:
package com.mysoftwaremobileapps.Finnnofortablets;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class finnnoActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button TilbakeButton;
WebView FinnWeb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FinnWeb = (WebView)findViewById(R.id.FinnWeb);
FinnWeb.setWebViewClient(new MyWebViewClient());
FinnWeb.getSettings().setBuiltInZoomControls(true);
FinnWeb.getSettings().setJavaScriptEnabled(true);
FinnWeb.loadUrl("http://m.finn.no");
FinnWeb.requestFocus(View.FOCUS_DOWN);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
setContentView(R.layout.main);
FinnWeb = (WebView) findViewById(R.id.FinnWeb);
FinnWeb.setWebViewClient(new MyWebViewClient());
FinnWeb.getSettings().setJavaScriptEnabled(true);
FinnWeb.getSettings().setBuiltInZoomControls(true);
FinnWeb.requestFocus(View.FOCUS_DOWN);
FinnWeb.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.LoggInn:
setContentView(R.layout.main);
FinnWeb = (WebView) findViewById(R.id.FinnWeb);
FinnWeb.setWebViewClient(new MyWebViewClient());
FinnWeb.getSettings().setJavaScriptEnabled(true);
FinnWeb.loadUrl("http://m.finn.no/#loginForm.html");
FinnWeb.requestFocus(View.FOCUS_DOWN);
break;
case R.id.OmUtvikler:
setContentView(R.layout.omutvikler);
TilbakeButton = (Button)findViewById(R.id.TilbakeButton);
TilbakeButton.setOnClickListener(this);
break;
case R.id.RegistrerDeg:
setContentView(R.layout.main);
FinnWeb = (WebView) findViewById(R.id.FinnWeb);
FinnWeb.setWebViewClient(new MyWebViewClient());
FinnWeb.getSettings().setJavaScriptEnabled(true);
FinnWeb.loadUrl("http://m.finn.no/#auth/registrer.html");
FinnWeb.requestFocus(View.FOCUS_DOWN);
break;
case R.id.Tilbake:
if (FinnWeb.canGoBack()) {
FinnWeb.goBack();
}
else{
}
break;
case R.id.Frem:
if (FinnWeb.canGoForward()) {
FinnWeb.goForward();
}
else{
}
break;
case R.id.ExitWithSaving:
System.exit(0);
break;
case R.id.Exit:
System.exit(0);
break;
case R.id.LastAnnonse:
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.TilbakeButton:
setContentView(R.layout.main);
FinnWeb = (WebView) findViewById(R.id.FinnWeb);
FinnWeb.setWebViewClient(new MyWebViewClient());
FinnWeb.getSettings().setJavaScriptEnabled(true);
FinnWeb.getSettings().setBuiltInZoomControls(true);
FinnWeb.requestFocus(View.FOCUS_DOWN);
break;
}
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}

There are a couple of different ways to do this. The first is to remember the URL via a hook in your already overridden "shouldOverrideUrlLoading".
Like:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{ view.loadUrl(url);
//save off url in instance variable
this.currentURL = url.toString();
return true;
}
Secondly is to call out to your webView to get the current URL when the user clicks on your mentioned "Save Site" button via the method:
http://developer.android.com/reference/android/webkit/WebView.html#getUrl()
Either of these methods will allow you to access what URL is currently being displayed. I hope this helps.

Related

progress bar in webview keeps loading even after web page finished loading

Here is my code
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends ActionBarActivity {
private WebView view;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
String url = "http://www.carsaleindiaofficial.com/?m=1";
view = (WebView) this.findViewById(R.id.webView);
view.setWebViewClient(new WebViewClient());
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.loadUrl(url);
}
public class MyAppWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.findViewById(R.id.progressBar).setVisibility(View.GONE);
//if (progressBar.getVisibility() == View.VISIBLE)
//progressBar.setVisibility(View.INVISIBLE);
//progressBar.setVisibility(View.INVISIBLE);
//progressBar.setVisibility(View.GONE);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().endsWith("carsaleindiaofficial.com/?m=1")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
#Override
public void onBackPressed() {
if (view.canGoBack()) {
view.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings)
view.loadUrl(view.getUrl());
return super.onOptionsItemSelected(item);
}
}
The progress bar and webview works fine but when the page is finished loading the progress bar still remains? When I have loaded the page the progress bar visibility doesn't dissapear/change to GONE? Where is the error?
Ive tried both progressBar.setVisibility(View.INVISIBLE) and progressBar.setVisibility(View.GONE); but nothin seems to work.
Instead of using customizing webclient. you use default webclient. your problem is replace this.
view.setWebViewClient(new WebViewClient());
add this
view.setWebViewClient(new MyAppWebViewClient());
and also
progressBar.setVisibility(View.INVISIBLE);
not
view.findViewById(R.id.progressBar1).setVisibility(View.GONE);
full code
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends ActionBarActivity {
private WebView view;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maine);
progressBar = (ProgressBar) this.findViewById(R.id.progressBar1);
String url = "http://www.carsaleindiaofficial.com/?m=1";
view = (WebView) this.findViewById(R.id.webView1);
view.setWebViewClient(new MyAppWebViewClient());
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
//view.loadUrl(url);
view.loadUrl("http://m.facebook.com/");
// view.loadUrl("file:///android_asset/web.html");
}
public class MyAppWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.findViewById(R.id.progressBar1).setVisibility(View.GONE);
Log.i("pageFinished", "yesss");
progressBar.setVisibility(View.INVISIBLE);
//progressBar.setVisibility(View.GONE);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if (view.canGoBack()) {
view.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.maine, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings)
view.loadUrl(view.getUrl());
return super.onOptionsItemSelected(item);
}
}
just changed WebViewClient to MyWebViewClient, progressBar to progressBar1 & ActionBarActivity to AppCompatActivity and every code seems to work :) thank again every1.. :) #Devendra & #akhil :)
my final code
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends AppCompatActivity {
private WebView view;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) this.findViewById(R.id.progressBar1);
String url = "http://www.carsaleindiaofficial.com/?m=1";
view = (WebView) this.findViewById(R.id.webView);
view.setWebViewClient(new MyWebViewClient());
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.loadUrl(url);
}
public class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.i("pageFinished", "yesss");
progressBar.setVisibility(View.GONE);
Log.i("progressBar", "Gone");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
Log.i("progressBar", "Visible");
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.i("ShldOvrideUrl", "working");
return true;
}
}
#Override
public void onBackPressed() {
if (view.canGoBack()) {
view.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings)
view.loadUrl(view.getUrl());
return super.onOptionsItemSelected(item);
}
}
After intent of webview url you have to write progressbar.visibility="View.GONE"
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
FGallery.this.progressBar.setProgress(100);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
FGallery.this.progressBar.setProgress(0);
super.onPageStarted(view, url, favicon);
}
}
This is working for me. you can set it as WebViewClient.

Webview does not reload

I am using fragments and have added a item on the action bar to refresh webview named airport_menuRefresh but when ever i click it nothing happens. I have 3 tabs. I have tried different methods but neither of them works.
Here is the code of my 1tab(tab1 only contains the not working logic to refresh).
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class GamesFragment extends Fragment {
private ProgressBar progress;
private WebView myWebView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String url = "http://google.com";
int delay = 6 * 1000;
View rootView = inflater.inflate(R.layout.fragment_games, container, false);
myWebView = (WebView)rootView.findViewById(R.id.webViewGames);
myWebView.setWebChromeClient(new myWebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
progress = (ProgressBar)rootView.findViewById(R.id.progressBar);
progress.setMax(100);
Handler handler = new Handler();
MyRunnable runnable = new MyRunnable(url, myWebView);
handler.postDelayed(runnable, delay);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView View, String url) {
GamesFragment.this.progress.setProgress(0);
View.loadUrl(url);
return true;
}
});
myWebView.setOnKeyListener(new android.view.View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return rootView;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.airport_menuRefresh:
GamesFragment.this.myWebView.loadUrl("http://google.com");
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyRunnable implements Runnable {
String url;
private WebView mywebview;
public MyRunnable(String url, WebView wv) {
this.url = url;
this.mywebview = wv;
}
public void run() {
mywebview.loadUrl(url);
}
}
private class myWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
GamesFragment.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
}
Here is my main Activity:
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.tech.example.adaptor.SlidingTabLayout;
import com.tech.example.adaptor.TabsPagerAdapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends ActionBarActivity {
SlidingTabLayout tabs;
ViewPager viewPager;
TabsPagerAdapter adapter;
Toolbar toolbar;
private Menu optionsMenu;
CharSequence Titles[]={ "tab1", "tab2", "tab3" };
int Numboftabs =3;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
adapter = new TabsPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
// Assigning ViewPager View and setting the adapter
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
setRefreshActionButtonState(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
#Override
public int getDividerColor(int i) {
return 0;
}
});
tabs.setViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.optionsMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public void setRefreshActionButtonState(final boolean refreshing) {
if (optionsMenu != null) {
final MenuItem refreshItem = optionsMenu
.findItem(R.id.airport_menuRefresh);
if (refreshItem != null) {
if (refreshing) {
refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
} else {
refreshItem.setActionView(null);
}
}
}
}
}
EDIT
I edited my main activity like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.airport_menuRefresh:
GamesFragment.myWebView1.loadUrl("http://example.com");
MoviesFragment.myWebView.loadUrl("http://example2.com");
TopRatedFragment.myWebView2.loadUrl("http://example3.com");
return true;
}
return super.onOptionsItemSelected(item);
}
Now its reloading but suppose i click reload on tab1 all 3 tabs reloads! Any solution?
I guess error is in the name of the WebView of your methods. As long as you imported:
import android.view.View;
When in this methow
public boolean shouldOverrideUrlLoading(WebView View, String url) {
// ^-----> UPPERCASE
you make this call:
View.loadUrl(url);
you're trying to call static method of View and not the instance of View from method signature.
try this:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// ^---> lowercase
GamesFragment.this.progress.setProgress(0);
view.loadUrl(url);
// ^---> lowercase
return true;
}
Finally i found a solution.
Moved onCreateOptionsMenu and onOptionsItemSelected from main activity to fragment tabs like this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
.............
.............
.............
setHasOptionsMenu(true);
.................
.................
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.airport_menuRefresh:
TopRatedFragment.this.myWebView2.loadUrl("http://myexample.com");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And this worked like a charm.

How to use go back in sites correct?

I have my WebViewFragment and of course i want to go back in the site im browsing but i have the error:
The method onBackPressed() is undefined for the type Fragment
Why? I don´t understand that?
What am i doing wrong?
Here´s my full webview code i´m using.
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment extends Fragment {
WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.menus);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
return v;
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}}
If i´m using:
public void onBackPressed() {
Fragment webview = getFragmentManager().findFragmentByTag("webview");
if (webview instanceof WebViewFragment) {
boolean goback = ((WebViewFragment)webview).canGoBack();
if (!goback)
super.onBackPressed();
}
}}
I have the errors:
The method canGoBack() is undefined for the type WebViewFragment
The method onBackPressed() is undefined for the type Fragment
Thank you dudes for your help!
Found the solution what is working for me in my fragment.
webView.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return v;

Android Application Web View Back Button

I have a web application that works well but I cannot get the back button to function in the web view. Please see code:
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
public class extends Activity
{
final Activity activity = this;
WebView WebView;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.example.com");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (WebView != null && (keyCode == KeyEvent.KEYCODE_BACK) && WebView.canGoBack()) {
WebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
The application runs but when the back button is pressed it still exits the application. I am also wanting to add the ability to use a html mailto tag with the application. Any help would be appreciated. Thank you.
Edit:
Include a null check to see if WebView is null before invoking methods on it.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (WebView != null && (keyCode == KeyEvent.KEYCODE_BACK) && WebView.canGoBack()) {
WebView.goBack();
return true;
}
Your code seems correct to me. What is the exact behavior you are hoping to achieve from the back button?
What currently happens when you run the application and press the back button?
Edit, Oh I see what is happening.
You are trying to override onKeyDown() inside your onCreate(). onKeyDown() and onCreate() are both methods of Activity, thus you cannot declare one inside the other.
Try your code like this:
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
public class DealJargon extends Activity {
final Activity activity = this;
WebView WebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.loadUrl("http://www.example.com");
}
WebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress){
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
WebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && WebView.canGoBack()) {
WebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Edit 2: Anytime you get some kind of compile error that has something to do with a brace it is likely that you are trying to declare a method inside the declaration of another method. Or something similar.

Using reflection in Android for backwards compatibility

I was reading over at the Android development website about using reflections. But I'm really not grasping how to use it. I need this Java file to run on a 1.5 (SDK3) device but just ignore the new code and it works fine on a 2.0 (SDK5) or later phone. I have this Activity (posted below) and it's a simple webview. However, I want to have geolocation enabled (even if it is only for 2.0 and later phones), since these APIs weren't introduced until SDK 5, and I would like the webview to be able to, at the very least, to load on a 1.5 phone rather than just crashing. How do I take my code and set it up using reflections?
package com.my.app;
import com.facebook.android.R;
//NEEDS TO BE IGNORED**********************************************************
import android.webkit.GeolocationPermissions;
import android.webkit.GeolocationPermissions.Callback;
//END**************************************************************************
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
//GeolocationPermissionsCallback NEEDS TO BE IGNORED**********************************************************
public class Places extends Activity implements GeolocationPermissions.Callback {
private ProgressDialog progressBar;
public WebView webview;
private static final String TAG = "Main";
String geoWebsiteURL = "http://google.com";
#Override
public void onStart()
{
super.onStart();
CookieSyncManager.getInstance().sync();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new testClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.loadUrl("http://google.com");
progressBar = ProgressDialog.show(Places.this, "", "Loading Page...");
//START GROUP OF CODE THAT NEEDS TO BE IGNORED************************************************************
webview.getSettings().setGeolocationEnabled(true);
GeoClient geo = new GeoClient();
webview.setWebChromeClient(geo);
}
public void invoke(String origin, boolean allow, boolean remember) {
}
final class GeoClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
//END OF CODE THAT NEEDS TO BE IGNORED************************************************
}
private class testClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
if (url.startsWith("mailto:") || url.startsWith("geo:") ||
url.startsWith("tel:")) {
Intent intent = new Intent
(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
}
}
//What's here????
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
Intent z = new Intent(this, Search.class);
startActivity(z);
}
return super.onKeyDown(keyCode, event);
}
public boolean onCreateOptionsMenu (Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent m = new Intent(this, Home.class);
startActivity(m);
return true;
case R.id.refresh:
webview.reload();
Toast.makeText(this, "Refreshing...", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void onStop()
{
super.onStop();
CookieSyncManager.getInstance().sync();
}
}
Step #1: Do not implement GeolocationPermissions.Callback on the activity. Use some other object for GeolocationPermissions.Callback, one implemented in a public Java class that you would not load if you are running on older versions of the OS.
Step #2: Read the answers and comments on the question you asked previously, which covers what you need to know for the rest. Notably, you would make GeoClient be a public Java class in its own file, so you can avoid loading it on older versions of the OS. Personally, I like the Stephen C answer, and I demonstrate its use here.

Categories