android finish activity contain a webview when press back button - android

I have an android application in which I have a button.User presses that button then it start an activity that contain a webview.
The problem is in order to finish webview activity when user press back button in the first time,I tried to finish that activity But not working, It went back to history page.I pressed back button several time,webview activity finish.
How can my app finish webview activity when user press button in the first time?
Here my webview activity
public class SocialWebViewActivity extends Activity {
private WebView webView;
ProgressDialog mProgress;
public static String url="";
#SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.social_web_view);
webView = (WebView) findViewById(R.id.social_web_view_external);
webView.getSettings().setJavaScriptEnabled(true);
// the init state of progress dialog
mProgress = ProgressDialog.show(this, "Web", "Loading...");
// add a WebViewClient for WebView, which actually handles loading data from web
webView.setWebViewClient(new WebViewClient() {
// load url
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
// when finish loading page
public void onPageFinished(WebView view, String url) {
if(mProgress.isShowing()) {
mProgress.dismiss();
}
view.clearHistory();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(getApplicationContext(), description, Toast.LENGTH_LONG).show();
if(mProgress.isShowing()) {
mProgress.dismiss();
}
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
if(!"".equals(SocialWebViewActivity.url)){
webView.loadUrl(SocialWebViewActivity.url);
}
}
}

Override the onKeyDown(param)
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) ) {
webView.clearHistory(); // clear history
finish(); // finish activity
return true;
}
return super.onKeyDown(keyCode, event);
}

Related

Android webview custom error page

I am creating application that use WebView to access a online website. I am stuck where I have to add code to check availability of page.
public class SpartanWeb extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Adds Progrss bar Support
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
// Makes Progress bar Visible
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
// Get Web view
mWebView = (WebView) findViewById(R.id.webView1);
WebSettings websettings = mWebView.getSettings();
websettings.setJavaScriptEnabled(true);
mWebView.stopLoading();
mWebView.clearCache(true);
mWebView.loadUrl("http://google.com");
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.setWebViewClient(new WebViewClient());
mWebView.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);
}
});
// onProgressChanged
final Activity MyActivity = this;
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// bar disappear after URL is loaded, and changes string to
// Loading...
MyActivity.setTitle("Loading...");
MyActivity.setProgress(progress * 100); // Make the bar
// disappear after URL
// is loaded
// Return the app name after finish loading
if (progress == 100)
MyActivity.setTitle(R.string.app_name);
}
});
}// EOM oc
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I am trying to add onReceivedError but for some reason custom page is not loading.
/** Called when the activity is first created. */
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
mWebView.loadUrl("file:///android_asset/error.html");
}
Please advise what to do.
You can call loadErrorPage(view) function in the onReceivedError function.
The following code will load the error content you need to show.Here i am load the html file with loadDataWithBaseURL.
public void loadErrorPage(WebView webview){
if(webview!=null){
String htmlData ="<html><body><div align=\"center\" >"This is the description for the load fail : "+description+"\nThe failed url is : "+failingUrl+"\n"</div></body>";
webview.loadUrl("about:blank");
webview.loadDataWithBaseURL(null,htmlData, "text/html", "UTF-8",null);
webview.invalidate();
}
}
I added onReceivedError to mWebView.setWebViewClient(new WebViewClient so now it's working. Thanks for tips.
mWebView.setWebViewClient(new WebViewClient() {
#Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/error.html");
} });
You can use the following code ..
public class TestResultWebclient extends WebViewClient {
ProgressDialog progressDialog;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(TermsAndCondsMrupeeActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
if (progressDialog != null)
try {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
super.onPageFinished(view, url);
}
}

stop page to redirect when user press back key in webview android

public void onBackPressed (){
WebView webview = (WebView) findViewById(R.id.mainWebView);
if (webview.isFocused() && webview.canGoBack()) {
webview.goBack();
}
else {
super.onBackPressed();
finish();
}
}
private class MyCustomWebViewClient extends WebViewClient {
ProgressDialog progressDialog = new ProgressDialog(AndroidMobileAppSampleActivity.this);
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressDialog.setMessage("Processing");
progressDialog.setCancelable(false);
progressDialog.setOnKeyListener(new OnKeyListener(){
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_SEARCH) {
return true;
}
else
return false;
}});
progressDialog.show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progressDialog.setMessage("Processing");
progressDialog.setCancelable(false);
progressDialog.setOnKeyListener(new OnKeyListener(){
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_SEARCH) {
return true;
}
else
return false;
}});
progressDialog.show();
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
This is my code, i am loading a url in webview and showing a processing dialog when user redirect to another page, Now i want to stop my page to redirect and also hide processing dialog when user press the back key. I tried but not successful, Please help. Thanks in advance
Clear history on finished page load.
No back history.
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.clearHistory();
super.onPageFinished(view, url);
}
});

Webview cannot go back with local html

I have a webview that load up a URL from internet, but when there is no connectivity (onReceiedError) it loads up a locally saved html document in assets folder.
but when I press back button on that particular activity (which loads up the local HTML) it doesn't go back to the previous activity instead tries to refresh the page.. It is only after 4-5 Back presses it goes back.
here is my code.
private class HelloWebViewClient extends WebViewClient{
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
mWebView.loadUrl("file:///android_asset/offline.html");
}
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event)
{
if ((KeyCode)== KeyEvent.KEYCODE_BACK && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(KeyCode, event);
}
#Override
public void onBackPressed()
{
this.finish();
overridePendingTransition (0, R.anim.right_slide_out);
return;
}
}
Works fine with the normal webpage to load from Internet.
coz in onReceivedError you change the url . so there will be no goback event
you have to just show toast message and delete mWebView.loadUrl("file:///android_asset/offline.html");

