Unable to call javascript from within Android Activity - javascript

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

Related

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?

push message from code behind

when I use from javascript works perfectly but when I click link button nothing happens. how can I fix pushing message from code behind?
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
protected void LinkButton1_Click(object sender, EventArgs e)
{
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.Send("asf", "111");
}
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
[assembly: OwinStartup(typeof(signalRtest.Startup))]
namespace signalRtest
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}

how to display G map by repeater and markers from database

I want to display google map inside repeater from database values comes, i searched on google and reached to this result but not working with me i don't know if it have something missing or not can you help me please.
<body>
<form id="form1" runat="server">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<asp:Literal runat="server" ID="Literal1"></asp:Literal>
<script type="text/javascript">
var markers = [
<asp:Repeater ID="rptMarkers" runat="server">
<ItemTemplate>
{
"title": '<%# Eval("City") %>',
"lat": '<%# Eval("Latitude") %>',
"lng": '<%# Eval("Longitude") %>'
}
</ItemTemplate>
<SeparatorTemplate>
,
</SeparatorTemplate>
</asp:Repeater>
];
</script>
</body>
Here my code behind aspx.cs,
public class Markers
{
public string City { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
void GetData(string strRsult)
{
XmlDataDocument xmlDataDoc = new XmlDataDocument();
xmlDataDoc.LoadXml(strRsult);
Literal1.Text = "<script type=\"text/javascript\">var markers = [";
foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
{
if (n.HasChildNodes)
{
List<Markers> markers = new List<Markers>();
foreach (XmlNode childNode in n)
{
if (childNode.Name == "GEOData")
{
Literal1.Text += "title: '" + childNode.Attributes["City"].Value + "', lat: '" + childNode.Attributes["Longitude"].Value + "', lng: '" + childNode.Attributes["Latitude"].Value + "'}";
}
}
Literal1.Text += "];</script>";
}
}
XML file
- <AVSearch_PropertyDetails RequestedCurrency="EUR">
- <Property IDHotel="10000" PropertyCode="10000" Hotelname="REZ:Online HOTEL" StarCategory="0" ImageIdentifier="RHN_10000" NumberOfRooms="80" CheckinTime="00:00" CheckoutTime="23:59" Email="info#r-h-n.com" Status="0" StatusInfo="">
- <GEOData CountryCode="DE" CountryName="Germany" City="Duesseldorf" IDCity="32" Zip="40472" Street="Wanheimer Street 45" Longitude="6.7932130" Latitude="51.2871870">
- <Distances>
<Distance Type="1" Distance="0.50" />
<Distance Type="2" Distance="1.81" />
</Distances>
</GEOData>
- <Descriptions>
<Description IDLanguage="4" IDType="1" Text="This is the test hotel used for testing and debugging purposes only. Please do not book this hotel." />
<Description IDLanguage="4" IDType="4" Text="This is a testhotel" />
<Description IDLanguage="4" IDType="3" Text="Terms & conditions EN" />
</Descriptions>
`
Download Google Map DLL in your project from codeplex GoogleMapControl.
Register DLL in your page:
<%# Register Assembly="Artem.Google" Namespace="Artem.Google.UI" TagPrefix="artem" %>
Here is the steps to create Google Map dynamically in repeater control.
First download Artem.Google.dll from this link and put down DLL in bin folder.
ASPX Page Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="GmapRepeater.aspx.cs" Inherits="GmapRepeater" %>
<!DOCTYPE html>
<%# Register Assembly="Artem.Google" Namespace="Artem.Google.UI" TagPrefix="artem" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:Repeater ID="rptMarkers" runat="server" OnItemDataBound="rptMarkers_ItemDataBound">
<ItemTemplate>
<artem:GoogleMap ID="GMap" runat="server"></artem:GoogleMap>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
ASPX.CS Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Artem.Google.UI;
public partial class GmapRepeater : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
protected void rptMarkers_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Markers loData = (Markers)e.Item.DataItem;
GoogleMap GMap = (GoogleMap)e.Item.FindControl("GMap");
GMap.MapType = Artem.Google.UI.MapType.Roadmap;
GMap.ApiVersion = "v2";
GMap.Latitude = Convert.ToDouble(loData.Latitude);
GMap.Longitude = Convert.ToDouble(loData.Longitude);
GMap.Zoom = 18;
GMap.EnableMapTypeControl = false;
GMap.Height = 200;
GMap.Width = 195;
Marker loMarker = new Marker();
loMarker.Position.Latitude = Convert.ToDouble(loData.Latitude);
loMarker.Position.Longitude = Convert.ToDouble(loData.Longitude);
loMarker.Clickable = true;
loMarker.Info = "Marker Information";
loMarker.Title = "Title of your Marker";
loMarker.Visible = true;
GMap.Markers.Add(loMarker);
}
}
private void GetData()
{
XmlDataDocument xmlDataDoc = new XmlDataDocument();
xmlDataDoc.Load(Server.MapPath("~/Files/XMLFile.xml"));
List<Markers> markers = new List<Markers>();
foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
{
if (n.HasChildNodes)
{
foreach (XmlNode childNode in n)
{
if (childNode.Name == "GEOData")
{
Markers loObj = new Markers();
loObj.City = Convert.ToString(childNode.Attributes["City"].Value);
loObj.Longitude = Convert.ToString(childNode.Attributes["Longitude"].Value);
loObj.Latitude = Convert.ToString(childNode.Attributes["Latitude"].Value);
markers.Add(loObj);
}
}
}
}
if (markers != null && markers.Count > 0)
{
rptMarkers.DataSource = markers;
rptMarkers.DataBind();
}
}
}
Markers Entity Class:
public class Markers
{
public string City { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
Please let me know if you have any questions.

Google Glass Augmented Reality with Wikitude SDK

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>

Categories

Resources