Google Glass Augmented Reality with Wikitude SDK - javascript

I am playing with Augmented Reality using Wikitude SDK for Google GLASS and it works fine. The data are loaded as it is supposed and on marker click i am showing a sidebar on the android device, however i am facing an issue when i try to TAP a marker on google glass. Tapping marker on device works fine with Wikitude AR Android SDK but how can i do the same using Wikitude for Google Glass.
As it is said in documentation the onMarkerSelectedfn function is the function which fires when a marker is selected on cam and yes that is working fine in the android device. But it is not working on google glass. Is there any special thing that i should do to work on Google glass too?
Shortly, how can i show details of the marker, on marker tap event, in another LiveCard or ImmersiveCard on Google Glass using Wikitude Augmented Reality SDK for Google Glass? or How to implement Browsing POI Presenting Details in that way that will work also in Google Glass?
onMarkerSelected: function onMarkerSelectedFn(marker) is the function triggered when POI Marker is selected.
Some sources that i found here describes same what i want to achieve however till that time this feature was not available on the SDK (i dont know if still not available as in documentation was not written). However any idea will be appriciated
Here is the WIkitude Google Glass Documentation
Here is the js function:
// fired when user pressed maker in cam
onMarkerSelected: function onMarkerSelectedFn(marker) {
World.currentMarker = marker;
// update panel values
$("#poi-detail-title").html(marker.poiData.name);
$("#poi-detail-description").html(marker.poiData.address);
//var distanceToUserValue = (marker.distanceToUser > 999) ? ((marker.distanceToUser / 1000).toFixed(2) + " km") : (Math.round(marker.distanceToUser) + " m");
$("#poi-detail-distance").html(marker.poiData.distance+" m");
// show panel
$("#panel-poidetail").panel("open", 123);
$( ".ui-panel-dismiss" ).unbind("mousedown");
$("#panel-poidetail").on("panelbeforeclose", function(event, ui) {
World.currentMarker.setDeselected(World.currentMarker);
});
},
Here is the Activity that shows the Markers:
public class RealityActivity extends Activity {
private Context context;
private GestureDetector mGestureDetector;
private ArchitectView architectView;
private double lat = 0.0;
private double lng = 0.0;
public static final String WIKITUDE_SDK_KEY = "API_KEY";
public long lastCalibrationToastShownTimeMillis = System.currentTimeMillis();
public String url = "5_1/index.html";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reality);
getActionBar().hide();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
context = this;
Bundle args = getIntent().getExtras();
if (args != null) {
lat = args.getDouble("lat");
lng = args.getDouble("lng");
}
architectView = (ArchitectView) findViewById(R.id.architectView);
final ArchitectView.ArchitectConfig config = new ArchitectView.ArchitectConfig(WIKITUDE_SDK_KEY);
architectView.onCreate(config);
architectView.registerSensorAccuracyChangeListener(sensorAccuracyChangeListener);
mGestureDetector = createGestureDetector();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
architectView.load(url);
activateArchitectView();
} catch (IOException e) {
Log.v("log", "Could not load architect: " + e.getMessage());
}
}
ArchitectView.SensorAccuracyChangeListener sensorAccuracyChangeListener = new ArchitectView.SensorAccuracyChangeListener() {
#Override
public void onCompassAccuracyChanged(int accuracy) {
/* UNRELIABLE = 0, LOW = 1, MEDIUM = 2, HIGH = 3 */
if (accuracy < SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM && !isFinishing() && System.currentTimeMillis() - lastCalibrationToastShownTimeMillis > 5 * 1000) {
Log.v("log", "ArchitectView.SensorAccuracyChangeListener");
lastCalibrationToastShownTimeMillis = System.currentTimeMillis();
}
}
};
private void activateArchitectView() {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
architectView.setLocation(lat, lng, 100);
String params = getPoiInformation().toString();
callJavaScript("World.loadPoisFromJsonData", new String[]{params});
}
});
}
}, 3000);
}
private void callJavaScript(final String methodName, final String[] arguments) {
final StringBuilder argumentsString = new StringBuilder("");
for (int i = 0; i < arguments.length; i++) {
argumentsString.append(arguments[i]);
if (i < arguments.length - 1) {
argumentsString.append(", ");
}
}
if (this.architectView != null) {
final String js = (methodName + "( " + argumentsString.toString() + " );");
Log.v("log", "YER: " + js);
this.architectView.callJavascript(js);
}
}
private JSONArray getPoiInformation() {
JSONArray pois = new JSONArray();
List<MyModel> sliced = new ArrayList<MyModel>(FindModel.model);
if (FindModel.model.size() > 10) {
sliced = FindModel.model.subList(0, 10);
}
for (MyModel model : sliced) {
HashMap<String, String> poi = new HashMap<String, String>();
poi.put("id", String.valueOf(model.id));
poi.put("name", model.name);
poi.put("address", model.address);
poi.put("distance", String.valueOf(((int) model.distance)));
poi.put("lat", String.valueOf(model.lat));
poi.put("lng", String.valueOf(model.lng));
pois.put(new JSONObject(poi));
}
return pois;
}
#Override
public void onLowMemory() {
super.onLowMemory();
if (architectView != null) {
architectView.onLowMemory();
}
}
#Override
protected void onResume() {
super.onResume();
if (architectView != null) {
architectView.onResume();
if (sensorAccuracyChangeListener != null) {
architectView.registerSensorAccuracyChangeListener(sensorAccuracyChangeListener);
}
}
}
#Override
protected void onPause() {
super.onPause();
if (architectView != null) {
architectView.onPause();
if (sensorAccuracyChangeListener != null) {
architectView.unregisterSensorAccuracyChangeListener(sensorAccuracyChangeListener);
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (architectView != null) {
architectView.onDestroy();
}
}
private GestureDetector createGestureDetector() {
GestureDetector gestureDetector = new GestureDetector(context);
//Create a base listener for generic gestures
gestureDetector.setBaseListener( new GestureDetector.BaseListener() {
#Override
public boolean onGesture(Gesture gesture) {
if (gesture == Gesture.TAP) {
// do something on tap
Toast.makeText(context, "TAP", Toast.LENGTH_SHORT).show();
return true;
} else if (gesture == Gesture.TWO_TAP) {
// do something on two finger tap
Toast.makeText(context, "TWO_TAP", Toast.LENGTH_SHORT).show();
return true;
} else if (gesture == Gesture.SWIPE_RIGHT) {
// do something on right (forward) swipe
Toast.makeText(context, "SWIPE_RIGHT", Toast.LENGTH_SHORT).show();
return true;
} else if (gesture == Gesture.SWIPE_LEFT) {
// do something on left (backwards) swipe
Toast.makeText(context, "SWIPE_LEFT", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
gestureDetector.setFingerListener(new GestureDetector.FingerListener() {
#Override
public void onFingerCountChanged(int previousCount, int currentCount) {
// do something on finger count changes
}
});
gestureDetector.setScrollListener(new GestureDetector.ScrollListener() {
#Override
public boolean onScroll(float displacement, float delta, float velocity) {
// do something on scrolling"
return false;
}
});
return gestureDetector;
}
/*
* Send generic motion events to the gesture detector
*/
#Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mGestureDetector != null) {
return mGestureDetector.onMotionEvent(event);
}
return false;
}
}
and here is the index.html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Type"
content="application/json; charset=utf-8">
<meta
content="width=device-width,initial-scale=1,maximum-scale=5,user-scalable=yes"
name="viewport">
<script src="architect://architect.js"></script>
<!-- positioning of poi-radar -->
<link rel="stylesheet" href="css/poi-radar.css" />
<!-- jquery mobile CSS -->
<link rel="stylesheet" href="jquery/jquery.mobile-1.3.2.min.css" />
<!-- required to set background transparent & enable "click through" -->
<link rel="stylesheet"
href="jquery/jquery-mobile-transparent-ui-overlay.css" />
<!-- jquery JS files -->
<script type="text/javascript" src="jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="jquery/jquery.mobile-1.3.2.min.js"></script>
<!-- marker representation-->
<script src="js/marker.js"></script>
<!-- World logic-->
<script type="text/javascript" src="js/presentingPoiDetails.js"></script>
<!-- radar component -->
<script type="text/javascript" src="js/radar.js"></script>
<script>
$( document ).ready(function() {
//alert("onReady");
//console.log("onReady");
//AR.logger.activateDebugMode();
$("#log").css({ opacity: 0 });
$("#footer").css({ opacity: 0 });
$(document).click(function (e) {
//alert("click");
if(e){
console.log("onclick");
alert(e);
}
});
$('#log').click(function (e) {
if(e){
console.log("onclick");
var offset = $(this).offset();
var left = e.clientX - offset.left);
var top = e.clientY - offset.top);
alert(left+":"+top);
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page1" style="background: none;">
<!-- the radar div - Wikitude SDK radar will be drawn into this div -->
<div class="radarContainer_left" id="radarContainer"></div>
<div id="log" style="float: right;">log data</div>
<!-- transparent footer-->
<div id="footer" data-role="footer" class="ui-bar" data-theme="f"
data-position="fixed" style="text-align: center;">
<!-- small status-button -->
<a style="text-align: right;" id="popupInfoButton" href="#popupInfo"
data-rel="popup" data-role="button" class="ui-icon-alt"
data-inline="true" data-transition="pop" data-icon="alert"
data-theme="e" data-iconpos="notext">Log</a> <br />
<!-- popup displayed when button clicked -->
<div data-role="popup" id="popupInfo" class="ui-content"
data-theme="e" style="max-width: 350px;">
<p style="text-align: right;" id="status-message">Trying to find
out where you are</p>
</div>
</div>
<div
id="panel-poidetail"
data-role="panel"
data-position="right"
data-display="overlay"
data-theme="a" >
<div data-role="header">
Close
<h1>Detay</h1>
Path
</div>
<div data-role="content">
<b>Cami<b>
<br/>
<span id="poi-detail-title">Test Name</span>
<br/>
<br/>
<b>Test Address</b>
<br/>
<span id="poi-detail-description">Test Desc</span>
<br/>
<br/>
<b>Test Distance</b>
<br/>
<span id="poi-detail-distance">240 m</span>
<br/>
<br/>
</div>
</div>
</div>
</body>
</html>

Related

Data format issue with passing data between JavaScript and C#

The structure is like this:
Test.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="PartTimeFrontendMockup.Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"/>
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css"/>
<!-- Theme style -->
<link id="stileAdminLTE" runat="server" rel="stylesheet" href="dist/css/adminlte.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar#5.7.2/main.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<div class="card card-warning">
<div class="card-header">
<h3 class="card-title">Selezione date Part-time</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form class="form-horizontal">
<div class="card-body">
<div class="form-group row">
<div class="col-sm-4">
<!-- small card -->
<div class="small-box bg-success">
<div class="inner">
<h3><span id="spanPTPerc">0</span><sup style="font-size: 20px">%</sup></h3>
<p>Percentuale part-time</p>
</div>
<div class="icon">
<i class="fas fa-calculator"></i>
</div>
</div>
</div>
<div class="card bg-blue col-sm-8 form-inline">
<label for="inputdalle" class="col-sm-2 col-form-label">Dalle</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="inputdalle" placeholder="Dalle" value="6:30"/>
</div>
<label for="inputalle" class="col-sm-2 col-form-label">Alle</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="inputalle" placeholder="Alle" value="12:30"/>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
</div>
<!-- /.card-footer -->
</form>
</div>
<div id="PTCalendar"></div>
<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- Momentjs -->
<script src="plugins/moment/moment.min.js"></script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-loading-overlay/2.1.7/loadingoverlay.min.js" integrity="sha512-hktawXAt9BdIaDoaO9DlLp6LYhbHMi5A36LcXQeHgVKUH6kJMOQsAtIw2kmQ9RERDpnSTlafajo6USh9JUXckw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar#5.7.2/main.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar#5.7.2/locales-all.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="js/PTMockup.js"></script>
</body>
</html>
Test.aspx.cs:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PartTimeBackend;
using System;
using System.Collections.Generic;
namespace PartTimeFrontendMockup
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
if (Request["Action"] == "GetPTPercentage") {
string ss = "";
JObject j = new JObject();
JArray eventi=(JArray) JsonConvert.DeserializeObject(Request["eventi"]);
PTEvent pte = new PTEvent();
List<DateTime> LDT = new List<DateTime>();
DateTime dtdalle = new DateTime();
DateTime dtalle = new DateTime();
foreach (JObject evt in eventi) {
JProperty dalle = evt.Property("start");
JProperty alle = evt.Property("end");
dtdalle = Convert.ToDateTime(dalle.First.Value<String>());
dtalle = Convert.ToDateTime(alle.First.Value<String>());
pte.AddDateFromMisto(dtdalle, dtalle);
}
double asd = pte.PTpercentage;
string perc = String.Format("{0:0.0}", asd) ;
Response.Clear();
string ret = "OK";
if (ret == "OK")
{
j.Add("Stato", "OK");
j.Add("perc", perc);
}
else
{
j.Add("Stato", "KO");
j.Add("Errore", ret);
}
Response.Write(JsonConvert.SerializeObject(j));
Response.End();
}
}
}
}
}
Finally, classes file:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using EWSoftware.PDI;
using System.Data.Common;
using PartTimeBackend.models;
using EWSoftware.PDI.Objects;
using EWSoftware.PDI.Properties;
using EWSoftware.PDI.Parser;
using EWSoftware.PDI.Binding;
using System.Web;
namespace PartTimeBackend
{
public class PTEvent
{
public DateTime StartDateTimePT { get; set; }
public DateTime EndDateTimePT { get; set; }
public TimeSpan totalWorkingTime;
public double PTpercentage;
public string PTperc;
public int totDates;
public VCalendar vc;
public List<DateDuration> DDL;
public List<DateTime> datesChecker;
public PTEvent()
{
this.vc = new VCalendar();
DDL = new List<DateDuration>();
totDates = 0;
PTpercentage = 0;
totalWorkingTime = new TimeSpan();
datesChecker = new List<DateTime>();
StartDateTimePT = DateTime.Today;
EndDateTimePT = DateTime.Today;
}
public void AddDateFromMisto(DateTime dtFrom, DateTime dtTo)
{
DateDuration dd = new DateDuration();
RRuleProperty rrp = new RRuleProperty();
VEvent nve = new VEvent();
dd.dalle = dtFrom;
dd.alle = dtTo;
nve.RecurDates.Add(dtFrom);
this.DDL.Add(dd);
GetPTPercentage();
}
private void CalculateTOTs()
{
var distinctItems = this.DDL.Distinct();
this.totDates = this.DDL.Distinct().Count();
}
public string GetPTDates()
{
string allDates = "";
foreach (var x in this.DDL)
{
allDates += "date: " + x.dalle + "\t duration: " + x.Duration + "\r\n";
}
return allDates;
}
public void GetPTPercentage()
{
CalculateTOTs();
var distinctItems = this.DDL.Distinct();
TimeSpan ts = new TimeSpan();
foreach (var xx in distinctItems)
{
ts += xx.Duration;
}
this.PTpercentage = ((ts.TotalHours) / 1872) * 100;
this.totalWorkingTime = ts;
}
}
public class DateDuration
{
public DateTime dalle;
public DateTime alle;
public TimeSpan Duration
{
get { return alle - dalle; }
}
}
}
The web oage should work like this:
Whenever a user clicks on a date, the date should be marked as an event, the <span id="spanPTPerc">0</span> content should hold percentage of the Part-Time.
My problem can be summed into two major issues:
How can I debug the whole process? That would help trace the change in values in the variables and edit the code accordingly.
Is there a problem in the passing of the event data to C#? I think the whole issue relies in the conversion between datetime and the JavaScript's moment.js
Update: whenever I try to printout the JArray variable "eventi", i it is always "[]" which should indicate an empty array .. that might be the problem.
Mockup.js
function popErrore(testo) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: testo,
})
}
/* initialize the calendar
-----------------------------------------------------------------*/
//Date for the calendar events (dummy data)
var date = new Date()
var d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear()
var Calendar = FullCalendar.Calendar;
var Draggable = FullCalendar.Draggable;
var containerEl = document.getElementById('external-events');
var checkbox = document.getElementById('drop-remove');
var calendarEl = document.getElementById('PTCalendar');
// initialize the external events
// -----------------------------------------------------------------
var j = [];
var calendar = new Calendar(calendarEl, {
locale: 'it',
headerToolbar: {
left: 'prev,next',
center: 'title',
right: ''
},
eventOverlap:false,
themeSystem: 'bootstrap',
eventDidMount: function (info) {
if (info.event.display != 'background') {
$(info.el).popover({
animation: true,
delay: 300,
html: true,
content: info.event.extendedProps.description,
trigger: 'hover'
});
}
},
});
calendar.render();
/* AGGIUNTA EVENTI */
function addNew(info) {
var strdalle = $("#inputdalle").val();
var stralle = $("#inputalle").val();
var dalle = new moment(info.dateStr +" "+ strdalle, "YYYY-MM-DD hh:mm")
var alle = new moment(info.dateStr + " " + stralle, "YYYY-MM-DD hh:mm")
var myEvent = {
title: "Part Time dalle " +strdalle + " alle " +stralle,
start: dalle,
end: alle,
description:'Part Time',
display:'block',
backgroundColor: 'green',
allDay: false
};
calendar.addEvent(myEvent);
}
calendar.on('dateClick', function (info) {
addNew(info);
$.post('Test.aspx', // url
{
Action: 'GetPTPercentage',
eventi: JSON.stringify(calendar.getEvents()),
}, // data to be submit
function (data, status, jqXHR) {// success callback
var jObj = JSON.parse(data);
if (jObj.Stato == "OK") {
$("#spanPTPerc").text(jObj.perc);
} else {
popErrore(jObj.Errore);
}
})
});

