android get data from activity and display in html - android

I wanted to put variable from my activity and display it in html. Below is how I insert the variable into webview but I'm not sure how am I suppose to get the data from html and display it in "textview" form?
EDIT
Java
webView = (WebView)findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDatabasePath("/data/data/com.example.hybrid/hybrid_user");
webView.loadUrl("file:///android_asset/www/index.html");
webView.loadUrl("javascript:callFromActivity(\""+userid+"\")");
html
<body>
<form>
<fieldset>
<legend>Hybrid Application</legend>
<p>
<label>UserName: </label>
</p>
<p id="mytext">Hello!</p>
<p>
<label>Mobile Number :</label>
<input type = "text"
id = "mobileNum" />
</p>
<button type="button"
onclick="updateRecord()">Submit</button>
<div id="output"></div>
</fieldset>
</form>
<script>
function errorHandler(transaction, error){
alert('Error:'+error.message+' (Code '+error.code+')');
return true;
}
window.onerror = errorHandler;
var shortName = 'hybrid_user';
var version = '1.0';
var displayName = 'Hybrid Database';
var maxSize = 65536;
var db = openDatabase(shortName, version, displayName, maxSize);
function updateRecord(id, textE1){
database.transaction(function(tx){
tx.executeSql("UPDATE hybrid_user SET mobile = ? WHERE userid = ?", [textE1.innerHTML, id], null, onError);
})
}
function callFromActivity(msg){
document.getElementById("mytext").innerHTML = msg;
}
</script>
I'm new to html and I don't know what's wrong with my code, it did not display out the userid in the html page. Any comments and answers will be appreciated!
Edit update
webView.loadUrl("javascript:callFromActivity(\""+userid+"\")");
Apparently is the system didn't go through this line of code. Is there anyway go through this code?

try change innerHTML for value like this:
function callFromActivity(msg) {
document.getElementById("mytext").value = msg;
}

webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
webView.loadUrl("javascript:callFromActivity(\""+userid+"\")");
}
});
I solved my problem with this. When the page loads finished it will execute the above code and get the userid from the activity.

Related

Volley android remove div-container from fetched json

I use volley to fetch content from a wordpress blog via its api.
The content I receive looks like this:
<p>Blog content blabla</p>\n
<div id=\ "pressrelease-link-345\" class=\ "sh-link pressrelease-link sh-hide\">
<a href=\ "#\" onclick=\ "showhide_toggle('pressrelease', 345, 'Show full article', 'Hide article'); return false;\" aria-expanded=\ "false\">
<span id=\"pressrelease-toggle-345\">Show full article</span>
</a>
</div>
<div id=\ "pressrelease-content-345\" class=\ "sh-content pressrelease-content sh-hide\" style=\ "display: none;\">
</p>\n
<p>more content which is displayed after expanding the text in the browser</p>
I'd like to show the full text in my app, so the whole -part should be removed. Is there a nicer way to do this than just building the string for each article (id, here 345)? I though maybe I could just 'filter' out the div using volley, but didn't figure out how yet.
If i have understand, you want remove a div from a HTML page with a WebView ?
private void yourwebv (){
String url = "mysite.com";
final WebView webview = (WebView) findViewById(R.id.WEBVIEW_ID);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.setVisibility(View.INVISIBLE);
final ProgressBar ProgressBar = (ProgressBar) findViewById(R.id.ProgressBar);
ProgressBar.setVisibility(View.VISIBLE);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url){
String javaScript ="javascript:document.getElementsByClassName('YOURDIVCLASSNAME_REMOVE')[0]" +
".style.display='none';void(0);";
webview.loadUrl(javaScript);
Log.d("[WV]", " JS OK");
final ProgressBar ProgressBar = (ProgressBar) findViewById(R.id.ProgressBar);
ProgressBar.setVisibility(View.INVISIBLE);
webview.setVisibility(View.VISIBLE);
}
});
webview.loadUrl(url);
Log.d("[WV]", " WEBSITE + JS SCRIPT OK");
}

How to open a image stored locally using html code in android?

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", "");

put iframe on android app

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);
}

Passing data from java class to Web View html

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);

Changing HTML in a WebView programmatically

I'm loading an html asset page into a WebView using
webMain.loadUrl("file:///android_asset/record.html");
which works fine, but inside the html are a number of places where I'd like to use information from the app. For instance, the HTML may contain text that reads "[Custom]". Is there a way I can replace that word with information passed from the application?
This is an old and already accepted question, however I am sure that the problem can be solved in more elegant way by using javascript.
Keep the html file in your assets folder and surround the text which you want to replace into with div elements with unique id's.
<html>
<head> ... <head>
<body>
Static text
<div id="replace1">replace me</div>
<div id="replace2">replace me too</div>
More static text ...
</body>
</html>
Now create a javascript function which will replace the innerHtml of a div with an id:
function replace(id, newContent)
{
document.getElementById(id).innerHTML = newContent;
}
This function will be best placed directly in the html file, update the <head> section to look like this:
<head>
...
<script type="text/javascript">
function replace(id, newContent)
{
document.getElementById(id).innerHTML = newContent;
}
</script>
</head>
Now we need to call the javascript function from from the WebView Android api:
WebView helpView = (WebView)findViewById(R.id.helpView);
helpView.getSettings().setJavaScriptEnabled(true);
helpView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:replace('replace1', 'new content 1')");
view.loadUrl("javascript:replace('replace2', 'new content 2')");
}
});
helpView.loadUrl("file:///android_asset/help.html");
Using this you will avoid reading potentially large data into memory and running expensive operations on it unnecessarily.
This is worked for me.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Payment Demo</title>
</head>
<body>
<div>
<input type="text" id="uname " name="uname " value="">
<input type="text" id="pass" name="pass" value="">
</div>
</body>
</html>
This is java code.
WebView wb = (WebView) findViewById(R.id.webView1);
wb.loadUrl("file:///android_asset/web1.html");
wb.getSettings().setJavaScriptEnabled(true);
wb.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView web, String url) {
// TODO Auto-generated method stub
String uname = "email#mail.com";
String pass = "******";
web.loadUrl("javascript:(function(){document.getElementById('uname').value = '"+uname+"';})()");
web.loadUrl("javascript:(function(){document.getElementById('pass').value = '"+pass+"';})()");
}
});
Actually I do not understand why the file size of record.html will affect maintainence of the code. Read the html string (using Java reader class or what ever) from the html file in asset, use replaceAll function with Regex to replace all the [Custom] in the html file. How long the html is should not really affect how you maintain the code. It should rather be a performance problem, or the string is really really long that exceeds the java String limit.
some code I have used before :
InputStream is = getApplicationContext().getAssets().open("details/product_jsmodify.html");
Reader r = new InputStreamReader(is);
String details = Utils.readertoString(r);
details = details.replace("%product_name%",productName );
Utils is my class doing the conversion to string. I am not using Regex here as I am only replacing word for once. Then I load the string like Cata does. It is quite clean I suppose.
Yes you can do that by loading your page in a String and then load that string in your WebView.
Eg:
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
Taken from here
This one worked for me, with the html along with the text and images.
InputStream is = getAssets().open(html_name);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
str = str.replace("InitialTextToBeReplaced", "TextAfterReplacement");
//Now instead of webview.loadURL(""), I needed to do something like -
webView.loadDataWithBaseURL("file:///android_asset/", str, "text/html", "UTF-8",null);

Categories

Resources