I have a WebView, and after setting up a custom WebViewClient with WebView.setWebViewClient, the WebViewClient methods do not seem to be called. In particular I'm overriding onLoadResource and onReceivedError. However, neither of these are called after calling WebView.loadUrl();
Here's the code in question: https://gist.github.com/9673b619e019038848a0
What am I missing?
Are you sure you are looking for the correct log message and that your device is outputting logging properly? I essentially copied your code into a clean project and it appears to work perfectly. Glancing at the documentation it looks like you are following everything properly.
I am using the webview as the content view, that is the only significant difference I see.
For reference here is my test activity:
package com.testing.androidtest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
private static final String APP_TAG = "MYAPP";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final WebView webView = new WebView(getApplicationContext());
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d(APP_TAG, consoleMessage.message());
return true;
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(APP_TAG, "Error in WebView: " + failingUrl + "; " + description);
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
Log.d(APP_TAG, "loading resource: " + url);
}
});
webView.loadUrl("http://google.com/");
setContentView(webView);
}
}
Related
I'm trying to load a web application in WebView but I've encounter some problem.
The web application that I was trying to load was a login page and I am going to login to it.
Here is where the problem start, I have no problem loading the 1st page but after I login and it should be showing the page after I login but all I can see was a blank page, I've checked on the login log that my account was logged in but there was nothing on the WebView.
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient());
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
webView.loadUrl(url);
}
I have tried it using WebChromeClient and it was able to load without problem but I want it to load inside WebView and not open another browser.
Anyone have any idea on why this is happening?
Try this sample,
MainActivity.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView)findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(Main.this, "WebView Example", "Loading...");
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 (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(activity, "Oh no! " + 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("http://www.google.com");
}
}
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"
>
<WebView android:id="+#id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
This may helps you.
use this to load any url that you are willing to open into your web view xml
String url = "URL";
if (url != null){
webView.loadUrl(url);
}else{
String content = getIntent().getStringExtra(CONTENT_EXTRA);
webView.loadData(content, "text/html", null);
}
Please check your code with different URLs because there is no need to override shouldOverrideUrlLoading method to load the url again on login click.
I've searched on google and stackoverflow but cannot find any solutions relevant to Android API 17 and above.
I like to retrieve data from a webview on Button Click.
I like to achieve something similar to what ios has:
myText.stringByEvaluatingJavaScriptFromString
("document.getElementById('chapter-description').value")
my source code is:
package com.xyz.webviewtest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class MainActivity4 extends AppCompatActivity {
TextView textView;
#SuppressLint("JavascriptInterface")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
// new MyJavaScriptInterface(this).showHTML("HtmlViewer");
webview.loadUrl("http://www.xsoftech.com");
}
class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
public void showHTML(String html) {
new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
.setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
}
}
}
http://developer.android.com/ states that the constructor is deprecated
This constructor was deprecated in API level 17. Private browsing is
no longer supported directly via WebView and will be removed in a
future release. Prefer using WebSettings, WebViewDatabase,
CookieManager and WebStorage for fine-grained control of privacy data.
Webview have textarea so i can write something after writing i want able to get data on button click. Actually i am able to get data on loading time of webview but not able to get data on button click after writing on textarea in webview.
I found a possible solution, but I am not able to get any data on button click.
The solution is:
package example.xsoftech.sample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
public class Main2 extends Activity {
WebView webview1;
public static String data;
Button button;
String sUrl = "http://www.facebook.com/";
// String sUrl = "http://www.xsoftech.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
webview1 = (WebView)findViewById(R.id.myWebview);
webview1.getSettings().setJavaScriptEnabled(true);
webview1.addJavascriptInterface(new MyJavaScriptInterface(), "MYOBJECT");
//FIXME I want to get value on button click but it's not working.So plz give me solution for work it?
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Main2.this, "click is done: "+data, Toast.LENGTH_SHORT).show();
data= "";
webview1.loadUrl(sUrl);
}
});
webview1.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("lifecyle", "shouldOverrideUrlLoading");
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("lifecyle", "onpagefinished");
StringBuilder sb = new StringBuilder();
sb.append("document.getElementsByTagName('form')[0].onsubmit = function () {");
sb.append("var objPWD, objAccount;var str = '';");
sb.append("var inputs = document.getElementsByTagName('input');");
sb.append("for (var i = 0; i < inputs.length; i++) {");
sb.append("if (inputs[i].type.toLowerCase() === 'password') {objPWD = inputs[i];}");
sb.append("else if (inputs[i].name.toLowerCase() === 'email') {objAccount = inputs[i];}");
sb.append("}");
sb.append("if (objAccount != null) {str += objAccount.value;}");
sb.append("if (objPWD != null) { str += ' , ' + objPWD.value;}");
sb.append("window.MYOBJECT.processHTML(str);");
sb.append("return true;");
sb.append("};");
view.loadUrl("javascript:" + sb.toString());
}
});
webview1.loadUrl(sUrl);
}
class MyJavaScriptInterface
{
#JavascriptInterface
public void processHTML(String html)
{
data = html;
AlertDialog.Builder builder = new AlertDialog.Builder(Main2.this);
builder.setTitle("AlertDialog from app")
.setMessage(html)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setCancelable(false).show();
}
}
}
any help is appreciated.
I am really happy to giving answer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
final WebView browser = (WebView)findViewById(R.id.myWebview);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
// This call inject JavaScript into the page which just finished loading.
browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('textarea')[0].innerHTML);");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementById('chapter-description').value);");
}
});
/* load a web page */
browser.loadUrl(sUrl);
}
Enable javascript
Add your own javascript
Register your own webviewClient, overriding the onPageFinished to insert a bit of javascript
In the javascript, acquire the element.innerText of the tag, and pass it to your javascript interface.
I have created an application that uses WebView to view my website, the application is running smoothly and without any bugs, I even uploaded it on the Google Play store. The only thing is that I have youtube video links in my website and they don't work on my application. They appear on the screen and the user can easily click on them, but after clicking the video loading sign appear and stays rotating without any benefit. I know that mobile web browser have no flash player plug-in and I have looked at all the similar questions on StakcOverFlow. So what I would like to do is to make my application call the YouTube app from the android system and let it complete the mission by playing my website youtube videos. I read about Intent methode, but couldn't find anything helpful. Any Suggestions guys?
Thank you svenoaks. Now I have a small error in the code:
package com.parse;
import android.net.Uri;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class ParserActivity extends Activity {
private WebView myWebView;
#SuppressLint({"setJavaScriptEnabled"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parser);
myWebView =(WebView) findViewById(R.id.webview);
myWebView.loadUrl("https://parse.com/apps/aramco-app1/push_notifications /new");
myWebView.setWebViewClient(new HelloWebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
myWebView.setScrollbarFadingEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setSupportZoom(true);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{webview.loadUrl (url);
return true;
{
// YouTube video link
if (url.startsWith("vnd.youtube:"))
{
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse
(String.format("http://www.youtube.com/v/%s", url.substring("vnd.youtube:".length())))));
return true;
}
return false;
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
Toast.makeText(WebActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
{
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean setIsZoomInEnabled;
}
class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
private void show()
{
// TODO: Implement this method
}
}
onReceive method has an Error.
This worked for me pre KitKat, but now I can't even see the videos in the webview to click on, because of no plug-in. Hopefully it will work for you:
webView.setWebViewClient(new 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
(String.format("http://www.youtube.com/v/%s", url.substring("vnd.youtube:".length())))));
return true;
}
return false;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
Toast.makeText(WebActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
I developed a small android webview app to access an internal (local network) PHP based site.
Here is my code:
package com.CheckInventory;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
#SuppressWarnings("unused")
public class CheckInventoryActivity extends Activity {
WebView webview;
String username;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
WebView webView = (WebView) findViewById(R.id.webview);
webView.setBackgroundColor(0);
webView.setBackgroundResource(R.drawable.myimage);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
WebSettings webSettings = webview.getSettings();
webSettings.setLoadWithOverviewMode(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setDatabasePath("/data/data/"+this.getPackageName()+"/databases/");
webSettings.setDomStorageEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("http://192.168.0.124/android");
webview.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown (int keyCode, KeyEvent event) {
if((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()){
//webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
The site has authentication, but I would like to add some authentication between the app and the site (How do I do this? pass a parameter maybe when the url is invoked), secondly and more importantly, where specifically do I put the onReceivedError so the user never sees the url or the page down if they walk away from the building or loose connection.
public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
Toast.makeText(Webform.this, "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
}
I saw this explanation in Detecting Webview Error and Show Message but I do not know where to implement it.
Thank you in advance
You need to create class which extends WebViewClient and implements method OnReceivedError
like this
class myWebClient extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(Webform.this, "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
and then you need to set new WebViewClient to your WebView
web = (WebView) findViewById(R.id.webview);
web.setWebViewClient(new myWebClient());
Hope this helps
You can add onReceivedError in Your HelloWebViewClient class and handle what you want to handle when you get error.
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
//Your code to do
Toast.makeText(getActivity(), "Your Internet Connection May not be active Or " + error , Toast.LENGTH_LONG).show();
}
}
I'm sorry for this as I am very Green at this Android Development, and I maybe beating a dead horse here-
A software tjat we use has a mobile version, but it's a mobile website, I am trying to build this into a standalone web-app using webview.
The app will get me to the login screen, but when I attempt to login the the pop-up showing its logging in, and in my webview, it is sticking there. It doesn't move past this point.
In the default browser it works fine.
Can you please assist me in what I need to do to get pass this in the most simple terms? ;-) Thank you!
package com.giantflyingsaucer;
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
{
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 boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://URL.USED.FOR/WEBAPP");
}
}
This was resolved by using
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
perhaps your login is trying to make use of some web plugin. Try adding one or both of these:
mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
mWebView.getSettings().setPluginsEnabled(true);