Showing timer from c# on html page using javascript

Hello I am trying to implement a timer in c sharp that counts seconds and display it on my html page. But when i pass the variable to javascript it is always 0. I have searched everywhere for an answer.
This is my code so far:
The timer object:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
/// <summary>
/// Summary description for Class1
/// </summary>
public class TimerEu
{
private Timer t;
private int time;
public TimerEu()
{
this.t = new Timer(1000);
this.time = 0;
t.Elapsed += new ElapsedEventHandler(RunEvent);
t.Interval = 1000;
t.Enabled = true;
}
public void RunEvent(object source, ElapsedEventArgs e)
{
this.time++;
Console.WriteLine(time);
}
public int getTime()
{
return this.time;
}
}
aspx.cs page:
public partial class _Default : System.Web.UI.Page
{
public String[] var=new String[10];
public TimerEu time;
public int testint;
protected void Page_Load(object sender, EventArgs e)
{
time = new TimerEu();
testint = 0;
Console.Write("hello"+time.getTime());
for (int i = 0; i < 10; i++)
var[i] =Operations.test.convertString();
}
public void plus()
{
this.testint++;
}
}
and the html/javascript part:
<form id="form1" runat="server">
<div>
<br></br>
<br></br>
<br></br>
<p id="demo" runat="server"></p>
<script>
var now=0;
var x= setInterval(function () {
//now++;
now = <%=time.getTime()%>
// now =<%=testint%>
// <%plus();%>
document.getElementById("demo").innerHTML = now;
},1000)
</script>
The problem is that the javascript dosen't seem to call the getTime function every sec, instead it only gets 0 as output. What am I doing wrong?
You have to understand important thing. This statement <%=time.getTime()%> is executed only once on the server side before rendered html page is sent to the browser. When it's executed, it will be replaced with 0 (the result of method call).
Browser will see only now = 0 and in this case, javascript code doesn't make any sense
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var before_loadtime = new Date().getTime();
window.onload = Pageloadtime;
function Pageloadtime() {
var aftr_loadtime = new Date().getTime();
// Time calculating in seconds
pgloadtime = (aftr_loadtime - before_loadtime) / 1000
document.getElementById("loadtime").innerHTML = "Pgae load time is <font color='red'><b>" + pgloadtime + "</b></font> Seconds";
}
</script>
</head>
<body>
<h3 style="font-weight: bold; font-style: italic; font-size: large; color: #3333CC">Page load time in JavaScript</h3>
<div>
<span id="loadtime"></span>
</div>
</body>
</html>

