can webview start an activity onReceivedError? - android

I am trying to start an activity (Errorpage) when webview failed to load content.But there is no error during the build, but the app closes, while inernet is off. It was supposed to launh the Errorpage activity.
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import androidx.appcompat.app.AppCompatActivity;
public class smwebview extends AppCompatActivity {
private WebView webview;
private ProgressBar spinner;
String ShowOrHideWebViewInitialUse = "show";
private WebView mWebView; //added for back buton override
public boolean mShouldPause = false;
String fullurl;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smwebview);
getIntent();
fullurl= getIntent().getStringExtra("full_url");
webview = (WebView) findViewById(R.id.webView_Latest);
webview.setWebViewClient(new CustomWebViewClient());
spinner = (ProgressBar)findViewById(R.id.progressBar2);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// keep screen on
webview.loadUrl(fullurl);
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public void onLoadResource(WebView webview, String url) {
super.onLoadResource(webview, url);
if (url.contains("youtube.com")) mShouldPause = true;
}
public void onReceivedError(WebView webview, int errorCode, String description, String failingUrl) {
Intent intent7 = new Intent(smwebview.this,Errorpage.class);
startActivity(intent7);
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
public class WebViewClient extends android.webkit.WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
#Override
public void onResume()
{
super.onResume();
webview.onResume();
}
#Override
public void onPause() {
super.onPause();
if(mShouldPause){
webview.onPause();
}
mShouldPause = false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
If anybody have any idea Please help me. Also please comment your suggestions on the code/logic. (I am very new to android programming)

Internet if off. Its different scenario you must add check internet connection before load.
Or onRwleceiveError is different case. When you load wrong url or utl you entered is not working

Related

I want to show a progress text while loading the website

This is my second activity
can anyone help me to add a progress text while loading the website, after the loading it should stop, help me to place the code in right place ,because i don't know much about java, i am just studying
package com.example.jaisonjoseph.newsclient;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.support.design.widget.NavigationView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Manorama extends Activity {
Toolbar toolbar=null;
public WebView mwebView;
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manorama);
if(isNetworkStatusAvialable (getApplicationContext())) {
WebView view=(WebView) findViewById(R.id.webView2);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new WebViewClient());
view.loadUrl("http://manoramaonline.com");
} else {
WebView view1=(WebView) findViewById(R.id.webView2);
view1.getSettings().setJavaScriptEnabled(true);
view1.setWebViewClient(new WebViewClient());
view1.loadUrl("file:///android_asset/index.html");
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction()==KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
WebView webView = (WebView) findViewById(R.id.webView2);
if (webView != null) {
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
private class MyWebViewClient extends WebViewClient {
ProgressBar bar=(ProgressBar)findViewById(R.id.progressBar);
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
super.onPageFinished(view, url);
}
}
}
You should set WebViewClient for listening page loading started and finished. You can make that like:
Custom WebViewClient:
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
webView.setVisibility(View.GONE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
super.onPageFinished(view, url);
}
}
Set above client to your webView:
webView.setWebViewClient(new MyWebViewClient());
You can also add an TextView below your ProgressBar and set visibility of that. Good luck.

Adding loading spinner on Action Bar while the WebView loads?

I am developing an android app. which is using webview to render a html page but it stays blank while the page loads. I want to add a loading spinner in the action bar so the user knows that something is loading and it not blank.
Please can anyone guide me how to do that.
My existing code -
package com.pranavsethi.dpsrkp;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Achievements extends Activity{
private WebView mWebView;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webvew_client_layout);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
//For web view
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true); //enable javascript
mWebView.getSettings().setBuiltInZoomControls(true); //enable zoom
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.setScrollbarFadingEnabled(true);
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
// handle download, here we use brower to download, also you can try other approach.
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
mWebView.loadUrl("http://pranavsethi.tk"); // name of website to load
mWebView.setWebViewClient(new HelloWebViewClient()); //removing loading progressbar
}
private class HelloWebViewClient extends WebViewClient{ //our web client
#Override
public void onReceivedError(WebView view, int errorCode, //Code for checking the internet connection and return the error if fails
String description, String failingUrl) {
Intent intent = new Intent(Achievements.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return;
}
#Override
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 boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
overridePendingTransition (R.anim.right_slide_in, R.anim.fade_out);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onBackPressed()
{
this.finish();
overridePendingTransition (0, R.anim.right_slide_out);
return;
}
}
SOLUTION
Add the following -
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
After -
super.onCreate(savedInstanceState);
And this in your WebViewClient
private class HelloWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url){
webview.loadUrl(url);
setProgressBarIndeterminateVisibility(true);
return true;
}
#Override
public void onPageFinished(WebView webview, String url){
super.onPageFinished(webview, url);
setProgressBarIndeterminateVisibility(false);
}
}

backbutton on my android webview

