I am developing one Android app using Cordova. On the app startup I want to show some dynamic message on the UI which is index.html. How can I show this message from Java code.
index.html
MainActivity.java
How to update the value of text box on index.html ?
In short I want to update some value from my JAVA code not from JavaScript!
Thank you
This is how i do it. (less stress)
First you need to attach an event listener to the OnLoad Event of the index.
HTML
<body onLoad="showMessage()">
JavaScript
function showMessage()
{
alert('Hello Message');
}
Now the showMessage() function will be called as soon as the page load is completed. Do note that you can also create your own method for displaying a message instead of using an alert.
You're welcome.
UPDATE
This is a simple method for showing a dynamic message (instead of an alert)
I'm only adding this because i'm guessing that you are requesting help with the code also. So here is a super sweet alert box, complete with animations.
First make sure you have the required HTML on the page that will be used to display the message
HTML
<div id="Page_Alert" class="Animate_Opacity">
<div id="Page_Alert_Box_Container" class="Box_Container Animate_MarginTop">
<div id="Page_Alert_Title">Alert Preview</div>
<div id="Page_Alert_Content">This is just a preview of what an alert popUp will look like.</div>
<div class="Buttons_Container">
<div class="BTN" onClick="hide_AlertWindow()">OK</div>
<!-- <div class="BTN">CANCEL</div> -->
</div>
</div>
<div class="bg"></div>
</div><!-- End Alert Pop Up -->
CSS
#Page_Alert{position:absolute; top:0; left:0%; width:100%; height:100%; z-index:-20; opacity:0; overflow:hidden;}
#Page_Alert > .bg{position:absolute; top:0; left:0; width:100%; height:100%; background:BLACK; opacity:.6; z-index:0;}
#Page_Alert > .Box_Container{position:relative; margin:auto; margin-top:-45%; width:80%; min-height:100px; background:WHITE; color:#444; z-index:1;}
#Page_Alert > .Box_Container > #Page_Alert_Title{position:relative; margin:auto; padding-top:18px; width:90%; font-family:OpenSansBold; color:BLACK; font-weight:bold; font-size:1.2em; z-index:1;}
#Page_Alert > .Box_Container > #Page_Alert_Content{position:relative; margin:auto; margin-top:12px; width:90%; background2:RED; font-size:.9em; z-index:1;}
#Page_Alert > .Box_Container > .Buttons_Container{position:relative; margin:auto; margin-top:24px; width:95%; height:40px; background2:RED; z-index:1;}
#Page_Alert > .Box_Container > .Buttons_Container > .BTN{position:relative; margin-right:13px; min-width:3px; height:30px; color:#0286A4; display:block; float:right; text-align:right; font-size:1.15em; font-family:OpenSansSemiBold;}
.Animate_Opacity
{
transition:opacity .5s;
-moz-transition:opacity .5s; /* Firefox 4 */
-webkit-transition:opacity .5s; /* Safari and Chrome */
-o-transition:opacity .5s; /* Opera */
}
.Animate_MarginTop
{
transition:margin-top .4s;
-moz-transition:margin-top .4s; /* Firefox 4 */
-webkit-transition:margin-top .4s; /* Safari and Chrome */
-o-transition:margin-top .4s; /* Opera */
}
Now all you do is call this function on page load (or when ever you wish to show an alert.
JavaScript
function show_AlertWindow(_title,_content)
{
var Page = document.getElementById('Page_Alert');
var Box = document.getElementById('Page_Alert_Box_Container');
var Title = document.getElementById('Page_Alert_Title');
var Content = document.getElementById('Page_Alert_Content');
Title.innerHTML = _title;
Content.innerHTML = _content;
Page.style.zIndex=15;
setTimeout(function(){ Page.style.opacity=1; },100);
setTimeout(function(){ Box.style.marginTop = 45 +'%'; },400);
}
function hide_AlertWindow()
{
var Page = document.getElementById('Page_Alert');
var Box = document.getElementById('Page_Alert_Box_Container');
Page.style.opacity=0;
setTimeout(function(){ Page.style.zIndex=-1; },200);
setTimeout(function(){ Box.style.marginTop = -45 +'%'; },300);
}
Soooo... if your body tag is like this
<body onLoad="show_AlertWindow('Alert Title','Hello message from alert')">
You will see a sweet dynamic alert box animate onto the screen.
Your welcome! (I practically did all of the work for you)
Related
HTML:
<div id="slideimage">
<img src="file:///android_asset/images/mainpageimage1.jpg" style="width:100%; height:auto; padding-bottom:7px;" >
<img src="file:///android_asset/images/mainpageimage2.jpg" style="width:100%; height:auto;" >
</div>
Script:
window.onscroll = function () { scrollFunction() };
function scrollFunction() {
if (document.body.scrollTop > 700 ) {
$("slideimage").animate({left: '250px'});
}
I have the code above but it doesn't do anything.
I just need a simple code to slide the image.
The problem is that the code is an Android app based on HTML code, not a website, and I'm new to it so I don't know if it works the same.
You are forgetting the hash (#) in the jQuery selector.
window.onscroll = function () { scrollFunction() };
function scrollFunction() {
if (document.body.scrollTop > 700 ) {
$('#slideimage').animate({left: '250px'});
}
}
Check to see if it works right now.
For an android webview application, a dynamic webview page (page A) loads items from local storage correctly when the page A loads for the first time. Then, on Page B another local storage item is added. Then, page A is loaded using window.location.herf= "page A". But, page A does not load the extra local storage item added on Page B. It seems like page A always loads from cache after the 1st time load. This problem happens with any android device or emulator running on any android 4.3 or less operating system.
NOTE:*************
Page A refreshes correctly on an emulator running on android 4.4 or on chrome web.
So... I want a work around for any android OS 4.3 or less.
html.js function that dynamically fills content on page A
function ShowResults(value) {
var overNight = getNetWork(value); /// it the function to get local storage based on value key
document.write('<li><a href="file:///android_asset /SettingEditProgram.html?overnightkey='+value+'">')
document.write('<div class="column">')
document.write('<div class="rectangle"><network>'+ overNight.network + '</network></br>')
document.write('<program>'+ overNight.program +'</program></br>')
document.write('<text>' + overNight.start +'-'+ overNight.end + '</text></br>')
document.write('<text>' + overNight.demo + ', ' + overNight.region + '</text>')
document.write('</div>')
document.write('</div></a></li>')
}
Page A:_________________________
<head>
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='-1'>
<meta http-equiv='pragma' content='no-cache'>
<meta http-equiv="refresh" content="4">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"></script>
<link rel="stylesheet" href="file:///android_asset/style.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js"></script>
<script src="html.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup({ cache: false});
var parameters = $(location).attr('search');
parameter = parameters.replace("?overnightkey=","");
// 'Setting' data-attributes using setAttribute
var newKey = document.getElementById("overnight");
var oldValue = newKey.getAttribute("data-overnight",newKey);
newKey.setAttribute("data-overnight",newKey);
var newKeyvalue ="oldValue="+oldValue+" newValue:"+newKey;
console.log("newKeyvalue");
});
</script>
</head>
<body>
<div data-role="page" id="album-list">
<div id="headerBar">
<img class="goback" src="file:///android_asset/img/ic_goback-web.png">
<img class="appicon" src="file:///android_asset/img/ic_launcher-web.png"><p class="apptitle">Program Setting</p>
<img class="add" src="file:///android_asset/img/ic_add-web.png">
</div>
<div data-role="content">
<ul id="overnight" data-role="listview" data-split-icon="gear" data-split-theme="d" data-overnight="0">
<script>
getIDs().forEach(ShowResults);
</script>
</ul>
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>
page B that set local storage and then re-direct to page A:
$('#savebutton').click(function() {
var keyOverNight = localStorage.getItem("keyOverNightAll");
var keyOverNightArray = new Array();
if (keyOverNight) {
try {
keyOverNightArray = JSON.parse(keyOverNight); // use JSON3 to handle multiple browsers/versions
} catch (e) {
//keyOverNightArray = new Array(); // for parse failure --> return an empty Array
// do nothing
}
}
//Get a new key for setting page based on the local storage
//OvernightKeys
var newKey;
if (keyOverNightArray.length == 0)
{
newKey =1;
}
else
{
newKey= keyOverNightArray[keyOverNightArray.length-1]+1;
}
//Store the overnight key
keyOverNightArray.push(newKey);
localStorage.setItem("keyOverNightAll",JSON.stringify(keyOverNightArray));
//Now store Program values into the newKey
var overnightKey = "overNight"+ newKey.toString();
var jsonOvernight = {"network": NetworkSelected, "program": ProgramSelected, "start": STimeSelected, "end": ETimeSelected, "region": RegionSelected, "demo": DemoSelected }
localStorage.setItem(overnightKey, JSON.stringify(jsonOvernight));
//window.location = "file:///android_asset/SettingHomePage.html";
window.location.href = 'file:///android_asset/SettingHomePage.html?newKey='+newKey;
//window.location.reload(true);
});
Things I tried on Page A
Refreshed every 10 seconds.. It does not read the newest element from local storage.
Set the cache to no content
Set a new data-attribute everytime it comes to this page after adding an item on PageB
tricked page A to load a html.js script with time stamp on it.. eg. html.js?'+timeStamp+'somestring:"
reloads page A. then it runs infinitely.
If I closed the app, and re-run it, it will load the newest localstoarge items again only on the 1st load.
I've tried almost most of the stack over flow help.. Cannot find any answer yet.
check out targetSdkVersion.
I meet same problem. I set targetSdkVesrion to under 16. then sloved.
I want to add Google maps v3 with Geolocation into my jQuery Mobile / PhoneGap Android app but I've some problems:
It locates my position correct, but it's (the radius?) too close. I've changed the value of the radius at my code, but nothing happens. You can see the problem here: http://s7.directupload.net/images/131214/nbc3wudy.png
The second problem concers the height. You can see that at the screenshot too. The maps is too high for the screen, but I don't know how to change it.
And the last problem is this error: /android_asset/www/js/jquery.ui.map.js: Line 46 : Uncaught TypeError: Cannot call method 'apply' of undefined
Here is my code:
index.html
<div data-role="page" id="GPS">
<div data-role="header">
LeftPanel
<h1></h1>
</div>
<div data-role="content" id="map-content">
<div id="map-container"></div>
</div>
<script type="text/javascript">
$('#GPS').on("pagecreate", function() {
var positionOutput = function(position){
var longpos = position.coords.longitude;
var latpos = position.coords.latitude;
$('#map-container').height($(window).height());
$('#map-container').gmap('getCurrentPosition', function(position, status) {
if ( status === 'OK' ) {
var clientPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$('#map-container').gmap('addMarker', {'position': clientPosition, 'bounds': true});
$('#map-container').gmap('addShape', 'Circle', {
'strokeWeight': 0,
'fillColor': "#008595",
'fillOpacity': 0.25,
'center': clientPosition,
'radius': 15,
'clickable': false
});
}
});
};
navigator.geolocation.getCurrentPosition(positionOutput);
});
</script>
</div>
CSS:
#map-content {
padding: 0px;
}
i got a problem with my app.i'm developing an app with cordova & jquery mobile.
Following the code on jquery mobile master i found that code
function openPopup(idPopup, onTimeout) {
var popupContent = '<div data-role="content" data-theme="a" style="border:0px;" class="ui-corner-bottom ui-content centerContent">' +
'<h3 class="ui-title" id="myTitle">Caricamento</h3>' +
'<img src="img/load_shop33sell.gif"/></div>';
var popup = '<div data-role="popup" id="popup-' + idPopup + '" data-overlay-theme="b" data-theme="a" class="ui-content">' + popupContent + '</div>';
$.mobile.activePage.append(popup).trigger("pagecreate");
$("#popup-" + idPopup).on({
popupbeforeposition: function () {
$('.ui-popup-screen').off();
}
});
var fallback = setTimeout(function () {
$("#popup-" + idPopup).popup("open");
}, 3000);
$("#popup-" + idPopup).popup("open");
clearTimeout(fallback);
callback = setTimeout(function () {
$("#popup-" + idPopup).popup('close');
if (onTimeout && typeof (onTimeout) === "function") {
onTimeout();
}
}, 20000);
}
With this code, i am able to open a popup without needing to include a
<div data-role="popup">..../<div>
in each page i create.I just modified a bit adding the popupbeforeposition event to make the popup undismissable by clicking on the background.
Well, it works fine but i got a problem. Randomly in my first page this happens
Seems like the popup opens before it get the right position. In addition i have a second page which is scrollable, and i always have this situation. If i try to scroll up to the top of the page, i have half of the screen black, as in first picture.
What could be the problem?
Thanks in advance, and sorry for my english :)
As you mentioned it is due to data-overlay-theme="a". But actually it should works in good way..thinking that this is due to $('.ui-popup-screen').off();
you can observe here
Prevent JQuery Mobile from closing a popup when user taps outside of it
if you need an alternative way for black background you can do this ..
Add div <div id="overlaypage"></div> like this inside <div data-role="page">
HTML:
<div data-role="page">
<div id="overlaypage"></div>
<div id="header"></div>
</div>
CSS:
.overlaycont {
background:#000;
bottom:0;
left:0;
position:fixed;
right:0;
top:0;
z-index:100;
opacity:.6
}
jQuery:
When you try to click to open a popup addclass
$("#overlaypage").addClass("overlaycont");
When you closing the popup remove class
$("#overlaypage").removeClass("overlaycont");
Working demo: http://jsfiddle.net/nPeaV/7421/
ok, i solved the problem combining the two answers, this is my function to open popup
function apriPopup(idPopup, onTimeout) {
$(".ui-navbar").css('display','none');
var popupContent = '<div data-role="content" data-theme="a" style="border:0px;" class="ui-corner-bottom ui-content centerContent">' +
'<h3 class="ui-title" id="myTitle">Caricamento</h3>' +
'<img src="img/load_shop33sell.gif"/></div>';
var popup = '<div data-role="popup" data-dismissible="false" id="popup-' + idPopup + '" data-theme="a" class="ui-content">' + popupContent + '</div>';
$.mobile.activePage.append(popup).trigger("create");
//$("#popup-" + idPopup).on({
// popupbeforeposition: function () {
// $('.ui-popup-screen').off();
// }
//});
var fallback = setTimeout(function () {
$("#overlaypage").addClass("overlaycont");
$("#popup-" + idPopup).popup("open");
}, 3000);
$("#overlaypage").addClass("overlaycont");
$("#popup-" + idPopup).popup("open");
clearTimeout(fallback);
callback = setTimeout(function () {
$(".ui-navbar").css('display','block');
$("#overlaypage").removeClass("overlaycont");
$("#popup-" + idPopup).popup('close');
if (onTimeout && typeof (onTimeout) === "function") {
onTimeout();
}
}, 20000);
}
as you can see i have commentend the $('.ui-popup-screen').off(); , added a data-dismissable="false"
and i have used the overlaycont css style suggested by dileep.
in my index, as child of body,i added a <div id="overlaypage"></div> and $("#overlaypage").addClass("overlaycont");,
in this way popup is undismissabile by cliking outside of it, and background is displayed correctly.
such a pain!
I'm developing an app with multiple input[type=numer] elements. Android only for now.
The built-in numeric keyboard has two problems:
* it's inconsistent (different on different versions of Android)
* it has unnecessary keys (space, dash, comma and "next") which add confusion.
I'd like to have a keyboard with just numbers, comma and backspace. Is that possible?
Edit Oct 3, 2013. A third problem appeared and it's by far the worst. It looks like Samsung decided to skip the decimal character (".") from their numeric keyboard, at least the one that pops when input[type=numer] gets the focus in the browser. It seems all Galaxy S4 devices are affected (I've seen it on the S4 Mini, I don't have access to many Samsung devices... all I see are Nexus lovers :-)). I couldn't find much about the issue in Google, but I've seen Galaxy S4 users complain about it in 2012 (I've tried it on one S3 a few weeks ago and it was OK).
Long story short, after a careful consideration I decided to implement my own keyboard in html/javascript (Samsung is too important, I'm getting bad reviews just because of it and I don't think I can do anything to fix it). I'm in the process of rewriting my app, I'll try to remember and tell the story when I'm done.
Edit Dec 3, 2013. My current solution (still in alpha stage, the app rewrite takes me way longer than I expected) is a keyboard implemented entirely in javascript. I used regular <span> elements instead of <input> to prevent OS keyboard from popping out. As an added benefit, I get to control everything about the keyboard, so I added a few arithmetical keys (x, -, *, /, ( and )) and the user can type in expressions, for example "3x(2+5.5)" instead of "15". I'll link to the app when it's ready (still at least a few more weeks).
Sure it is.
First, configure your activity to never show the keyboard (try android:windowSoftInputMode = "stateAlwaysHidden"). You may have some problems if EditText insists on pulling it up, but you can make a mock EditText based on TextView to go around that, or inherit EditText and override some methods. There are multiple guide on that, like here: Close/hide the Android Soft Keyboard
Second, create your own UI-keyboard element, with any buttons you want in however layout you want, and catch button presses on this keyboard, for each press, append the appropriate character to the EditText/TextView's displayed text.
That said, users may not like it. As much as you hate that keyboards look differently for each device, each user is used to his own keyboard, and expects to see it when editing text. I urge you to reconsider.
Thanks for the update. Here is how I'm implementing it. It might be similar to how you are doing it. I'd be curious what issues you've run into so far.
I haven't moved this to production yet so still testing but it seems to work well so far. I've removed some validations from the code below to make it much shorter...
Basically the keyboard is 1 line on the iPad and 2 lines on the phone. It supports any input field with the class "keyboard" and highlights the entire ".keyboard-item" so it is clear to the user which field they are updating.
<div id="stuff">
<ul>
<li> <label for="name">Name</label> </li>
<li> <input type="text" id="name" class="required"/> </li>
</ul>
<ul class="keyboard-item">
<li> <label for="number">#</label> </li>
<li> <input type="text" id="number" class="keyboard required" pattern="[0-9]*" readonly="readonly" onkeypress="dosomething(this)"/> </li>
</ul>
</div>
<div class="mobile-number-keyboard">
<div class="mobile-number-keyboard1"> <span style="padding-left: 20px;">0</span> <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span style="padding-right: 20px;">5</span> </div>
<div class="mobile-number-keyboard2"> <span style="padding-left: 20px;">6</span> <span>7</span> <span>8</span> <span>9</span> <span style="width: 8px;">.</span> <span style="padding-right: 20px;"><</span> </div>
</div>
<style>
.mobile-number-keyboard { width: 101%; height: 40px; margin: auto; margin-bottom: 20px; }
body.phone .mobile-number-keyboard { height: 80px; }
.mobile-number-keyboard span { float: left; padding: 8px 22px; border: 1px outset White; cursor: pointer; background-color: #4F81BD; color: White; }
.mobile-number-keyboard span:hover { background-color: #87CEFA; }
.mobile-number-keyboard span:active { border-style: inset; background-color: #00E5EE; }
body.phone .mobile-number-keyboard2 { clear: both; height: 40px; }
.keyboard-focus { background: #FFC1C1; border: 1px solid red; }
.keyboard-item-focus { background: #00E5EE; }
</style>
<script>
function initCustomKeyboard(jContainer) {
jContainer.find('input, select, textarea').click(function() {
$('.keyboard-focus').removeClass('keyboard-focus');
$('.keyboard-item-focus').removeClass('keyboard-item-focus');
var me = $(this);
if (me.hasClass('keyboard')) {
me.addClass('keyboard-focus');
var parent = me.parent();
if (parent.hasClass('keyboard-item')) {
parent.addClass('keyboard-item-focus');
} else {
parent = parent.parent();
if (parent.hasClass('keyboard-item')) {
parent.addClass('keyboard-item-focus');
} else {
parent = parent.parent();
if (parent.hasClass('keyboard-item')) {
parent.addClass('keyboard-item-focus');
}
}
}
}
});
jContainer.find('.mobile-number-keyboard').find('span').click(function() {
var me = $(this);
var val = me.text();
var box = jContainer.find('.keyboard-focus');
var bval = box.val();
var blen = bval.length
if (box.length > 0) {
if (val === '<') {
if (blen === 0) { return; }
if (blen > 1 && bval.substring(blen-2, blen-1) === ' ') {
box.val( bval.substring(0, blen - 2) );
} else {
box.val( bval.substring(0, blen - 1) );
}
var whichCode = 8;
} else {
var max = box.attr('maxlength');
var whichCode = val.charCodeAt(0);
if (max === undefined || parseInt(max) > blen) {
box.val(bval + val);
} else {
return;
}
}
var ev = $.Event('keydown');
ev.which = whichCode;
box.trigger(ev);
ev = $.Event('keypress');
ev.which = whichCode;
box.trigger(ev);
ev = $.Event('keyup');
ev.which = whichCode;
box.trigger(ev);
}
});
}
$(function() { initCustomKeyboard('#stuff'); }
</script>