Calling C# COM Object from javascript fails

I'm trying to call a COM C# Object from javascript code and get an object that doesn't contain the COM object functions.
I created a setup project for the C# COM library. The library is signed for COM interop, and the setup project output is signed for COM register on the machine it deployed at.
I see that the TLB is properly exported.
C# Code:
using System;
using System.Runtime.InteropServices;
namespace YaronTestCOM
{
[Guid("BD145EEC-ACAC-4FDB-B766-0F15CE07990F")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IComEvents))]
public class YaronComObject : IComObject, IObjectSafety
{
[ComVisible(false)]
public delegate void YaronFirstEventHandler(string args);
public event YaronFirstEventHandler YaronFirstEvent;
public int YaronFirstComCommand(string arg)
{
if (YaronFirstEvent != null)
YaronFirstEvent(arg);
return (int)DateTime.Now.Ticks;
}
public void Dispose()
{
}
}
[Guid("A3576AA4-9DE0-422D-BAA3-3FFB862E8007")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[ComVisible(true)]
public interface IComObject
{
[DispId(0x10000001)]
int YaronFirstComCommand(string arg);
[DispId(0x10000002)]
void Dispose();
}
[Guid("B551EC8B-4D19-4781-938C-9E50E70D37CD")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComEvents
{
[DispId(0x00000001)]
void YaronFirstEvent(string args);
}
}
HTML+Javascrip Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<object id="publisher" name="publisher" classid="clsid:BD145EEC-ACAC-4FDB-B766-0F15CE07990F"></object>
<title>Sender Test</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var msgTxt = $("#msgTxt");
$("#btnSend").click(function () {
var msg = msgTxt.val();
//publisher.YaronFirstComCommand is undefined!!!
var result = publisher.YaronFirstComCommand(msg);
alert('The message ' + msg + 'has been sent and returned ' + result);
});
});
</script>
</head>
<body>
<div>
<input type='text' id='msgTxt' />
<input type='button' value='Send Message' id='btnSend' />
</div>
</body>
Any ideas?