I tried to add a back button to my android webview but i've got this error:
The method onBackPressed() of type new WebViewClient(){} must override or implement a supertype method
This is my Java file:
package sherdle.donald.duck.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
WebView webview;
final Activity activity = this;
#Override
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.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 void onBackPressed() {
// do something on back.
return;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://example.com");
}
}
Thanks for your help.
According to the doc, there is no onBackPressed method in the WebViewClient class. Did you want to Override it on your activity ?
try smthing like this:
package sherdle.donald.duck.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
WebView webView;
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(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://example.com");
}
#Override
public void onBackPressed (){
if(webView.canGoBack()) webView.goBack();
else super.onBackPressed();
}
}
You have to override the onkeyDown() method in your Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(mWebView.canGoBack() == true){
mWebView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Try this
package sherdle.donald.duck.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
WebView webview;
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://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) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if(mWebView.canGoBack() == true)
webview.goBack();
else finish();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
}
And this method should be override in Activty.
WebView webView = (WebView) findViewById(R.id.webview);
Change it to:
webView = (WebView) findViewById(R.id.webview);
and then use the second answer - works like a charm!

Android webview loading dialog

I'm trying to implement a loading dialog in my webview application but whatever I do it just won't work.
What I want is the following, everytime someone clicks a link in the webview the loading dialog has to popup like this:
(source: wordpress.com)
And when the loading is done it has to disappear. Can anyone show me how to do it in my own source? I've tried a lot of things but there's always an issue so I really don't know how to.
This is my WebviewActivity:
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebviewActivity extends MainActivity {
private WebView myWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
myWebView = (WebView)findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.requestFocus(View.FOCUS_DOWN);
myWebView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
}
});
}
#Override
public void onResume() {
super.onResume();
if ( isOnline() == true )
myWebView.loadUrl(webLink);
else if ( isOnline() == false )
showNoConnectionDialog();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
Thank you very much for your help!!
You have to override the WebViewClient like this,
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, final String url) {
progressDialog.cancel();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.show();
}
});
webview.loadUrl(TwitterUrl);
This is my final solution:
myWebView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progressDialog.show();
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
progressDialog.dismiss();
}
});
This can be possible with WebChromeClient. It does worked for me.
Code snippet :
progressDialog.show(); // Add before page load
webView.setWebChromeClient(new HelpWebChromeClient());
private class HelpWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
if(newProgress == 100)
progressDialog.dismiss();
}
}

Android progressBar random crash with nullPointerException, can't understand why

Here's one of the tabs I have that loads a page.
package realstrat.cfostudio.magazineapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import realstrat.cfostudio.magazineapp.R;
public class TabActivity3 extends Activity {
WebView mWebView;
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("--company URL--");
mWebView.setWebViewClient(new FirstTabWebViewClient());
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("OverviewMode", mWebView.getSettings().getLoadWithOverviewMode());
mWebView.saveState(savedInstanceState);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
((WebView)findViewById(R.id.webview1)).restoreState(savedInstanceState);
if (savedInstanceState.getBoolean("OverviewMode") == false) {
((WebView)findViewById(R.id.webpageview)).getSettings().setLoadWithOverviewMode(false);
((WebView)findViewById(R.id.webpageview)).getSettings().setUseWideViewPort(false);
}
else {
((WebView)findViewById(R.id.webpageview)).getSettings().setLoadWithOverviewMode(true);
((WebView)findViewById(R.id.webpageview)).getSettings().setUseWideViewPort(true);
}
return;
}
private class FirstTabWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// YouTube video link
if (url.startsWith("vnd.youtube"))
{
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return (true);
}
if (url.endsWith("-m.html")){
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
}
else {
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
}
view.loadUrl(url);
return true;
}
public void onPageStarted(WebView view, String url, Bitmap favicon){
progressBar = ProgressDialog.show(TabActivity3.this, "", "Loading...", true);
}
public void onPageFinished(WebView view, String url) {
progressBar.hide();
if (url.endsWith("-m.html")){
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
}
else {
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
}
return;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Context context = getApplicationContext();
CharSequence text = "Desc: " + description;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Once in a while it will crash with a nullPointerException on the line progressBar.hide() under onPageFinished(). That doesn't make any sense since onPageStarted() starts the progressBar, and onPageStarted always comes before onPageFinished(). Why is this?
This only happens like, once in 10 times or something, which is really confusing to me.
It usually happens (always?) when the activity is being started for the first time.
try this
if(progressBar!=null)
progressBar.hide();
Maybe the Activity has been restarted in between the two callbacks? Try rotating the phone while the progressBar is shown to see what the results are.
Try to load progress bar as singleton object. If you create anther progress bar object before hide first one then second progress bar will crash in hide().
if(_progressBar == null)
_progressBar = new ProgressDialog(this);

Categories

Resources