i am not able to play video on Android web view.
I have kept the html and video file in my assets folder.
Whenever i load the html file , it gives me the error
05-01 12:31:16.092: E/MediaResourceGetter(17241): Unable to read file: file:///android_asset/MediaBook2%20(2)/2B952499A0E681.mp4
And whenever i press on the play button i get the following error
05-01 12:31:23.680: E/chromium(17241): [ERROR:webmediaplayer_android.cc(328)] Not implemented reached in virtual void content::WebMediaPlayerAndroid::setRate(double)
05-01 12:31:23.710: E/MediaPlayer(17241): error (1, -2147483648)
05-01 12:31:23.710: E/MediaPlayer(17241): Error (1,-2147483648)
Am able to load any remote video and run,But problem is when i load the local video from the assets folder
Code to load the files and setup the web view
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Remove title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_webview);
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
// Keep the webview setup ready
setupWebView();
}
public void setupWebView()
{
webView = (WebView) findViewById(R.id.webView);
// progressBar = (ProgressBar) findViewById(R.id.progressBarForWebView);
WebSettings webViewSettings = webView.getSettings();
webViewSettings.setJavaScriptEnabled(true);
webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webViewSettings.setPluginState(PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
webView.setSoundEffectsEnabled(true);
webView.setWebViewClient(new SLCWebViewClient());
webView.setWebChromeClient(new WebChromeClient());
loadContentsInWebView();
}
public void loadContentsInWebView()
{
String localURL = "file:///android_asset/MediaBook2 (2)/SampleForVideo.html";
logger.debug("WebView URL: {}", localURL);
try {
webView.loadUrl(localURL);
}
catch (Exception e) {
e.printStackTrace();
logger.error("Error while loading url", e);
}
}
private class SLCWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.setWebChromeClient(new WebChromeClient()
{
private View mCustomView;
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
});
webView.loadUrl(url);
return true;
}
The Sample For Video.html code
<!DOCTYPE html>
<html>
<title>Testing for Video</title>
<body>
<video width="320" height="240" controls>
<source src="2B952499A0E681.mp4">
</video>
</body>
</html>
Code for the layout file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="#+id/fullscreen_custom_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000"/>
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
cheers,
Saurav
Thanks to Marcin for his answer.
I could run the the html files by loading the video.
My problem was i was using /MediaBook2 (2)/SampleForVideo.html. But the '/' should be removed when loading from assets. I splitted the string by trimming off the '/' and it worked.
But that was just a sample scenario i was working on to clear my understanding.
I have a much bigger folder structure and now when the .mp4 file is eventually loaded.
The media player is shown but the player is not playing any file.
The file:///android_asset protocol is a WebView-specific thing. That is: other system components can't read those URLs.
The MediaResourceGetter doesn't use the WebView's network stack and therefore doesn't "understand" the file:///android_asset protocol.
In your other question you mentioned you use a local http server - try serving the .mp4 from that.
if have still a problems about play video on android webview in 2018, let's give a chance and try code below.
Java:
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
final WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setPluginState(WebSettings.PluginState.ON);
webview.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() {
document.getElementsByTagName('video')[0].play();
})()");
}
});
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("http://html5demos.com/video");
}
#Override
protected void onPause() {
super.onPause();
webview.onPause();
}
#Override
protected void onResume() {
webview.onResume();
super.onResume();
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.com">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:hardwareAccelerated="true"
android:allowBackup="false"
android:icon="#mipmap/logo_example"
android:label="#string/app_name"
android:roundIcon="#mipmap/logo_example"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
References:
https://gist.github.com/aprock/5913322
Related
I have a weird problem with Andriod WebView. My website's Humberger menu expands and closes fine in my mobile browser but on my Android WebView app when the menu is clicked it's not working (doesn't expand fully to show menu items).
I've already tried the following lines of code from various answers on StackOverFlow:
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
settings.setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
Mobile Browser Working Correctly:
Android WebView App Not Working Correctly
Here is my Andriod WebView App code:
package com.app.pvm;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.MyWebView);
webView.setWebChromeClient(new MyChromeClient());
webView.setWebViewClient(new BrowserClient());
WebSettings settings = webView.getSettings();
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.loadUrl("https://test.app");
}
}
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/MyWebView"/>
</LinearLayout>
BrowserClient Class code:
package com.app.pvm;
import android.graphics.Bitmap;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
class BrowserClient extends WebViewClient {
public BrowserClient(){
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
Note: I'm using Andriod Studio for the WebView App.
your WebView should fit whole window, use match_parent
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/MyWebView"/>
wrap_content set for height makes this inner dropdown wrongly measured, in the meanwhile whole web content stretches WebView to size of its parent (LinearLayout) and became scrollable
I am creating an app that loads a website through the webview, and before it shows a splash screen. The problem is that after the splash screen a white screen appear and then the webview loads.
I don't want to use a timer in the splash scree, I want it to be gone once the webview is loaded. I saw that I need to move the splash activity to the main activity, but I am not sure how. I am a beginner with android studio.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.atlasdatabase">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name=".SplashActivity"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
<activity
android:name=".MainActivity"
android:theme="#style/Theme.AppCompat.NoActionBar">
</activity>
</application>
</manifest>
MainActivity.java:
package app.atlasdatabase;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import static app.atlasdatabase.R.style.AppCompatAlertDialogStyle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
WebView myWebView = (WebView) findViewById(R.id.atlasdatabase);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.loadUrl("file:///android_asset/index.html");
}
/**
* Exit the app if user select yes.
*/
private void doExit() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this, AppCompatAlertDialogStyle);
alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exitmsg);
alertDialog.setNegativeButton(R.string.no, null);
alertDialog.show();
}
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.atlasdatabase);
if(webView.canGoBack()){
webView.goBack();
}else{
/* Close the app without the Dialog
super.onBackPressed();
*/
/* Use the dialog to Exit the App */
doExit();
}
}
}
SplashActivity.java:
package app.atlasdatabase;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
tools:context="atlasdb.atlasdatabase.MainActivity">
<WebView
android:id="#+id/atlasdatabase"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_home_footer">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
background_splash.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Background color -->
<item android:drawable="#color/colorPrimary"/>
<!-- Image at the center of the screen -->
<item>
<bitmap android:gravity="center" android:src="#drawable/splash"/>
</item>
</layer-list>
I found the simplest answer in
How to manage the Blank White Loading screen of an Android Webview?, which helped me to solve the problem I was facing without any Splash activity Screen:
In Android manifest:
<activity android:name=".MainActivity"
android:theme="#style/Splash">
...
and on Activity, after creating webView, set the background to be transparent.
myWebView = (WebView)findViewById(R.id.webView);
myWebView.setBackgroundColor(Color.TRANSPARENT);
(I have added progress bar popup and killed on pageFinished for users to know loading is in progress.)
Here in the answer you can see comments where you need to concern.
You don't need a SplashActivity for this.
You can keep a view which is match_parent to the root view (so it will go full screen) and add your image or whatever to that.
When your Activity loads make sure it is visible/or like in the code given # onPageStarted if the view is not loaded yet, you can display your logo..
When the web view is ready as in the comment # onPageFinished make your splashView invisible or view gone!
for these tasks you can use android:visibility="gone" in Xml, yourRootViewWithImage.setVisibility(View.VISIBLE);
yourRootViewWithImage.setVisibility(View.GONE); use these lines in proper places!
Credit goes to this post, example :
public class MainActivity extends AppCompatActivity {
private boolean loadingFinished = true;
private boolean redirect = false;
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
myWebView = (WebView) findViewById(R.id.atlasdatabase);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.loadUrl("file:///android_asset/index.html");
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(
WebView view, WebResourceRequest request) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
myWebView.loadUrl(request.getUrl().toString());
return true;
}
#Override
public void onPageStarted(
WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
#Override
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
//HIDE LOADING IT HAS FINISHED // HIDE YOUR SPLASH/LOADING VIEW
} else{
redirect = false;
}
}
});
}
/// below code ..
}
I've experienced this problem before and this is just a hack , but i had the same problem and for some reason that i'm still reading why but changing the web view from opening from a fragment to an activity made the white screen at the start of loading the web view went away.
I am trying to open a camera using android webView widget. I googled many times to find out a solution but i could not findout a solution to open a camera in android webview.Here is the code i have used.
public class ShowWebView extends Activity {
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_web_view);
// Find the web view in our layout xml
myWebView = (WebView) findViewById(R.id.webView1);
// Settings
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setAllowFileAccess(true);
// Set a web view client and a chrome client
myWebView.setWebViewClient(new WebViewClient());
myWebView.setWebChromeClient(new WebChromeClient() {
// Need to accept permissions to use the camera and audio
#Override
public void onPermissionRequest(final PermissionRequest request) {
Log.d(TAG, "onPermissionRequest");
request.grant(request.getResources());
myWebView.loadData(summary, "text/html", null);
}
}
The following are the permission set in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
layout File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
Could some one please help me out how to open a camera in web View on Android 6.0
I want to open the following link in WebView
https://tickets.musiconelive.com/admin/SACValidateBarcode.asp
I am using following code to do that
web=(WebView)findViewById(R.id.web);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("https://tickets.musiconelive.com/admin/SACValidateBarcode.asp");
but it's not opening in WebView and instead is opening in the browser.
How can I fix this problem?
may this helps you
WebSettings mWebSettings;
WebView mWebView = (WebView)findViewById(R.id.services_detail_magnified_image);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
mWebView.setBackgroundColor(Color.TRANSPARENT);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_INSET);
mWebView.loadUrl(StaticURL.uChangePassword);
mWebView.setWebViewClient(new MyWebViewClient());
private class MyWebViewClient extends WebViewClient {
#Override
//show the web page in webview but not in web browser
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl (url);
return true;
}
}
i think this will help you.
package com.adySol;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
public class adySol extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url ="http://tickets.musiconelive.com/admin/SACValidateBarcode.asp";
WebView wv=(WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginState(PluginState.ON);
wv.getSettings().setAllowFileAccess(true);
wv.loadUrl(url);
}
}
Main.xml::
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white"
>
<WebView android:id="#+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent"></WebView>
</LinearLayout>
Manifest permission :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
You need to set WebViewClient()
This is example in kotlin
webview.apply {
loadUrl("https://www.google.com/")
webViewClient = WebViewClient()
}
As per android documentation
public void setWebViewClient (WebViewClient client)
Sets the WebViewClient that will receive various notifications and requests. This will replace the current handler.
webView=findViewById(R.id.webView);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR)
webView.setBackgroundColor(Color.TRANSPARENT);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_INSET);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
webView.setWebViewClient(MyWebViewClient());
webView.loadUrl("https://google.com/");
class MyWebViewClient extends WebViewClient() {
#override
boolean shouldOverrideUrlLoading(WebView view , WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request)
}
}
I am implementing a webview. I want two buttons on the top of the web page.
I have one vertical linear layout, inside of which is one horizontal layout with two buttons, and one webview outside of the horizontal layout.
I am simply loading the Google URL in Java code.
Every time I run the application, it opens a new browser on top of the application and the buttons get hidden. It's not showing the buttons above the webview.
Please help and tell me how can I load a URL in the webview without opening another browser, or how I can prevent it by opening a native browser, so that the page is loaded in the webview itself and not a new browser.
Thanks all
Ya. You must implement WebViewClient class and Override shouldOverrideURLLoading() method in this class.
Why ? Because webview just open your "exactly link", if that link redirect other links, android will open default browser for this action.
In your example, as you know, when you connecting to google.com google will redirects to google at your country. Example, if you are in China, google will go to google.com.cn, if in Vietnam, will be google.com.vn.
Here is my simple example: (you can imagine this is an new browser, :laugh)
First is layout xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<EditText
android:id="#+id/url"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:hint="Input URL"/>
<Button
android:id="#+id/run"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="0"
android:text="GO"/>
</LinearLayout>
<WebView
android:id="#+id/webview"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
</LinearLayout>
Here is code of main activity:
package com.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class WebViewExample extends Activity{
WebView webView;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webview);
Button button = (Button) findViewById (R.id.run);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
gotoPage();
}
});
}
private void gotoPage(){
EditText text = (EditText) findViewById(R.id.url);
String url = text.getText().toString();
WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webView.setWebViewClient(new Callback()); //HERE IS THE MAIN CHANGE
webView.loadUrl(url);
}
private class Callback extends WebViewClient{ //HERE IS THE MAIN CHANGE.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (false);
}
}
}
Hope this help you :)
Adding the following code before loadUrl() will solve this problem,
wv.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}});
The shouldOverrideUrlLoading() from WebViewClient does this job. Here goes the Android doc for shouldOverrideUrlLoading,
Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url...
http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading%28android.webkit.WebView,%20java.lang.String%29
My XML implementation:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:background="#android:color/transparent"
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</RelativeLayout>
My Java implementation:
WebView webView;
public final String GlobalUrl = "http://slashdot.org/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_application_activity);
webView = (WebView) findViewById(R.id.webView);
loadWebViewLoad(webView);
}
private void loadWebViewLoad(WebView webview) {
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setSupportMultipleWindows(true);
webview.setWebViewClient(new WebViewClient());
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl(GlobalUrl);
}
And final result is:
The layout should something similar to this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:id="#+id/button1"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_weight="1"/>
<Button android:id="#+id/button2"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_weight="1" />
</LinearLayout>
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
And you can also refer to the Need help changing from stock android browser to webview to see if you are launching the url correctly.
I had the exact same problem and fortunately after browsing the web for about an hour I mixed some of the things I found and it worked.
this is the code:
WebView webView;
webView = ((WebView) rootView.findViewById(R.id.detail_area));
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(mItem.link);
where "detail_area" was my webview, rootView was my selected item inside a "Master/Detail Flow", link was the URL I wanted to open.
I tried this. its working for me. it does not open new window. it will open webview page only. its hiding for new browser asking window open..
private WebView webView;
String strUrl="url" ;
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(strUrl);
webView.setWebViewClient(new WebViewClient());
Add the below line in your xml file which having webview
tools:context=".MyActivity" (name of your activity)
This might be a late post but it might help other developers...
You need to set setWebViewClient on webview before loading the URL on it like below,
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
Some background of the above code, Documentation states in literals words like below about the shouldOverrideUrlLoading method.
* #param view The WebView that is initiating the callback.
* #param request Object containing the details of the request.
* #return {#code true} if the host application wants to leave the current WebView
* and handle the url itself, otherwise return {#code false}.
*/
#Override
#SuppressWarnings("deprecation") // for invoking the old shouldOverrideUrlLoading.
#RequiresApi(21)
public boolean shouldOverrideUrlLoading(#NonNull WebView view,
#NonNull WebResourceRequest request) {
if (Build.VERSION.SDK_INT < 21) return false;
return shouldOverrideUrlLoading(view, request.getUrl().toString());
}
If you see the documentation above for returning the value, it says,
#return {#code true} if the host application wants to leave the current WebView
*and handle the url itself, otherwise return {#code false}.
So it simply says, If you return true from shouldOverrideUrlLoading method, it'll ask the default browser of your device to handle the request of opening the URL and if you return false, then your URL will be loaded through webview only.
Now you can load your URL in webview either after this setWebViewClient call or you can also load your URL inside shouldOverrideUrlLoading method before returning the value.
this code work for me
thanks...
WebView wbView = (WebView) findViewById(R.id.webView);
wbView.getSettings().setJavaScriptEnabled(true);
wbView.setWebViewClient(new WebViewClient());
wbView.loadUrl("http://ppid.polinela.ac.id");