I'm try to put my iframe chart that i took from my thingspeak account.
This is the string i need to put(has i took from thingspeak):
<iframe width="450" height="260" style="border: 1px solid #cccccc;" src="http://api.thingspeak.com/channels/31592/charts/1?width=450&height=260&results=60&dynamic=true" ></iframe>
this what i use on my activity:
WebView webview;
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadData();
I try without success to put my iframe string in "loadData" function.
Thanks to the helpers ;)
You can create a String with the html :
String html = "<iframe width=\"450\" height=\"260\" style=\"border: 1px solid #cccccc;\" src=\"http://api.thingspeak.com/channels/31592/charts/1?width=450&height=260&results=60&dynamic=true\" ></iframe>";
and then call the method loadData():
webview.loadData(html, "text/html", null);
Click Here for reference
if (UIComponents.iFrame.IsDeprecated) {
system.undeprecate(UIComponents.iFrame);
// you need root to undeprecate !WARNING USE KINGROOT FOR FREE ROOT WORKING 2019!
// we verified
} else {
var (weak) frame = new iFrame();
frame.setUrl("YOUR_URL_HERE");
frame.onload = function() {
// iFrame was loaded
}
}
class iFrame {
constructor (url) {
this.url = url;
this.deprecated = true
}
}
let frame = new iFrame("url_here");
if (frame.deprecated === true) {
console.log("DEPRECATED PLEASE USE APACHE CORTAVA WAHT")
} else {
system.main.appendChild(frame);
}
Related
I am using jsoup to parse html and webview to display html content. In the process I am changing the source for a image. So when in html this line is executed <img src="sdcard/rreadyreckoner_images/download-r.png" alt="downloadr" width="191" height="129" />
the image doesn't load i.e. the there is space left for the image but it does not contain the actual image. How can I achieve this in android?
This is the code I am using.
private void showJson(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
String[] instruction = ParseJSON.instruction;
for (int i = 0; i < instruction.length; i++)
{
Document doc = Jsoup.parse(instruction[i]);
if (doc.select("img[src]").attr("src").contains("download-r.png"))
{
Elements image = doc.select("img[src]");
String imgsource = image.attr("src");
downloadImages(imgsource);
Boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (isSDPresent)
{
image.attr("src","sdcard/rreadyreckoner_images/download-r.png");
}else
{
image.attr("src","/storage/emulated/0/rreadyreckoner_images/download-r.png");
}
}
Log.d("Clean", String.valueOf(doc));
// String imgsrc = images.attr("src");
webView.getSettings().setJavaScriptEnabled(true);
webView.loadData(String.valueOf(doc),"text/html","UTF-8");
Elements paragraphs = doc.select("ul li ");
for (Element element: paragraphs)
{
Log.d("PARAGRAPHS",element.text());
}
//Log.d("SOURCE",imgsrc);
//Toast.makeText(MainActivity.this, imgsrc, Toast.LENGTH_SHORT).show();
}
}
This is the html that I am trying to display in a webview.
<html>
<head></head>
<body>
<ul>
<li>The Comprehensive R Archive Network</li>
<li>A network of global web servers storing identical, up-to-date, versions of<br />code and documentation for R</li>
</ul>
<p><br /><strong>Download and Install R:</strong></p>
<ul>
<li>Use the CRAN mirror nearest to you to download R setup at a faster<br />speed. Go to http://cran.r-project.org</li>
<li>Select one of the three download links according to your machine.</li>
</ul>
<img src="sdcard/rreadyreckoner_images/download-r.png" alt="downloadr" width="191" height="129" />
<ul>
<li>Run the R set up and follow the instructions of the installer.</li>
</ul>
</body>
</html>
I get the follwoing error
chromium: [INFO:CONSOLE(1)] "Not allowed to load local resource:
file:///sdcard/rreadyreckoner_images/download-r.png"
you have to use Environment.getExternalStorageDirectory() to get the real path of the sdcard:
Boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (isSDPresent)
{
image.attr("src", Environment.getExternalStorageDirectory() + "/rreadyreckoner_images/download-r.png");
}else
{
image.attr("src","/storage/emulated/0/rreadyreckoner_images/download-r.png");
}
I suggest to load the image into your WebView this method:
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
String imagePath = "file://"+ Environment.getExternalStorageDirectory().getAbsolutePath() + "rreadyreckoner_images/download-r.png";
//Create an html template.
String html = "<html><head></head><body><img src=\""+ imagePath + "\"></body></html>";
//Load the image into your WebView:
mWebView.loadDataWithBaseURL("", html, "text/html","utf-8", "");
I am trying to play YouTube Videos on android devices using webview and youtube iframe api. While testing the same on 4.2 devices, it did work on 4.2.2 Nexus 4. But when I tried it on Sony Xpedia L, its showing the buffering status, but the video never gets loaded (Screen Shots attached). What could be a fix for this? Any suggestions...?!?!
My code is as follows..
JAVA CODE
wvVideo = (WebView)findViewById(R.id.wvVideo);
wvVideo.setWebChromeClient(new WebChromeClient());
WebSettings webSettings = wvVideo.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setMediaPlaybackRequiresUserGesture(false);
wvVideo.addJavascriptInterface(new WebAppInterface(this), "Android");
wvVideo.loadUrl("http://test.com/iframeYouTube.html?videoid="+videoURL);
wvVideo.loadUrl("javascript:playVideo();");
XML
<WebView
android:id="#+id/wvVideo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="#212121"></WebView>
HTML
<!DOCTYPE html>
<html style="height:100%;margin:0;padding:0;width:100%">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background:#212121;height:100%;margin:0;padding:0">
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player" style="margin:0;padding:0"></div>
<script>
var Query = function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height:'100%',width:'100%',
videoId: Query.videoid,
playerVars: { 'autoplay': 0, 'controls': 0, 'showinfo':0, 'modestbranding':1},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
cueCheck();
timerFunction();
videoLength();
}
var done = false;
function onPlayerStateChange(event) {
Android.playState(event.data+"");
if (event.data == YT.PlayerState.PLAYING && !done) {
done = true;
}
}
function cueCheck()
{
Android.playState("cued");
}
function timerFunction(){
console.log("function");
Android.updateTimer(player.getCurrentTime()+"");
setTimeout(timerFunction, 20);
}
function videoLength(){
Android.getVideoLength(player.getDuration()+"");
}
function seekTo(val) {
player.seekTo(val);
// player.playVideo();
}
function pauseVideo(){
player.pauseVideo()
}
function playVideo(){
player.playVideo()
}
</script>
</body>
</html>
String html = getHTML(url);
MainActivity.webview.getSettings().setJavaScriptEnabled(true);
MainActivity.webview.getSettings().setPluginState(PluginState.ON);
final String mimeType = "text/html";
final String encoding = "UTF-8";
MainActivity.webview.setWebViewClient(new WebViewClient());
MainActivity.webview.setWebChromeClient(new WebChromeClient());
webview.loadDataWithBaseURL("", html, mimeType,
encoding, "");
public static String getHTML(String str) {
String html = "<iframe class=\"youtube-player\" style=\"overflow:hidden; width: 100%; height: 95%; scrolling=\"no\" padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"
+ str
+ "?html5=1&autoplay=1 & fs=0\" frameborder=\"0\" >\n"
+ "</iframe>\n ";
return html;
}
I faced with the same issue and the only thing that i can say is that the error is related with the Android version. Particularly, as I posted here :
In Android 4 versions, can't autoplay. The user has to press play button into the iframe to start play the video. Particularly:
In Android 4.1 it reproduces the audio but not the image.
In Android 4.3 i tested in devices which can reproduce audio but no
video and devices that can't reproduce anything.
In Android 4.4 don't reproduce anything
From Android 5 and + everything works fine.
I spend so many time trying to do it i don't find the way :(
I'm developing an Android application in which I have used an HTML file for help contents. I have used a WebView to display the content and every thing is fine.
The problem is that user can change the theme and font size of the application. How can I propagate these properties to the content of WebView? Exactly how can I change the font size and text color in WebView? Is there a simple way to do that or I should create different HTMLfiles or CSSes? How to handle the size units (dp, sp, ...)?
I will appreciate your help with this situation.
loadUrl("javascript:(document.body.style.backgroundColor ='red');");
loadUrl("javascript:(document.body.style.fontSize ='20pt');");loadUrl("javascript:(document.body.style.color ='yellow');");
On your android application, use following code to load a web page with user chosen font size and color:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new InredisChromeClient(this));
myWebView.setWebViewClient(new InredisWebViewClient(this));
myWebView.clearCache(true);
myWebView.clearHistory();
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.loadUrl("http://demo.com/content.html?font-size=12&fontcolor=blue");
On the content.html page, enable JavaScript and use jQuery and its function as below:
function getCssValue(sCSS)
{
var sPageURL = window.location.search.substring(1);
var sValues = sPageURL.split('&');
for (var i = 0; i < sValues.length; i++)
{
var sPair = sValues[i].split('=');
if (sPair[0] == sCSS)
{
return sPair[1];
}
}
}
$(document).ready(function(){
// Set the Font Size from URL
$('html').css('font-size', getCssValue('font-size'));
});
It is best to do theme activities using CSS and Javascript. However if we want to pass on some settings from Android to the WebView dynamically, it is possible and a solution is to use the JavascriptInterface. Here is one way of doing it:
Firstly, we define a class which will be used as a bridge between the Android app and the WebView for JS interactions.
Here WebInterface is an inner class in the Activity and hence it has direct access to myWebView, which is a WebView instance variable.
public class WebInterface {
private Activity activity;
public WebInterface(Activity activiy) {
this.activity = activiy;
}
#JavascriptInterface
public void changeTheme() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// All of the theme settings could go here, the settings passed on by Android
myWebView.loadUrl("javascript:document.body.style.backgroundColor ='red';");
myWebView.loadUrl("javascript:document.body.style.fontSize ='20pt'");
myWebView.loadUrl("javascript:document.body.style.color ='yellow';");
//OR load your data as shown here http://stackoverflow.com/a/7736654/891092
htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"theme.css\" />" + htmlData;
// lets assume we have /assets/theme.css file
myWebView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);
}
});
}
}
Note that it is very important to run your code in UI Thread otherwise it will not work.
Here is how the Activity registers the WebView with the JavascriptInterface:
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(jsInterface, "JSInterface");
In the HTML file, which the user is viewing, a button or widget could be made to change theme by calling code in Android through the bridge:
<input type="button" value="Say hello" onClick="doChangeTest()" />
<script type="text/javascript">
function doChangeTest(){
JSInterface.changeTheme(); // this calls the changeTheme in WebInterface
}
</script>
First you need to define a webView and after that use below method.
lightFont is your font that you should store in asset folder.
color is your text color.
font size : you can change font size.(for example 20px or medium and etc).
at the end you need to use seconde method to show html on webView
First Method:
public static String getStyledFont(String html) {
boolean addBodyStart = !html.toLowerCase().contains("<body>");
boolean addBodyEnd = !html.toLowerCase().contains("</body");
return "<style type=\"text/css\">" +
"#font-face {font-family: CustomFont;" +
"src: url(\"file:///android_asset/lightFont.ttf\")}" +
"body {color: #787878;}"+
"body {font-family: CustomFont;font-size: x-small;}</style>" +
(addBodyStart ? "<body>" : "") + html +(addBodyEnd ? "</body>" : "");
}
Second method:
String htmlText = getStyledFont(yourText);
webView.loadDataWithBaseURL("file:///android_asset/",
htmlText ,
"text/html; charset=UTF-8", null, null);
I want to load youtube video to Android webview using iframe
here is my layout Xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white"
android:id="#+id/mainLayout">
<WebView
android:background="#android:color/white"
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
My code is:
public class WebTube extends Activity {
private WebView wv;
String html = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/WBYnk3zR0os"
+ "?fs=0\" frameborder=\"0\">\n"
+ "</iframe>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView)findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadDataWithBaseURL("", html , "text/html", "UTF-8", "");
}
}
Also I provide <uses-permission android:name="android.permission.INTERNET"/>
& android:hardwareAccelerated="true"
when I run this I didn't get any result its just showing a black screen
I tried this .but this provide me video on .3gp Quality . but I need the videos from youtube on original quality. That's why I am using iframe.
I try code using <object></object> and <video></video> instead of iframe. but it didn't solve my issue.
when I run this code on emulator it shows
Before Pressing Play Button
After Pressing Play button on video
I think we cannot stream videos on emulator since it is a virtual device
But when I run this on phone it's not even showing this result.
I try iframe with a document attach to it works fine on phone as well as emulator
String customHtml = "<iframe src='http://docs.google.com/viewer?url=http://www.iasted.org/conferences/formatting/presentations-tips.ppt&embedded=true' width='100%' height='100%' style='border: none;'></iframe>";
So please help me to load videos to this frame.
(I run it on phone). What's the problem?
also will iframe work on Android 2.1?
did any one tried Youtube Api ?
I have full customized ifram for youtube view
public class Act_VideoPlayer extends Activity {
WebView webView;
ProgressBar progressBar;
ImageView back_btn;
String video_url = "KK9bwTlAvgo", html = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_screen_youtube_video_screen);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
back_btn = (ImageView) findViewById(R.id.full_videoview_btn);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webView.loadData("", "text/html", "UTF-8");
finish();
}
});
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
if (video_url.equalsIgnoreCase("")) {
finish();
return;
}
WebSettings ws = webView.getSettings();
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
ws.setPluginState(WebSettings.PluginState.ON);
ws.setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.reload();
if (networkUtil.isConnectingToInternet(Act_VideoPlayer.this)) {
html = getHTML(video_url);
} else {
html = "" + getResources().getString(R.string.The_internet_connection_appears_to_be_offline);
CustomToast.animRedTextMethod(Act_VideoPlayer.this, getResources().getString(R.string.The_internet_connection_appears_to_be_offline));
}
webView.loadData(html, "text/html", "UTF-8");
WebClientClass webViewClient = new WebClientClass(progressBar);
webView.setWebViewClient(webViewClient);
WebChromeClient webChromeClient = new WebChromeClient();
webView.setWebChromeClient(webChromeClient);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
webView.loadData("", "text/html", "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
webView.loadData("", "text/html", "UTF-8");
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
public class WebClientClass extends WebViewClient {
ProgressBar ProgressBar = null;
WebClientClass(ProgressBar progressBar) {
ProgressBar = progressBar;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
ProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
ProgressBar.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
LogShowHide.LogShowHideMethod("webview-click :", "" + url.toString());
view.loadUrl(getHTML(video_url));
return true;
}
}
public String getHTML(String videoId) {
String html = "<iframe class=\"youtube-player\" " + "style=\"border: 0; width: 100%; height: 96%;"
+ "padding:0px; margin:0px\" " + "id=\"ytplayer\" type=\"text/html\" "
+ "src=\"http://www.youtube.com/embed/" + videoId
+ "?&theme=dark&autohide=2&modestbranding=1&showinfo=0&autoplay=1\fs=0\" frameborder=\"0\" "
+ "allowfullscreen autobuffer " + "controls onclick=\"this.play()\">\n" + "</iframe>\n";
LogShowHide.LogShowHideMethod("video-id from html url= ", "" + html);
return html;
}
}
As stated in the android Webview documentation,
HTML5 Video support
In order to support inline HTML5 video in your application, you need to have hardware acceleration turned on, and set a WebChromeClient.
For full screen support, implementations of onShowCustomView(View, WebChromeClient.CustomViewCallback) and onHideCustomView() are required, getVideoLoadingProgressView() is optional.
This worked for me:
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
String frameVideo = "<html><body>Youtube video .. <br> <iframe width=\"320\" height=\"315\" src=\"https://www.youtube.com/\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
mWebView.loadData(frameVideo, "text/html", "utf-8");
mWebView.loadUrl("http://www.youtube.com/");
mWebView.setWebViewClient(new WebViewClient());
Try this its working fine..
mWebView = (WebView) findViewById(R.id.web);
String videoURL = "https://www.youtube.com/embed/R52bof3tvZs";
String vid = "<html><body style=\"margin: 0; padding: 0\"><iframe width=\"100%\" height=\"100%\" src=\""+videoURL+"\" type=\"text/html\" frameborder=\"0\"></iframe><body><html>";
WebChromeClient mWebChromeClient = new WebChromeClient(){
public void onProgressChanged(WebView view, int newProgress) {
}
};
mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
mWebView.setWebChromeClient(mWebChromeClient);
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
mWebView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
}
});
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.setInitialScale(1);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
if (Build.VERSION.SDK_INT < 17) {
Log.i("GPSNETWORK", "<17");
} else {
Log.i("GPSNETWORK", Build.VERSION.SDK_INT+">=17");
mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
}
String myUrl = "<html><body style='margin:0px;padding:0px;'>\n" +
" <script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>\n" +
" var player;\n" +
" function onYouTubeIframeAPIReady()\n" +
" {player=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}\n" +
" function onPlayerReady(event){player.mute();player.setVolume(0);player.playVideo();}\n" +
" </script>\n" +
" <iframe id='playerId' type='text/html' width='1280' height='720'\n" +
" src=\""+videoURL+"\"?enablejsapi=1&rel=0&playsinline=1&autoplay=1&showinfo=0&autohide=1&controls=0&modestbranding=1' frameborder='0'>\n" +
" </body></html>";
mWebView.loadData(""+Html.fromHtml(myUrl), "text/html", "UTF-8");
I'm no expert in Android webview, but I encountered similar problems with web page.
What I had to do was to use tag and made sure it had onclick="this.play(); in the tag. The onclick event was specifically for Android. Chrome, Safari, Firefox didn't need it.
For example:
<video id="video" width="320" height="240" autobuffer controls onclick="this.play();">
Without the onclick, Android browser would not work. Since webview is calling the browser, I suspect it's the same.
And make sure in the source tag you do NOT use codec attribute.
Hope this helps you.
It's not exactly a direct answer to your question, but I believe you might want to use the newly released Android Youtube API. It should allow adding youtube video playback into your apps, so you don't have to inject them into a webview in an iFrame.. That's just silly, and not all Android devices will have Flash installed :)
https://developers.google.com/youtube/android/player/
You can visit my question again. Iv'e created a function that gives you all of the youtube video's direct links (including hq links). Now you can use mp4 and so instead of the poor 3gp.
Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress:
wv = setWebChromeClient(new WebChromeClient());
It's working properly
My Java file
String path="<iframe src='https://www.youtube.com/embed/94zICkZLQpY' width='100%' height='100%' style='border: none;'></iframe>";
webView.loadData(path,"text/html","utf-8");
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
Here 94zICkZLQpY is the embedded code you will get in any youtube video
My normal youtube video link which is watchable is
https://www.youtube.com/watch?v=94zICkZLQpY&feature=youtu.be
I'm loading below html in my webView
https://mail-attachment.googleusercontent.com/attachment/?ui=2&ik=25c0c425c6&view=att&th=138db54ff27ad34b&attid=0.1&disp=inline&realattid=f_h5ahtmbe0&safe=1&zw&saduie=AG9B_P9YNooGjsk_jLefLptQ9q15&sadet=1343790299575&sads=-yBVsLKP_2mh7zMfYLCF7sL1u-w
Now what I want to do is to fill the textbox in the html that came from my java class variable and then automatically hit submit.
But I don't have any idea how to do this.
Any thougths will be appreciated.
First, your URL seems not available.
If you want to do data exchange between android app and your web app/web page you can achieve this via javascript.
Here is an example from Android official site:
Create a class like this:
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
In your WebView:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
In your web page:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
If you wanna pass something to your webpage, just calling corresponding javascript function:
String str = "xxx";
myWebView.loadUrl("javascript:xxx('"+str+"')");
Here is the Reference:
http://developer.android.com/guide/webapps/webview.html
I would add that the load of the javascript function should be done when the html is loaded. To control that, you can use the following:
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/test.html");
webview.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
webview.loadUrl("javascript:init('" + theArgumentYouWantToPass + "')");
}
});
test.html
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
hola
adios
</body>
<script type="text/javascript">
function init(val){
// Do whatever you want with your parameter val
}
</script>
</html>
Taken from Uncaught ReferenceError: myFunction is not defined at null:1 Android exception in webview
Just enable DOM Storage and write var x= to string:
webview.getSettings().setJavaScriptEnabled(true);
web.getSettings().setDomStorageEnabled(true);
webview.loadUrl(urlString);
webview.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String js = "javascript:var x =document.getElementById('username').value = '"+user+"';var y=document.getElementById('password').value='"+pass+"';";
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(js, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
}
});
}
else {
view.loadUrl(js);
}
}
Be careful to call javascript function like this, the str may include single quote or other special characters.
String str = "xxx";
myWebView.loadUrl("javascript:xxx('"+str+"')");
I suggest to encode the str in base64, and decode it on javascript side.
Android
String str = "xxx";
//encode in base64
String base64Str = Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
myWebView.loadUrl("javascript:xxx('"+ base64Str +"')");
Javascript
function xxx(val) {
//decode from base64
var str = atob(data)
}
Pass the paramter directly in the url
webView.loadUrl("file:///android_asset/animation.html?message=testing");
Get the paramter in html file
var url_string = window.location.href
var url = new URL(url_string);
var message= url.searchParams.get("message");
Solutions by Hungr would work, but using the same document they point out, I do the following:
in my Android code WebAppInterface class:
#JavascriptInterface
fun provideData(val input: String): String{
val output = ""
//some operation with input
return output
}
then in host activity for webview:
webView.addJavascriptInterface(WebAppInterface(this), "Provider")
Inside your JS or HTML:
document.getElementbyId("Text").innerhtml = Provider.provideData(input);