I am using WebView for loading a website. But it is very slow and is leaking when specific websites are loaded.
I am loading WebView with the following code.
#Override
protected void onNewIntent(Intent intent) {
if (intent.getStringExtra("url") != null) {
webView.loadurl(intent.getStringExtra("url"));
}
}
But I am calling webView.loadUrl(Config.URL); (Config.URL may contain same url as specified above) in onCreate() method after initializing WebView with the following.
this.webView = (WebView) findViewById(R.id.wv);
this.webView.getSettings().setJavaScriptEnabled(true);
this.webView.getSettings().setLoadsImagesAutomatically(true);
this.webView.getSettings().setDomStorageEnabled(true);
this.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
MyClient client = new MyClient(WebActivity.this, (ProgressBar)findViewById(R.id.progressBar));
webView.setWebViewClient(client);
Loading a from onCreate() is working fine (not fine, it's too slow). But
the same URL that is loading from onNewIntent() is not working!!!.
After I did this inonNewIntent() no URLs got loaded using
webView.loadurl() and the current page is getting immovable. ie. the
scrollbars are moving in WebView but page is not scrolling. I tested
the same URL in onCreate() and it is working.
For doing that I am passing url with
intent.putExtra("url", Config.URL+targetUrl);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
with the pending intent from the notifications. Although it is working in some devices i.e Google Nexus. But it is not working on most of the phones.
I have
android:hardwareAccelerated="true"
Myclient
public class MyClient extends WebViewClient{
private Context context;
private Activity activity;
private Handler handler;
private Runnable runnable;
private ProgressBar viewBar;
private String ret,ret2;
public void setFirstLoad(boolean firstLoad) {
this.firstLoad = firstLoad;
}
private boolean firstLoad=false;
public MyClient(Activity activity, ProgressBar bar) {
this.context = activity.getApplicationContext();
this.activity = activity;
viewBar=bar;
handler=new Handler();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}else if(url.startsWith("http:") || url.startsWith("https:")) {
*//*view.setVisibility(View.GONE);
viewBar.setVisibility(View.VISIBLE);*//*
view.loadUrl(url);
}
return true;*/
if (Uri.parse(url).getHost().equals("www.somepage.com")) {
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Answers.getInstance().logShare(new ShareEvent()
.putContentId(Build.USER)
.putMethod(shareName(url))
.putContentName(contentDecode(url))
.putContentType("news_share"));
}catch (android.content.ActivityNotFoundException e){
Log.e("Activity not found",e.toString());
Toast.makeText(context,"Application not found",Toast.LENGTH_LONG).show();
}
return true;
}
#Override
public void onReceivedError(final WebView view, int errorCode, String description, final String failingUrl) {
//Clearing the WebView
try {
view.stopLoading();
} catch (Exception e) {
}
try {
view.clearView();
} catch (Exception e) {
}
if (view.canGoBack()) {
view.goBack();
}
view.loadUrl("about:blank");
//Showing and creating an alet dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
alertDialog.setTitle("Error");
alertDialog.setMessage("No internet connection was found!");
alertDialog.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
view.loadUrl(failingUrl);
}
});
AlertDialog alert = alertDialog.create();
alert.show();
//Don't forget to call supper!
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onLoadResource(final WebView view, String url) {
super.onLoadResource(view, url);
//injectScriptFile(view, "js/script.js");
injectCSS(view,"css/style.css");
if (firstLoad){
firstLoad=false;
view.setVisibility(View.INVISIBLE);
viewBar.setVisibility(View.VISIBLE);
runnable=new Runnable() {
#Override
public void run() {
viewBar.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
}
};
handler.postDelayed(runnable,2000);
}
// test if the script was loaded
// view.loadUrl("javascript:setTimeout(hideMe(), 200)");
}
/*#Override
public void onPageFinished(final WebView view, String url) {
//System.gc();
}*/
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
System.gc();
}
The question is: What is the problem when using loadurl() method in onNewIntent()?
Try this from where you loads webview
web.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
});
You can use the webclient to handle the webview. Here I include the javascript with loading.
String aboutURL="YOUR URL";
final ProgressDialog pd = ProgressDialog.show(, "", "Please wait", true);
WebSettings settings=Webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(true);
settings.setDomStorageEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setDatabaseEnabled(true);
settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
Webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
}
});
Webview.loadUrl(aboutURL);
Here Loading is processed based on network
Use Handler to post a delay action as below will fix this, but I don't known why.
new Handler().post(webView.loadurl(url));
Related
I have problem with reducing the time of displaying progress bar in WebView. For underesting a add image. enter image description here.
Where I can implement some thread of something to stop showing progress bar for one second, while my web running in WebView?
I tried implement thread before showing progress bar in onPageStarted, but it waiting for whole loading page, not only for loading progress bar.
We have very slow loading on web page, so we need showing to users one or two second loading page in webview without progressbar, after this time show "loading" progress bar.
If you have question, please ask me, we need quick respond to resolve this problem. I'm trying to find some solution, but nothing.
Thanks a lot!
There is my ChromeClien.class
public class MyWebChromeClient extends WebChromeClient {
private ProgressListener mListener;
public MyWebChromeClient(ProgressListener listener) {
mListener = listener;
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
mListener.onUpdateProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
public interface ProgressListener {
public void onUpdateProgress(int progressValue);
}}
There is MainActivity.class
public class MainActivity extends AppCompatActivity{
private WebView webview;
ProgressDialog prDialog;
String cekani;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieManager.getInstance().setAcceptCookie(true);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, PrvniSpusteni.class));
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
if(KontrolaInternetu.isInternetAvailable(MainActivity.this)) //Vrátí hodnotu TRUE, pokud je připojení k internetu k dispozici
{
webview =(WebView)findViewById(R.id.webView);
//Nastavení webové stránky
webview.loadUrl(getString(R.string.url_aplikace));
webview.setWebViewClient(new MyWebViewClient());
//Puštění JavaScriptu pro web
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
WebSettings ws = webview.getSettings();
ws.setJavaScriptEnabled(true);
ws.setAllowFileAccess(true);
if (android.os.Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true);
}else {
CookieManager.getInstance().setAcceptCookie(true);
}
webview.setWebChromeClient(new WebChromeClient(){
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onPermissionRequest(final PermissionRequest request) {
request.grant(request.getResources());
}
});
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ECLAIR) {
try {
Log.d(TAG, "Enabling HTML5-Features");
Method m1 = WebSettings.class.getMethod("setDomStorageEnabled", new Class[]{Boolean.TYPE});
m1.invoke(ws, Boolean.TRUE);
Method m2 = WebSettings.class.getMethod("setDatabaseEnabled", new Class[]{Boolean.TYPE});
m2.invoke(ws, Boolean.TRUE);
Method m3 = WebSettings.class.getMethod("setDatabasePath", new Class[]{String.class});
m3.invoke(ws, "/data/data/" + getPackageName() + "/databases/");
Method m4 = WebSettings.class.getMethod("setAppCacheMaxSize", new Class[]{Long.TYPE});
m4.invoke(ws, 1024*1024*8);
Method m5 = WebSettings.class.getMethod("setAppCachePath", new Class[]{String.class});
m5.invoke(ws, "/data/data/" + getPackageName() + "/cache/");
Method m6 = WebSettings.class.getMethod("setAppCacheEnabled", new Class[]{Boolean.TYPE});
m6.invoke(ws, Boolean.TRUE);
Log.d(TAG, "Enabled HTML5-Features");
}
catch (NoSuchMethodException e) {
Log.e(TAG, "Reflection fail", e);
}
catch (InvocationTargetException e) {
Log.e(TAG, "Reflection fail", e);
}
catch (IllegalAccessException e) {
Log.e(TAG, "Reflection fail", e);
}
}
}
else
{
//Zobrazení AlertDialogu pokud není připojení k internetu
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isFinishing()){
new AlertDialog.Builder(MainActivity.this)
.setTitle(getString(R.string.no_internet))
.setMessage(getString(R.string.internet))
.setCancelable(false)
.setIcon(R.drawable.icon)
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}})
.setNegativeButton(getString(R.string.zrusit), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}})
.show();
}
}
});
}
}
//Při stisknutí tlačítka zpět se uživatel vrátí ve webview nazpět bez toho, aby aplikace spadla.
private final String TAG = MainActivity.class.getSimpleName();
// Progress bar - zobrazí se tehdy, pokud čekám na načítání stránky
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
prDialog = new ProgressDialog(MainActivity.this);
prDialog.setIcon(R.drawable.icon);
prDialog.setMessage(getString(R.string.nacitani_webove_stranky));
prDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(prDialog!=null){
prDialog.dismiss();
}
}
}
//Při stisknutí tlačítka zpět se uživatel dostane zpět pouze ve webview
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".mp3")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "audio/*");
view.getContext().startActivity(intent);
return true;
} else if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
view.getContext().startActivity(intent);
return true;
} else {
return true;
}}}
Hey bro, you don't necessarily need to implement threads for your
requirement. Firstly you can load the url in the webview and after a
particular time period you can start displaying progress bar. For
calling the progress bar after certain time period you can use
Handler.
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
prDialog = new ProgressDialog(MainActivity.this);
prDialog.setIcon(R.drawable.icon);
prDialog.setMessage(getString(R.string.nacitani_webove_stranky));
prDialog.show();
}
}, 100);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(prDialog!=null){
prDialog.dismiss();
}
}
Please help me. How to disable webview open new page ? I want to disable this behaviour, so if I click on a link, don't load it. I've tried this solution and edited a bit for myselft, but not worked. My webviewclient code:
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://example.com");
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
}
public class myWebClient extends WebViewClient
{
#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
// This method is used to detect back button
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
In your WebViewClient, you can load only specific url that you want as below,
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.equals("my url")) {
view.loadUrl(url);
}
return true;
}
Firstly you use web view you create web activity like this:
xml layout:-
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
WebView Activity:-
public class WebViewActivity extends AppCompatActivity {
#BindView(R.id.webView1)
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
// i am using intent getting the value from like this
Intent intent2 = getIntent();
Bundle bundle = intent2.getExtras();
String link = bundle.getString("Agreement_URL");
Log.e("link---",""+link);
String file_type=bundle.getString("file_type");
if(file_type.equals("PDF"))
{
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://docs.google.com/gview?embedded=true&url="+link);
setContentView(webView);
}
else
{
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(link);
}
}
/** Method on BackPressed Button click*/
public void onBackPressed(){
super.onBackPressed();
/** Activity finish*/
finish();
}
pass the value like this from previous activity
Intent intent =new Intent(context, WebViewActivity.class);
intent.putExtra("Agreement_URL","http://54.183.245.32/uploads/"+ finalUploadDoc);
intent.putExtra("file_type","PDF");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.e("ggg",""+ finalUploadDoc);
context.startActivity(intent);
try this it helps you
When I tried to login it shows a popup window and asking for email and password
when I entered my correct email and password and click on login it doesn't redirect to my account it only shows the same page
this is my MainActivity
you can also download my application for better understanding my problems https://play.google.com/store/apps/details?id=in.bidforx.bidforx
use email: anup.gorai.9835#gmail.com
password:78907890
private ProgressBar progressBar;
private WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppRate.with(this)
.setInstallDays(0)
.setLaunchTimes(3)
.setRemindInterval(0)
.monitor();
AppRate.showRateDialogIfMeetsConditions(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo(
));
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.loadUrl("https://bidforx.com");
if (Build.VERSION.SDK_INT>=21){
CookieManager.getInstance().setAcceptThirdPartyCookies(webView,true);
}else{ CookieManager.getInstance().setAcceptCookie(true);}
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent=new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
String shareBody="Add World ";
String shareSub="Download the BidForx App and Buy everthing in 1% Download the App now https://play.google.com/store/apps/details?id=in.bidforx.bidforx";
myIntent.putExtra(Intent.EXTRA_TEXT,shareBody);
myIntent.putExtra(Intent.EXTRA_TEXT,shareSub);
startActivity(Intent.createChooser(myIntent,"Share using"));
}
});
}
private class WebViewClientDemo extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
// on back pressed
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
finish();
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
When I try to login, I am getting an error
"Uncaught TypeError: Cannot read property 'username' of null", source: https://bidforx.com/js/login.js (2)
There must be some problem in login.js line 2. In line 2 you try to call localStorage, and somehow you can login with browser but not with app.
I haven't tried it yet but you should allow WebView to use HTML5 local storage feature first and see if you can login with app.
webView.getSettings().setDomStorageEnabled(true);
and I think you should do the item checking like this:
if (localStorage.hasOwnProperty("username")) {
//
}
in order to prevent TypeError
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);
}
}
I am Trying to implement the horizontal progressbar.But I am not understanding how to implement it in my class.Now I have implemented the dialog box which is in the format of sphener,But I want it in horizontal format showing progress of activity I am downloading some contents at that time it should show the progress.
My code is
public class Loginwebview extends Activity {
WebView webview;
String url1;
Bundle bundle=null;
private ProgressDialog progressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weblogin);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
bundle = new Bundle();
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
url1=url.toString();
bundle.putString("parameter", url1);
progressDialog = ProgressDialog.show(Loginwebview.this, "", "Loading...");
new Thread() {
public void run() {
try{
if(url1.contains("&mydownloads=true"))
{
if(url1.contains(".zip"))
{
sleep(150000);
Intent i1 = new Intent(Loginwebview.this, DownloadZipActivity.class);
i1.putExtras(bundle);
startActivityForResult(i1,0);
}
else
{
sleep(40000);
Intent i2 = new Intent(Loginwebview.this, DownloadOther.class);
i2.putExtras(bundle);
startActivityForResult(i2, 0);
}
}
else if(url1.contains("mydownloads=true"))
{
Log.d("its in Mydownloadssss",url1.toString());
Intent i3=new Intent(Loginwebview.this,Downloadlist.class);
i3.putExtras(bundle);
startActivityForResult(i3, 0);
}
}
catch(Exception e)
{
}
progressDialog.dismiss();
}
}.start();
return true;
}
public void onPageFinished(WebView view, String url1) {
Log.i("inside onpage", "Finished loading URL: " +url1);
String mainurl=url1;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e("onReceivedError", "Error: " + description);
}
});
webview.loadUrl("http://xxx/PublicModules/UserLoginVerify.aspx?userid=809&deviceid=DA0CE50D-0EEB-5E8E-9DCA-AED00F9BDFE5");
}
}