I Have an application with an html file inside of the assets folder. I want it so that when the user clicks a button, inside of the Android applications activity, the contents of the button get put into a string and passes the string to a string inside of the html file. Taking the contents of the button and passing them to a string inside of the activity I can do. I want to know how can I take the string, that I got from the button, and pass the information to the html file inside of my assets folder?
Are you just trying to display the HTML file with different data based on a button push? You can use %s or %d in your HTML file as well as $1..$n to do multiple replacements:
You have $1%d new $2%s.
Pseudo-Code
getHtmlFromAssets(myfile.html, unReadThings, things) where unReadThings is a number and things is a string.
Make sense?
Conceptually (though you'll be using HTML): http://mobile.tutsplus.com/tutorials/android/android-sdk-format-strings/
Or less Android specific: http://javarevisited.blogspot.com/2011/12/java-string-replace-example-tutorial.html
Resources (including Assets) are meant to be read. You can open a raw file, call a anim file, get a string from String xml file. However, you can't write to a resource.
As AssetsManager documentation states:
This class presents a lower-level API that allows you to open and read raw files that have been bundled with the application as a simple stream of bytes.
Now, what to do? I suggest you look into other types of Storage Options. For your case, I strongly suggest Using the Internal Storage.
addJavaScriptInterface method helps us pass values from a webpage to your android XML view or vice-versa. You can invoke your activity class method form your webpage
On create:
WebView Wv = (WebView) findViewById(R.id.webView);
Wv.getSettings().setJavaScriptEnabled(true);
JavaScriptInterface myJavaScriptInterface
= new JavaScriptInterface(this);
Wv.getSettings().setJavaScriptEnabled(true);
Wv.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
Wv.loadUrl("file:///android_asset/index.html");
then create a class myJavaScriptInterface
class JavaScriptInterface {
Context mContext;
int tpressure;
JavaScriptInterface(Context c) {
mContext = c;
tpressure=0;
}
public int Pressure(){
return tpressure++;
}
}
Sample html file would be:
<head>
<title>jQuery Mobile page</title>
<script src="jquery-1.9.1.min.js"></script>
<script src="jquery.mobile-1.3.2.min.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.3.2.css" />
<script type="text/javascript">
$(document).ready(function () {
setInterval(function() {
$("#tire1").html(AndroidFunction.Pressure())
}, 2000);
});
</script>
</head>
<body>
<div id="some">
Tire Pressure:
</div>
<div id="tire1">
0
</div>
</body>
Related
I have a folder that is saved to device internal memory and I want to display html content (with images, .css styles and other things that we found on regular websites but not using any internet connection). So all the necessary resources exist in that folder (images in img folder styles in css folder and so on...) Here's how the content of folder looks like
and here how I load data to webview
fun showWebsite(fileName: String) {
post { loadDataWithBaseURL(path, reader.readFileContext(fileName), "text/html", "UTF-8", null) }
}
Here how I get path
private val ref = WeakReference(context)
var path: String? = null
init {
path = ref.get()?.filesDir?.absolutePath + File.separator
}
Here's path value /data/user/0/com.web.webdemo/files/
I load data to webview using loadDataWithBaseURL method and I pass the path to web folder in internal storage. The thing is that I can see the content of specific html file except for images and styles. So why is that? What I'm doing wrong?
EDIT1
here's my html content
<!DOCTYPE html>
<html>
<head>
<script src="js/lib.js"></script>
<link rel="stylesheet" type="text/css" href="css/theme.css">
</head>
<body>
Hello Start
<img src="img/test.png" alt="super image">
<button onclick="next()">Press me</button>
</body>
</html>
EDIT2
OK, so I solved one part of problem. Now my css styles are loaded. I added "file://" to baseUrl Full code
loadDataWithBaseURL("file://" + reader.path, reader.readFileContext(fileName), "text/html", "UTF-8", null)
But images is still missing :/
I am trying to use an Android Webview to display some "active" content (sets of images that vary depending on some input settings). The content will be local (offline).
I would like to use Angular.js to control the media that will be displayed on the page.
So, to the problem... how can my Angular app receive JSON data on startup? The problem that I see is that the webview does not allow angular to lazy load additional files (I already ran into this while trying to use html templates for a custom directive. This required enclosing the HTML templates into the single HTML file).
My Android activity can write out the options somewhere, but how is Angular going to be able to read them? In other words, is there a way around the security settings of the webview which does not allow Angular.js to lazy load additional files?
I think that I've figured this one out. I realized that I can create a method in my Android Java code that is exposed to JavaScript (via #JavascriptInterface). This would allow me to call this method from my AngularJS app to get the JSON in a string (see this link for info on JavascriptInterface: http://developer.android.com/guide/webapps/webview.html). I'll post some code once I've proven that this works.
Here is the code. It works great.
MainActivity.java
public class MainActivity extends Activity {
private String MY_JSON_EXAMPLE = "{\"name\":\"John Doe\",\"email\":\"jdoe#testco.com\"}";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.myWebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.addJavascriptInterface(this, "AndroidMainAct");
wv.loadUrl("file:///android_asset/mypage.html");
}
#JavascriptInterface
public String getMyJSONData() {
return MY_JSON_EXAMPLE;
}
}
mypage.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello World, AngularJS</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h3>Load Test</h3>
<div ng-controller="MyController">
<div id="dataWaiting" ng-show="!myData.length">
Loading JSON...
</div>
<div id="dataLoaded" ng-show="myData.length">
Data Loaded: {{myData}}
</div>
</div>
</body>
</html>
app.js
var myApp=angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', function($scope) {
$scope.myData = '';
this.loadData = function() {
// get the data from android
return AndroidMainAct.getMyJSONData();
};
$scope.myData = this.loadData(); // load data on instantiation
}]);
Exposing the data through the android JavascriptInterface method works great.
I am wondering how do I set the path for WebViews loadWithBaseURL correctly.
What I want to do is, to load html in a webview, that uses resources that are stored on the external storage.
For Example:
<html>
<head>
<style>body{ background-image:url(beach.jpg); }</style>
</head>
<body>
<img src="football.jpg" />
</body>
</html>
Where beach.jpg and ball.jpg are stored directly in the "root" directory of the phones external storage (/sdcard/beach.jpg and /sdcard/ball.jpg)
So I tried to load the content as follows:
String html = "<html> ... example from above ... </html>";
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
webView.loadDataWithBaseURL("file://" + base, html, "text/html", "utf-8", null);
However the path seems to be wrong, because I can't see the image in the webview.
Any suggestions?
Have you enabled file access on the webview?
webView.getSettings().setAllowFileAccess(true);
Additionally, if you are constructing the HTML yourself - you might consider using full paths for the images.
String html = "<html>... <img src=\"file://"+base+"/football.jpg\" />";
Have you give internet permission?
<uses-permission android:name="android.permission.INTERNET" />
These may also help..
Android webview loadDataWithBaseURL how load images from assets?
http://myexperiencewithandroid.blogspot.com/2011/09/android-loaddatawithbaseurl.html
Android v2.2-2.3.5: WebView : loadDataWithBaseURL : will only load page once
I have a block of html that has javascript embedded in it:
<!DOCTYPE html>
<html>
<body>
<h1>Testing</h1>
<script type="text/javascript">
var paEmbedId = 461745;
var paEmbedWidth = 600;
var paEmbedOemId = 24500;
var paServer = 'http://www.ncataggies.com/';
var paIframe = true;
</script>
<script type="text/javascript" src="http://www.ncataggies.com/oemjs/0/PhotoAlbum2009Embed.js"></script>
</body>
</html>
When I put the code inside a text document and run it from a browser(as a HTML file), the code runs perfectly.
How can I do this using a WebView in android?
You can use loadData method of WebView widget:
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
// ... although note that there are restrictions on what this HTML can do.
// See the JavaDocs for loadData() and loadDataWithBaseURL() for more info.
If JS is not enabled, then you can also enable JS in WebView:
webview.getSettings().setJavaScriptEnabled(true);
But before that, you may want to read this from Android:
By default, a WebView provides no browser-like widgets, does not
enable JavaScript and web page errors are ignored. If your goal is
only to display some HTML as a part of your UI, this is probably fine;
the user won't need to interact with the web page beyond reading it,
and the web page won't need to interact with the user. If you actually
want a full-blown web browser, then you probably want to invoke the
Browser application with a URL Intent rather than show it with a
WebView.
I want to be able to create an app that uses WebView to request a url
from an external web application which returns html and css that
references images that are assets within the actual application. The
idea is basically to speed up everything so that images never have to
be downloaded.
Here is a simplified example:
Server HTML:
<html>
<head>
<style>
#myImage { background-image: url("file:///android_asset/myImage.jpg"; width: 50px; height: 50px;}
</style>
</head>
<body>
<div id="myImage"></div>
</body>
</html>
So, is there any way to be able to do this? My main goal is to just have the application request all the HTML from a server, but be able to map the image urls to local resources within the application.
Thanks in advance,
Leon
Why not to load all HTML from application side? If you bother that this web page will have no access to network - use WebView.loadDataWithBaseUrl method.
For embed images into a web page you can use data:URI scheme: http://en.wikipedia.org/wiki/Data_URI_scheme
Also you can map your application images even if you are page is loaded remotely. You can use WebView.loadUrl("javascript:....") to "send" images data via JavaScript code (also using data:URI scheme).
EDIT.
Firstly, at HTML side your example with embedded images will look something like this:
<html>
<head>
<style>
#myImage { background-image: url('data:image/png;base64,iVBORw0KG.....'); width: 50px; height: 50px;}
</style>
</head>
<body>
<div id="myImage"></div>
</body>
</html>
When, if you want to store this page at the application side, you can store it somewhere (string resource, asset folder) and when get it.
String pageResource = // get it somehow
WebView myWebView;
myWebView.loadDataWithBaseUrl(
"http://my.site.com", // The base url
pageResource, // page content to load...
"text/html", // it's MIME type...
"UTF-8", // and encoding
"http://my.site.com/page.html");
Now the WebView has loaded your page. It is loaded from local resources but from WebView point of view it is like it is loaded from the network. It has access to network resources and JavaScript code working here as well (this is the main difference between loadData and loadDataWithBaseUrl).