How to load pdf from java to object in html - android

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

Related

Android WebView showing blank page for local files

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.

check this value with the Android Webview After saving the values to the local storage on the Android browser

I'm going to check this value with the Android Webview After saving the values ​​to the local storage on the Android browser.
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>HTML5</title>
<script>
window.onload = function(){
loadStorage();
document.querySelector("form").onsubmit = saveStorage;
};
function saveStorage(){
var saveId = document.getElementById("saveId").checked;
var userId = document.getElementById("userId").value;
if(saveId){
window.localStorage.setItem("userId", userId);
window.localStorage.setItem("userIdSaved", true);
}else{
window.localStorage.removeItem("userId");
window.localStorage.setItem("userIdSaved", false);
}
}
function loadStorage(){
var userId = window.localStorage.getItem("userId");
document.getElementById("userId").value = userId;
if(userId!=null){
document.getElementById("saveId").checked = true;
}
}
</script>
</head>
<body>
<h1>Login(Web Storage)</h1>
<form action="login.php" method="post">
<fieldset>
id: <input type="text" name="id" id="userId" autocomplete="off">
<input type="checkbox" id="saveId">Save ID<br>
pass: <input type="password"><br>
<input type="submit" value="login">
</fieldset>
</form>
</body>
</html>
However, if you run a webview not output the value stored in the Android browser.
Check the values ​​by executing the Webview, but does not save local storage in
<html>
<head>
<meta charset="UTF-8">
<title>HTML5</title>
</head>
<?
$Id = $_POST['id'];
?>
<script>
window.onload = function(){
var userId = window.localStorage.getItem("userId");
alert(userId);
init();
};
function init(){
var list = document.getElementById( "list");
list.innerHTML = "";
for( var i = 0; i < localStorage.length ; i++){
var key = localStorage.key(i);
list.options[list.options.length] = new Option(localStorage[key],key);
}
}
</script>
<body>
<h1>Result</h1>
<p>Welcome to <?=$Id?> </p>
home<br/>
<select id = "list" size= "10"></ select>
<fieldset >
key : <input type = "text" id= "key"/>
value : <input type = "text" id= "value"/>
</fieldset >
</body>
</html>
To show the value stored in the Webview, how can I do?
I am not sure you can use web localStorage inside WebView. However you may store values in the application preferences. Implement corresponding methods in your custom Javascriptinterface. See https://stackoverflow.com/a/10389678/527759

html2canvas with phonegap error

Getting error
"11-13 13:10:55.470: E/Web Console(9799):
Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17 at
file:///android_asset/www/index.html:304"
when converting html div content to canvas in android with phonegap.
It is working properly on browser. Any help will be appreciated. I am using jQuery-1.9.1, jQuery-UI.
code snippet:
// html file
<html>
<head>
<meta charset="utf-8" />
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="resourcess/css/jquery-ui.css" />
<script src="js/jquery-1.9.1.js"></script>
<script src="js/html2canvas.js"></script>
<script src="js/jquery.plugin.html2canvas.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery.ui.touch-punch.min.js"></script>
<script src="cordova-2.5.0.js"></script>
<link rel="stylesheet" href="resourcess/css/style.css" />
</head>
<body>
<div class="imag-container">
<div class="dragImg">
<div id="dropHere"></div>
<div id="click" > click </div>
<div id="img-check">check</div>
<canvas id="canvas" width="100" height="100">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</body>
// script
$(function(){
//Make every clone image unique.
var counts = [0];
var resizeOpts = {
handles: "all" ,autoHide:true
};
$(".dragImg").draggable({
helper: "clone",
//Create counter
start: function() { counts[0]++; }
});
$("#dropHere").droppable({
drop: function(e, ui){
if(ui.draggable.hasClass("dragImg")) {
$(this).append($(ui.helper).clone());
//Pointing to the dragImg class in dropHere and add new class.
$("#dropHere .dragImg").addClass("item-"+counts[0] );
$("#dropHere .img").addClass("imgSize-"+counts[0]);
//Remove the current class (ui-draggable and dragImg)
$("#dropHere .item-"+counts[0]).removeClass("dragImg ui-ggable ui-draggable-dragging");
$(".item-"+counts[0]).dblclick(function() {
$(this).remove();
});
make_draggable($(".item-"+counts[0]));
$(".imgSize-"+counts[0]).resizable(resizeOpts);
}
}
});
var zIndex = 0;
function make_draggable(elements)
{
elements.draggable({
containment:'parent',
start:function(e,ui){ ui.helper.css('z-index',++zIndex); },
stop:function(e,ui){
}
});
}
$('#click').click(function(){
//Some code
var domElement = document.getElementById('dropHere');
setTimeout(function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext('2d');
html2canvas(domElement, {
onrendered: function (domElementCanvas) {
var canvas = document.getElementById("canvas");
canvas.getContext('2d').drawImage(domElementCanvas, 0, 0, 50, 50,0,0,100,100);
}
});
}, 10000);
});
});