Unable to call javascript from within Android Activity

I am trying to invoke a simple highlight-this-text javascript function in an xhtml page loaded in the assets folder and displayed in a WebView from within an Android activity. Using the following functions:
1. loadUrl("javascript:myFunc(param)"); does not work.
2. Neither does inlining the entire function within the loadUrl work.
3. I have also tried to use the highlighting function in a separate file (highlighter.js) and also within the xhtml body section (using CDATA tags).
None of the above approaches has worked. I need help in figuring out what I am doing wrong.
The code:
/* JSWebview:
* 1. Loads a webpage in the external sdcard.
* 2. enables javascript and runs a small script.
*/
package com.sriram.jswebview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView wv = null;
private String url = null;
private JSInterface myJSI;
private Button fromMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPage();
//wv.loadUrl("javascript:doecho(\"Hello World!\");");
//wv.loadUrl("javascript:tostring());");
String toFind = "Hello";
Log.v(this.toString(), "Finding string = " + toFind);
//find string and highlight.
if(android.os.Build.VERSION.SDK_INT < 16) {
Log.v(this.toString(), "Launching findAll.");
int num = wv.findAll(toFind);
Log.v(this.toString(), num + " instances found.");
} else {
Log.v(this.toString(), "Searching with findAllAsync.");
wv.findAllAsync(toFind);
}
fromMain = (Button) findViewById(R.id.fromMain);
fromMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = "This is a test.";
wv.loadUrl("javascript:callFromActivity(\""+message+"\")");
//wv.loadUrl("javascript:function (msg) { var oldHTML = document.getElementById(\"highlightbegin\"); var newHTML = \"<span style=\'color:#ffa000\'>\" + msg + \"</span>\"; document.getElementById(\"highlightbegin\").innerHTML = newHTML;}");
}
});
}
#SuppressLint("SetJavaScriptEnabled")
#SuppressWarnings("deprecation")
public void loadPage() {
//loads the index.xhtml page from /mnt/sdcard.
Log.v(this.toString(), "Inside loadPage().");
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//external media is mounted.
url = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "index.xhtml";
Log.v(this.toString(), "URL = " + url);
}
wv = (WebView) findViewById(R.id.wv);
wv.getSettings().setJavaScriptEnabled(true); //enable javascript.
myJSI = new JSInterface(this.getApplicationContext(), wv);
wv.addJavascriptInterface(myJSI, "JSInterface");
if((wv != null) && (url != null)) {
Log.v(this.toString(), "Inside loadurl.");
//wv.loadUrl(url);
wv.loadUrl("file:///android_asset/mypage.xhtml");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
//this class is used to call Javascript functions that act on the html page.
class JSInterface {
private WebView wv = null;
private Context c;
public JSInterface(Context context, WebView w) {
Log.v(this.toString(), "Inside JSInterface constructor.");
c = context;
wv = w;
}
public String tostring() {
//Log.v(this.toString(), "Inside toString()");
String result = "injected Object";
return result;
}
public void doecho(String x) {
Log.v(this.toString(), "Inside doEcho of JSInterface.");
Toast.makeText(wv.getContext(), x, Toast.LENGTH_SHORT).show();
}
public void showToast(String message) {
Toast.makeText(c, message, Toast.LENGTH_LONG).show();
}
public void openAndroidDialog() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(c);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/fromMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="fromMain" />
<WebView
android:id="#+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_world"
android:layout_above="#id/fromMain" />
</RelativeLayout>
mypage.xhtml (present within the assets folder:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="application/xhtml+xml;charset=UTF-8" />
<title>My HTML</title>
</head>
<body>
<h1>MyHTML</h1>
<p id="highlightbegin">Hello World! This is a test.</p>
<div> <input type="button" value="Alert" onclick="displayAlert()" /> </div>
<div> <input type="button" value="Say hello" onclick="showAndroidToast('Hello Android!')" /> </div>
<div> <input type="button" value="Open Dialog" onclick="openAndroidDialog()" /> </div>
<div> <input type="button" value="Add highlight" onclick="changeColor()" /> </div>
<script type="text/javascript">
//<![CDATA[
function showAndroidToast(toast) {
JSInterface.showToast(toast);
}
function openAndroidDialog() {
JSInterface.openAndroidDialog();
}
function displayAlert() {
window.alert("I am here!");
}
//]]>
</script>
<script src="doecho.js" type="text/javascript"> </script>
<script src="tostring.js" type="text/javascript"> </script>
<script src="highlighter.js" type="text/javascript"> </script>
</body>
</html>
highlighter.js (which contains the javascript function):
function callFromActivity(msg) {
alert(msg);
var oldHTML = document.getElementById("highlightbegin");
alert(oldHTML);
var newHTML = "<span style='color:#ffa000'>" + msg + "</span>";
alert(newHTML);
document.getElementById("mytext").innerHTML = newHTML;
}

how to make html page detect enter key pressed?

I am using VSTS 2008 + C# + .Net 3.5 + IIS 7.0 + ASP.Net to develop a web application. The web application has an aspx page called default.aspx. And I want to implement the effect that when user press the enter key of keyboard, it is the same effect of press button "Action". Any ideas how to implement?
Here is the default.aspx file,
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<script type="text/javascript">
function requery() {
var query = location.search.substring(1);
var pairs = query.split("&");
var param1Value = document.getElementById("txtParam1").value;
url = "/Default.aspx?param1=" + param1Value;
for (var i = 0; i < pairs.length; ++i) {
var pair = pairs[i];
if ((pair.indexOf("param1") != 0) && (pair.length > 0)) {
url += "&" + pair;
}
}
location.href = url;
}
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtParam1" runat="server"></asp:TextBox>
<input type="button" value="Action" onclick="requery()" />
</div>
</form>
</body>
</html>
Here is the code behind file default.aspx.cs,
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtParam1.Text = Request.QueryString["param1"];
}
}
}
add an event handler to the document's keydown event. explanation in the comments.
function keydownHandler(e) {
if (e.keyCode == 13) { // 13 is the enter key
requery(); // call your function.
// alternately, give your button an id and used
// document.getElementById('myID').click();
// prevent the browser from doing whatever it normally
// does when you push the enter key.
// (not tested for this situation, may need tweaking)
if (e.preventDefault) {
e.preventDefault(); // FF,chrome
}
else {
return false; // IE
}
}
}
// register your handler method for the keydown event
if (document.addEventListener) {
document.addEventListener('keydown', keydownHandler, false);
}
else if (document.attachEvent) {
document.attachEvent('onkeydown', keydownHandler);
}
If you are browsing from Internet Explorer this is an annoying issue. Add a textbox with a style of display:none;visibility:hidden; The enter key will respond appropriately. This typically occurs on forms with one text input in IE. Add the hidden one as mentioned above under your first input field

Categories

Resources