My android WebView is showing a blank page when I try to load "file:///android_asset/index.html" and it perfectly loads other url like "http://twitter.com".
My activity
public class MainActivity extends ActionBarActivity {
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.loadUrl("file:///android_asset/index.html");
return true;
}
return false;
}
}
My index.html file :
<!DOCTYPE html>
<html>
<head>
<title>World Tour</title>
<!-- Sets initial viewport load and disables zooming -->
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<!-- Makes your prototype chrome-less once bookmarked to your phone's home screen -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="mobile-web-app-capable" content="yes">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/ratchet.css">
</head>
<body>
<header class="bar bar-footer">
<span class="icon icon-info pull-left" ></span>
<span class="icon icon-plus pull-right" ></span>
<h1 class="title">List of previous drive</h1>
</header>
<div class="content">
<div class="card">
<ul id="drives-list" class="table-view">
<li class="table-view-divider table-view-cell" ><p class="pull-left">Comments</p><p class="pull-right">Distance</p></li>
</ul>
</div>
</div>
<script type="text/javascript" src="js/main.js" ></script>
<script type="text/javascript" src="js/ratchet.js" ></script>
</body>
</html>
Thanks for helping !
get string content from your assests file using below code
public static String getStringFromAssets(String name, Context p_context)
{
try
{
InputStream is = p_context.getAssets().open(name);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String bufferString = new String(buffer);
return bufferString;
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
and load content using below code
String m_data = getStringFromAssets("index.html", this);
webView.loadDataWithBaseURL("file:///android_asset/", m_data, "text/html", "utf-8", null);
Hope it works for you !!
Checkout if there are any errors in javascript code associated with the html page. If so android studio doesn't point out errors in js file.
I fixed the errors in the js file and it worked.
Related
I'm using leafletjs in an Android Application to render local polygons (without CRS Information) in geojson format, without maptiles. Unfortunately, zooming and other touch movement are very laggy. My geojson file contains 3000 polygons. Is there any solution to this problem, the only thing I can find is a solution for markers.
This is how it looks:
Here is my code:
In onCreate:
public void loadMap(){
scanFiles();
checkStoragePermissions();
webview = (WebView) findViewById(R.id.myWebView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// chromium, enable hardware acceleration
webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
// older android version, disable hardware acceleration
webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
WebSettings webSettings =
webview.getSettings();
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setJavaScriptEnabled(true);
webview.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
webview.setWebChromeClient(
new WebChromeClient());
File leafletMap = new File(Environment.getExternalStorageDirectory(), "/LeafletMap/Map.html");
webview.loadUrl("file:///" + leafletMap.getAbsolutePath());
}
And my HTML-File:
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="file:///android_asset/leaflet/leaflet.css">
<script type="text/javascript" src="file:///android_asset/leaflet/leaflet.js"></script>
<style>
body {
padding: 0;
margin: 0;
}
html, body, #mapid {
height: 100%;
width: 100vw;
}
</style>
</head>
<body>
<div id="mapid"></div>
<script>
var mymap = L.map('mapid', {
crs: L.CRS.Simple
});
//Add local
var layer;
const xhr = new XMLHttpRequest();
xhr.open('GET', 'file:///android_asset/poly.json');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.onload = function () {
if (xhr.status !== 200) return
var blahlayer = L.geoJSON(xhr.response).getBounds();
mymap.fitBounds(blahlayer);
L.geoJSON(xhr.response).addTo(mymap);
};
xhr.send();
</script>
</body>
</html>
I develop a mobile app hybrid and i want to preview a pdf file that i get from web service.
The problem is the connection to the web service i do from java class and i want to preview the PDF in html.
I search in google and this i have until now and this not work for me.
Here my code:
Main Activity:
public class MainActivity extends AppCompatActivity {
private boolean wantExit;
private ActionsApp doActions;
private WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
doActions = new ActionsApp();
view = new WebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadDataWithBaseURL("file:///android_asset/js/index.js", "javascript", "application/javascript", "UTF-8", null);
view.loadUrl("file:///android_asset/html/index.html");
view.addJavascriptInterface(doActions, "action");
setContentView(view);
}
}
ActionsApp Class: this class used for action to the web service
public class ActionsApp {
public ActionsApp(){}
#JavascriptInterface
public String getFile(String idObjStr) {
ObjectVersion objectVer = null;
JSONObject jsonObject = null;
JSONParser jsonParser;
int idObj;
InputStream fileStream;
try {
fileStream = get from web service the file as Stream: application/png
jsonParser = new JSONParser();
jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(fileStream, "UTF-8"))
} catch (ParseException e) {
e.printStackTrace();
}
return jsonObject.toString();
}
}
index.js: when i click on button in another page(not the page that i wrote down here) the start this function in the js file.
function openFile(objectID)
{
$.mobile.changePage( "#pdfFile" );
var container = $('#previewContainer');
var pdfObject = $('#pdfObject').remove();
// The "format=pdf" parameter instructs the server to create a pdf preview
of the file and return it.
pdfObject.attr('type', 'application/pdf')
.attr('data', JSON.parse(window.action.getFile(objectID)));
container.append(pdfObject);
}
index.html: this page is to perview to pdf file that i get from the function in js file through ActionsApp class.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-
1.4.5.min.js"></script>
</head>
<body>
<div id="pdfFile" data-role="page" data-theme="a">
<div data-role="header" data-theme="b">
<h2>pdf</h2>
</div>
<div data-role="content" class="ui-content">
<div id="previewContainer">
<!-- Embed a pdf previewer using an <object> element. This element
is modified in JavaScript. -->
<object id="pdfObject" width="100%" height="100%">
</object>
</div>
</div>
</div>
<link rel="stylesheet" type="text/css"
href="file:///android_asset/css/index.css">
<script src="file:///android_asset/js/index.js"></script>
</body>
</html>
Any suggestions?
Thanks,
Tal
I am trying to call JavaScript from Android but $.post() is not working. I tried it in Postman and it is working.
o/p: output is not defined
MainActivity.java
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/newhtml.html");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:loadjs()");
}
});
newhtml.html
<!Doctye HTML>
<html>
<head>
<title></title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
function loadjs(){
console.log("called");
var json_config = {
name: "Donald Duck",
city: "Duckburg"
};
console.log("name "+json_config.name);
console.log("city "+json_config.city)
$.post("http://www.w3schools.com/jquery/demo_test_post.asp",json_config,function(data,status){
console.log("data "+data);
console.log("status "+status);
}).fail(function(response) {
console.log("output is "+response.responseText)
});
}
</script>
</head>
<Body>
<div id="print_host"></div>
</Body>
</html>
page loaded but javascript does not work!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poll);
Device.webViewShowPoll = (WebView) findViewById(R.id.webViewShowPoll);
Device.webViewShowPoll.getSettings().setJavaScriptEnabled(true);
//Device.webViewShowPoll.getSettings().setPluginsEnabled(true);
Device.webViewShowPoll.getSettings().setJavaScriptEnabled(true);
Device.webViewShowPoll.getSettings().setPluginState(PluginState.ON);
Device.webViewShowPoll.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
Device.webViewShowPoll.getSettings().setAllowFileAccess(true);
Device.webViewShowPoll.addJavascriptInterface(appconnector, "appConnectr");
try
{
Device.webViewShowPoll.loadDataWithBaseURL("file:///android_asset/",
Utility.convertStreamToString(getAssets().open("index.htm",
AssetManager.ACCESS_BUFFER)), "text/html", "utf-8","");
}
catch (IOException e)
{
Log.e(getString(R.string.app_name), e.getMessage());
}
}
}
AND index.htm is :
<html>
<head>
<script type="text/javascript">
alert('Hello world!');
</script>
</head>
<body>
<p>Hello World!</p>
<p>Hello World!</p>
</body>
</html>
You haven't set a WebChromeClient to handle JS alerts
Device.webViewShowPoll.setWebChromeClient(new WebChromeClient());
JavaScript alert not working in Android WebView
I have a PhoneGap application with iScroll4, its basically iScroll example with 2000 list items.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>iScroll demo: iOS Perfect Scrollbar</title>
<link rel="stylesheet" type="text/css" href="css/general.css">
<link rel="stylesheet" type="text/css" href="css/scrollbar.css">
<script src="js/jquery-1.7.1.js"></script>
<script src="js/iscroll.js"></script>
<script src="js/alldata.js"></script>
<script type="text/javascript">
var myScroll;
function loaded() {
myScroll = new iScroll('wrapper',
{
scrollbarClass: 'myScrollbar',
hideScrollbar:false,
/*onBeforeScrollStart: function (e) { return false; }*/
});
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', loaded, false);
</script>
<script>
function initList(){
for(var i=0; i<allData.length; i++){
var line = "<li style='color:#"+ allData[i].Color + ";'>" + allData[i].EventName + "</li>"
$("#thelist").append(line);
}
}
$(document).ready(function(){
initList();
initList();
initList();
initList();
//alert("Finished!");
});
</script>
</head>
<body>
<div id="header">iScroll</div>
<div id="wrapper">
<div id="scroller">
<ul id="thelist">
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>
Note: the variable allData is a JSON array with 500 objects.
EDITED:
It works fine on Motorola Atrix (2.3.3) and on Galaxy 3,
But it doesn't move on Galaxy 2 (4.2.2) and Galaxy3 after 1000 list items, strange Motorola Atrix is has lower Android version and it's web-toolkit is slower
Is there any way to resolve that problem?
After the data is loaded you just need to refresh the list.
function initList(){
for(var i=0; i<allData.length; i++){
var line = "<li style='color:#"+ allData[i].Color + ";'>" + allData[i].EventName + "</li>"
$("#thelist").append(line);
}
myScroll.refresh();
}