I'm new in android development and I am trying out the WebView example in the official android site.
http://developer.android.com/guide/tutorials/views/hello-webview.html
But I do everything they say...which is pretty simple: I create the project, edit the layout file, then I add the code, etc. No problems building...but when I launch the app in the simulator I just got a black screen. It is like if the Layout is empty...like if the WebView is not created.
What am I doing wrong?
Sorry about that – that link is a bit outdated. The fixed version of this tutorial is available here:
http://developer.android.com/guide/webapps/webview.html
We should remove the old link; I'll file a bug.
And note, the error is that setContentView isn't being called.
in oncreate method add WebView.enablePlatformNotifications();
in manifest file add
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
now it works fine...
webview_id = (WebView)findViewById(R.id.webview_id);
webview_id.getSettings().setJavaScriptEnabled(true); // enable javascript
WebSettings webSettings = webview_id.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(true);
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webview_id.setInitialScale(90);
webSettings.setLoadWithOverviewMode(true);
webview_id.requestFocusFromTouch();
webview_id.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Snackbar.with(getApplicationContext()).dismiss();
Snackbar.with(getApplicationContext()) // context
.text(description) // text to display
.show(MainActivity.this);
}
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
}
});
if(isNetworkAvailable()){
webview_id .loadUrl("http://helloworld.org/");
}else{
Snackbar.with(getApplicationContext()).dismiss();
Snackbar.with(getApplicationContext()) // context
.text("Please Check your Internet Connection") // text to display
.show(MainActivity.this);
progressBar.setVisibility(View.VISIBLE);
}
}
Related
Why the web view can show a white page, although the page opens in the browser. At first there was an error:
net::ERR_CACHE_MISS
but after I added this code:
wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
there are no errors, but the page does not load, just a white page is displayed. The page opens by clicking on the button inside in webview.Clicking is not processed on the mobile application side.
My manifest also has permission:
<uses-permission android:name="android.permission.INTERNET" />
Please help me. I don’t understand why this can happen. The page also opens successfully on iOS.
Here is my code:
private void initView(String url) {
wvDetail.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("webview://closeScreen")) {
activity.finish();
return true;
} else
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(activity, description, Toast.LENGTH_LONG).show();
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
});
wvDetail.getSettings().setJavaScriptEnabled(true);
wvDetail.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wvDetail.loadUrl(url);
}
It seems to be a problem with the settings of your webview. Try and add the following settings:
WebSettings settings = wvDetail.getSettings();
//if your page needs javascript
settings.setJavaScriptEnabled(true);
//to handle your cache
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setAppCacheEnabled(true);
settings.setAppCachePath(cacheDir.path);
To enable some functionalities of JS you should also use setdomStorageEnabled (see this question):
settings.setDomStorageEnabled(true)
If your page is still not loading and you fully trust the web page that you will load, I would also use this settings to give even more access to the webview:
settings.setBlockNetworkImage(false);
settings.setLoadsImagesAutomatically(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
settings.setSafeBrowsingEnabled(false);
}
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAllowFileAccess(true);
To load the webview with the settings of the meta tag, use:
setUseWideViewPort(true);
Finally you could check upon your webView size and make it fit on your system window like this:
wvDetail.setFitsSystemWindows(true);
Just like a bonus if you are targetting above API level 11, you could set your layer type like this:
wvDetail.setLayerType(View.LAYER_TYPE_HARDWARE, null);
I hope this explanation of the common settings used in a webview makes sense! Depending on your webpage I think that some of them can be useful to you! let me know if it works! :)
I'm new to Android Studio, and have run into a problem that I can't fix.
I'm trying to run a HTML file in a webView, but for some reason it keeps reloading to my startpage/index file, when I try to call specific HTML that includes a specific JS file.
Note: these files work fine in every desktop and mobile browser, and works on UIWebView in an Apple App.
My MainActivity looks like this:
MyWeb = (WebView) findViewById(R.id.myWebView);
MyWeb.setWebViewClient(new WebViewClient())
MyWeb.getSettings().setJavaScriptEnabled(true);
MyWeb.getSettings().setSaveFormData(true);
MyWeb.getSettings().setDomStorageEnabled(true);
MyWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
MyWeb.loadUrl("URL");
If I remove the "MyWeb.setWebViewClient(new WebViewClient())" part, the file works, but the app launches a browser with an address bar.
Please help - I've allready spend more days trying to fix this, than I care to admit.
As you have already enabled necessary settings, try doing this once:
MyWeb.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
}
});
MyWeb.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;
}
});
In order for it to not launch in a browser you must add the line
MyWeb.setWebChromeClient(new WebChromeClient());
I'm having a few issues regarding the WebViewClient on Android.
The site works perfectly on any mobile browser. Including the ChromeViewClient that I have set for debugging purposes.
And the website that I am loading does not have any issues or errors when using any other mobile browser. Using Chrome's inspector and selecting a device, using as mentioned the native Android browser and also tested on an iOS WebView Component to make sure.
The WebViewClient renders "parts" of the website. Images on one page and not the other, buttons that can not be clicked, a slider that does not work, etc. The website that I am loading is very JavaScript and HTML5 intensive. I am completely out of ideas of how to debug this issue further, are there certain JavaScript libraries that the WebViewClient can't load properly? Is there any other method you would recommend I implement while trying to debug this issue? Or am I missing some really small thing that will make me hit my head against the table?
These are the JS files we are using on the website:
bootstrap.min.js;
jquery.min.js;
swiper.jquery.min.js;
slideout.min.js;
owl.carousel.min.js.
Code for the WebView:
this.webview = (WebView)findViewById(R.id.webView);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
firstLoad = true;
return true;
}
// when the page is finished loading
public void onPageFinished(WebView view, String url){}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Toast.makeText(getBaseContext(), "Could Not load. " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
return;
}
});
alertDialog.show();
}
});
webview.loadUrl("mywebsite.com");
I got it working by setDomStorageEnabled(true);
You need to set this when using local storage.
I am trying to load the site in an android app web view.
The site loads without the images ,all the images from the site are not loaded what could be the problem.
The code for onCreate is shown below.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String url = getResources().getString(R.string.web_url);
web = (WebView) findViewById(R.id.webview01);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setUseWideViewPort(true);
web.loadUrl(url);
}
One more note, when i set javascript to false using web.getSettings().setJavaScriptEnabled(false); the images load giving a warning that javascript should be enabled to run the site properly.
This site is protected with CloudFlare ,could this be the reason images are not loaded in the android web view ?
Add
web.getSettings().setDomStorageEnabled(true);
This should work. Keep the rest as is.
Although a caveat, I don't think its recommended to enable this by default, its disabled by default. The setting allows a website to store data and reuse it. So the images are not being loaded, because this site wasn't allowed to store them on your device. This opens up a can of security concerns.
Just use this line of code. I think your problem will be solved.
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
You may need this one as well, if you are lazy-loading content:
webView.getSettings().setJavaScriptEnabled(true);
Just this will suffice
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
I had similar problem in Android 9.0. The images in the site's html were using http instead of https.
Then I changed all the http with https and everything worked!
It was very easy to change the http to https using a sql query in mySql.
I am giving the query if it helps anyone!
UPDATE table_name SET column_name = replace(column_name, '<img src="http://', '<img src="https://')
I suspect that the issue might be your webview client.
Use this instead:
webView.setWebViewClient(new WebViewClient() {
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 (pDialog.isShowing()) {
pDialog.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(FundCardWeb.this, "Page Load Error" + description, Toast.LENGTH_SHORT).show();
}
});
for me the combination of adding those did it:
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setLoadsImagesAutomatically(true);
I don't like adding unneccesery cod when so I didn't use:
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
I have faced the same issue. In the web view, the Image with the http URL was not loading in my app. The following solution fixed my issue,
webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
But in Android 9, the above solution has thrown the issue sometimes, in such case add the following line in the manifest file.
android:usesCleartextTraffic="true"
My problem was just one image, not loading in webview. I just add this two thing
In Manifest
android:usesCleartextTraffic="true"
In java oncreate() just add
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mywebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
Been trying to change the User-Agent string in the HTTP request of an Android app. I have tested this together with wireshark and the emulator, and have seen that although I set the useragent string in the webview, the associated loadUrl request does not use this user-agent string. Instead I see the Dalvik useragent string in the wireshark capture.
Here is the code abstract. Any ideas? Or does the emulator not support this?
#Override
public void run() {
assert(context != null);
...
...
webView = new WebView(context);
...
String defaultUserAgent = "betaUAteststring";
// Clear per-application caches etc
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
....
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
..
}
#Override
public void onLoadResource(WebView view, String url) {
...
}
});
// Start loading
webView.getSettings().setUserAgentString(defaultUserAgent);
String setUA = webView.getSettings().getUserAgentString();
//--> logging here shows the correct user agent, so the webview does accept the value
// However the following statement does not result in an http request with the webviews user agent
webView.loadUrl(url);
//Alternative doesn't help either (and shouldn't according to javadoc)
//Map<String,String> headerMap = new HashMap<String,String>();
//headerMap.put("User-Agent","uaTestInAMap");
//webView.loadUrl(url, headerMap);
}
Answering my own question. It appears that the emulator for whatever reason is not taking the user agent string from the webview. I have not found out the reason for this however.
The code works fine on a real device.
You miss to override the default Android behavior on open url (launch default browser).
To use your customize browser to navitage, you only have to attach a WebViewClient to WebView
That is achieve adding the following line to your code:
webView.setWebViewClient(new WebViewClient());
Cheers,
Rodrigo