Android WebView is blank after network disconnect

I have a following scenario for webview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view_tutorial);
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.setWebViewClient(mWebViewClient);
mWebView.setInitialScale(0);
mWebView.setVerticalScrollBarEnabled(false);
mWebView.requestFocusFromTouch();
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
Button btnGo = (Button) findViewById(R.id.button1);
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.google.com";// here goes my server url with https://...... for authentication
showProgressDialog("Loading");
mWebView.loadUrl(url);
}
});
}
private void showProgressDialog(String title) {
if(mProgress == null || !mProgress.isShowing()){
mProgress = ProgressDialog.show(this, title, "Please wait...", true,
true, new OnCancelListener() {
public void onCancel(DialogInterface pd) {
finishActivity();
}
});
mProgress.setCanceledOnTouchOutside(false);
mProgress.setCancelable(true);
}
}
private void finishActivity() {
if(mWebView!=null){
finish();
}
}
private final WebViewClient mWebViewClient = new WebViewClient() {
public void onPageStarted(WebView view, String url,
android.graphics.Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d("test", "page started");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("test", "page should override called");
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (mIsLoadingSigninPage) {
mIsLoadingSigninPage = false;
dismissProgressDialog();
}
Log.d("test", "page finished");
super.onPageFinished(view, url);
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
mIsLoadingSigninPage = false;
dismissProgressDialog();
Log.d("test", "page error received");
super.onReceivedError(view, errorCode, description, failingUrl);
finishActivity();
}
};
private void dismissProgressDialog() {
if (mProgress != null && mProgress.isShowing()) {
mProgress.dismiss();
mProgress =null;
}
}
// this is log cat for point 3 below
03-07 07:31:20.977: D/test(1431): page started
03-07 07:31:22.788: D/test(1431): page should override called
03-07 07:31:22.887: D/test(1431): page started
03-07 07:31:24.496: D/test(1431): page finished
Ok,
When network is not available I ran this code, webviewclient's onReceivedError get called,
If network available and page loading started, and network disconnect, then also onReceivedError get called.
But there is a some instance of time,(count 1,2,3 after pressing button and disconnect network with f8 on emulator) mWebView.loadUrl(url) gets called, webViewclient's methods gets called like below
and WebView displays blank white screen, onReceivedError not called.
here is logcat
and
What is wrong with this code.
Why onReceivedError not called. If it does not get called, how to handle this situation
How to know webView has not loaded anyting and finish activity
it will certainly call page started and page finished because onReceivedError will be called on:-
-click of any link (if internet not present) then should override url will throw an error which it will handle
-on activity started or when webview is called
for all the exceptions which are not handled by onRecievedError you have to check http status

Webview showing "null" as content

I'm trying to load the url for a google calendar public calendar in a webview. Initially it worked without issue. At somepoint all I get is the text "null" in the webview. I've tried changing the url as well to just a basic webpage with the same result. I've also tried commenting out the wbv.loadurl line and get the same result. I've tried stepping through the code and the line is called when not commented out. Any help would be appreciated. Below is the code to populate the webview:
wbv = (WebView) findViewById(R.id.audioPlayer_showSchedule);
WebSettings settings = wbv.getSettings();
wbv.setWebViewClient(new TwitWebViewClient());
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
settings.setJavaScriptEnabled(true);
settings.setDefaultTextEncodingName("utf-8");
wbv.loadUrl("http://www.google.com/calendar/embed?src=r8psn8mpajnfa2703k43l6o014#group.calendar.google.com&ctz=America/Los_Angeles&program&mode=Week&gsessionid=vzeVWSq2Wdk3eVmGOUp1bQ");
Use below working code ::
public class Android_Activity extends Activity {
private Android_Activity _activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
_activity = this;
setContentView(R.layout.main);
mwebview=(WebView)view.findViewById(R.id.webview);
mwebview.getSettings().setJavaScriptEnabled(true);
mwebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
if(checkInternetConnection(_activity)==true){
if(savedInstanceState==null)
mwebview.loadUrl("http://abc.com");
else
mwebview.restoreState(savedInstanceState);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(_activity);
builder.setMessage("Please check your network connection.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
mwebview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(mwebview.getVisibility()==View.VISIBLE)
{
_activity.setProgress(progress * 100);
}
}
});
mwebview.setWebViewClient(new HelloWebViewClient());
}
//HelloWebViewClient class for webview
private class HelloWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
view.loadUrl(url);
return true;
}
} //HelloWebViewClient-class
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && mwebview.canGoBack() ){
mwebview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//To check whether network connection is available on device or not
public static boolean checkInternetConnection(Activity _activity) {
ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
return true;
else
return false;
}//checkInternetConnection()
}
And also in your main.xml layout you must have a webview with id webview
It all looks good to me. Are you sure your TwitWebViewClient is doing what you expect it to?
Also, are you sure that's the URL you want to be loading? I can't help but notice the "gsessionid=vzeVWSq2Wdk3eVmGOUp1bQ" at the end of it. Surely that won't work as soon as your session expired?

Categories

Resources