Interfacing with Html And Android

I have developed a media player in Html.Now my job is to play streaming Url in Html coded media player coming from Android activity.So i have need to pass url from android activity to Html media player files where it will be play.I have searched lot but haven't find any good solution.please suggest me. Thanks
Java Code
setContentView(R.layout.main);
// String LocalFile = "file:///android_asset/android.html";
WebView webView = (WebView) findViewById(R.id.webView1);
String html = "<embed src=\"file:///android_asset/"
+ "android.html"
+ " \"play=\"true\" loop=\"true\" width=\"100%\" height=\"100%\"> <embed>";
webView.getSettings().setPluginState(WebSettings.PluginState.OFF);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadDataWithBaseURL("file:///android_asset/", html,
"text/html", "utf-8", null);
String str = "rtmp://23.21.155.146:554/9016012507701502509011502505116016019xm150.sdp";
webView.loadUrl("javascript:passWebUrl('" + str + "')");
My Code for media player
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<style type="text/css" media="screen">
html, body{
margin:0;
padding:0;
height:100%;
}
#altContent{
width:100%;
height:100%;
}
</style>
<title>YOUR TITLE HERE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
function passWebUrl(url)
{
alert(url);
}
flashvars.HaloColor = "0x0086db";
flashvars.ToolTips = "true";
flashvars.AutoPlay = "true";
flashvars.VolumeLevel = "50";
flashvars.CaptionURL = "YOUR CAPTION HERE";
flashvars.Title = "YOUR TITLE HERE";
flashvars.Logo = "";
flashvars.SRC = "Here is my url link should comes from Android Activity";
flashvars.BufferTime = "5";
flashvars.AutoHideControls = "false";
flashvars.IsLive = "true";
var params = {};
params.wmode = "transparent";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "L3MP";
swfobject.embedSWF("http://media-player.cdn.level3.net/flash/v1_1_1/Level3MediaPlayer.swf", "altContent", "100%", "100%", "10.1.0","http://media-player.cdn.level3.net/flash/v1_1_1/expressInstall.swf", flashvars, params, attributes);
</script>
</head>
<body>
<div id="altContent">
<center> <BR><BR><span style="color:red"><b>Please Install Adobe Flash Player</b>
</span><BR><BR>
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</center>
</div>
</body>
</html>
</script>
</html>
For passing the value of variable from your java class to the javascript function in your html page you have to use this code. Try this:
String str = "variable_value";
webView.loadUrl("javascript:functionName('"+ str +"')");
EDIT : -
function passWebUrl(url)
{
alert(url);
}

How to display a MapView and a StreetView simultaneously?

I want to display a MapView that may be used to select a point to be displayed by StreetView in a separate area. I know that the API disallows multiple MapViews in a single process.
How can I cause StreetView to display in a different area than that which displays MapView?
I have been able to grab a static streetview without any problems, but I want to have dynamic StreetView and MapView.
aTdHvAaNnKcSe (THANKS in ADVANCE)
You can load 360 degree panoramic Google street-view in your WebView.
Try following activity in which both google-street-view and google-map can be navigated simultaneously in single Activity :
public class StreetViewActivity extends Activity {
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mappingWidgets();
}
private void mappingWidgets() {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setSupportZoom(false);
// If you want to load it from assets (you can customize it if you want)
//Uri uri = Uri.parse("file:///android_asset/streetviewscript.html");
// If you want to load it directly
Uri uri = Uri.parse("https://google-developers.appspot.com/maps/documentation/javascript/examples/full/streetview-simple");
webView.loadUrl(uri.toString());
}
}
You can place this as static HTML page in assets folder of your application and then you can modify it's java-script according to your needs using Google street-view API.
Here I am posting sample streetviewscript.html that you can put in assets folder of your application and customize it according to your needs :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Street View Layer</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script>
function initialize() {
var fenway = new google.maps.LatLng(42.345573,-71.098326);
var mapOptions = {
center: fenway,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById('map_canvas'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10,
zoom: 1
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
map.setStreetView(panorama);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 800px; height: 800px"></div>
<div id="pano" style="position:absolute; left:810px; top: 8px; width: 800px; height: 800px;"></div>
</body>
</html>
Edit : For simultaneously navigating two street views, load following HTML from assets :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Street View Events</title>
<STYLE type="text/css">
body, html { height:100%; padding:0; margin:0;}
#pano { float:left }
#pano1 { float:right }
</STYLE>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var cafe = new google.maps.LatLng(37.869085,-122.254775);
var heading_value = 270;
var pitch_value = 0;
var zoom_value = 1;
function initialize() {
var panoramaOptions = {
position: cafe,
pov: {
heading: heading_value,
pitch: pitch_value,
zoom: zoom_value
},
visible: true
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'), panoramaOptions);
var panorama2 = new google.maps.StreetViewPanorama(document.getElementById('pano1'), panoramaOptions);
google.maps.event.addListener(panorama, 'pano_changed', function() {
var panoCell = document.getElementById('pano_cell');
panoCell.innerHTML = panorama.getPano();
panorama2.setPano(panorama.getPano());
});
google.maps.event.addListener(panorama, 'links_changed', function() {
var linksTable = document.getElementById('links_table');
while(linksTable.hasChildNodes()) {
linksTable.removeChild(linksTable.lastChild);
};
var links = panorama.getLinks();
panorama2.setLinks(panorama.getLinks());
for (var i in links) {
var row = document.createElement('tr');
linksTable.appendChild(row);
var labelCell = document.createElement('td');
labelCell.innerHTML = '<b>Link: ' + i + '</b>';
var valueCell = document.createElement('td');
valueCell.innerHTML = links[i].description;
linksTable.appendChild(labelCell);
linksTable.appendChild(valueCell);
}
});
google.maps.event.addListener(panorama, 'position_changed', function() {
var positionCell = document.getElementById('position_cell');
positionCell.firstChild.nodeValue = panorama.getPosition();
panorama2.setPosition(panorama.getPosition());
});
google.maps.event.addListener(panorama, 'pov_changed', function() {
var headingCell = document.getElementById('heading_cell');
var pitchCell = document.getElementById('pitch_cell');
headingCell.firstChild.nodeValue = panorama.getPov().heading;
panorama2.setPov(panorama.getPov());
pitchCell.firstChild.nodeValue = panorama.getPov().pitch;
});
}
</script>
</head>
<body onload="initialize()">
<div style="width:100%; height :100%; background-color:Lime;">
<div id="pano" style="width:50%; height:100%; background-color:Blue;">
</div>
<div id="pano1" style="width:50%; height:100%; background-color:Gray;">
</div>
</div>
<div id="panoInfo" style="width: 425px; height: 240 px;float:left; display: none;">
<table>
<tr>
<td><b>Position</b></td><td id="position_cell"> </td>
</tr>
<tr>
<td><b>POV Heading</b></td><td id="heading_cell">270</td>
</tr>
<tr>
<td><b>POV Pitch</b></td><td id="pitch_cell">0.0</td>
</tr>
<tr>
<td><b>Pano ID</b></td><td id="pano_cell"> </td>
</tr>
<table id="links_table"></table>
</table>
</div>
</body>
</html>
How can I cause StreetView to display in a different area than that which displays MapView?
Street View is only available on the device as its own activity (from its own application) and therefore cannot be displayed alongside any of your own widgets.
On Android have a look at the sample Street View Panorama and Map available at https://developers.google.com/maps/documentation/android/code-samples. But i am not sure if it will also do for custom street views.

Categories

Resources