I`m just trying to pass values from my app to the webview using the examples from android developer page, throught javascript.
My webview is set with:
WebView navegador;
final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(this);
navegador.getSettings().setJavaScriptEnabled(true);
navegador.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
navegador.addJavascriptInterface(myJavaScriptInterface, "navegador");
navegador.loadUrl(url);
Right under it i create the JavaScriptInterface class:
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
System.out.println("FaceWeb -> Navegador.java -> JavascriptInterface");
mContext = c;
}
public String getLogin(){
System.out.println("FaceWeb -> Navegador.java -> getLogin: "+b.getString("login"));
return b.getString("login");
}
public String getNome(){
System.out.println("FaceWeb -> Navegador.java -> getNome: "+ b.getString("nome"));
return b.getString("nome");
}
public Integer getId(){
System.out.println("FaceWeb -> Navegador.java -> getId: "+ b.getInt("id"));
return b.getInt("id");
}
}
And here my html:
<body>
<div id="teste">
Parado.
</div>
<input type="button" onclick="leitura()" value="Buscar Valores" />
<script type="text/javascript">
function leitura()
{
document.getElementById("teste").innerHTML = "Aguarde...";
var fonte = navegador.getLogin();
var id = navegador.getId();
var nome = navegador.getNome();
document.getElementById("teste").innerHTML = "Login: "+fonte + "<br>Nome: "+nome+"<br>ID: "+id;
}
</script>
</body>
In Eclipse log i can see that the functions getLogin, getId and getNome are called when the button is pressed on the webview, with right values, but my div "teste" remains with "Aguarde..." only and the button itself remains 'pressed'.
Any ideas please, reply. I really don`t know where to look anymore.
Try with public int getId() instead of Integer. Try with calling getLogin and getNome only. See if getId is the problemmaker. If you comment the last innerHtml out, does the button come up then?
Related
Here I have created dynamic dropdown list using this link, but when I select some value from available list it should be called in action class.
The dropdown list which can be seen in the image ,here the values are loaded dynamically from the database and now what I want is when I select any value from that two dropdown list that values (I mean text value) should be sent to the action class and there I will execute one JDBC select query on the basis of this two values and will display in the table shown in the image but everything should be on load.Action should be on selecting values from dropdown list not on any button click .With static values I am able to call value from dropdown list into action class with name attribute.But in this case I cannot :(
I hope I am clear now .
I have tried calling select tag using listkey,name and id but none of them worked .
Below is my JSP code:
<div>
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:form action="ActionSelect">
<s:submit value=" Click Here"/>
</s:form>
<div>
Action class for loading dynamic dropdown list :
package com.ca.actions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.ca.database.Database;
import com.ca.pojo.Event;
import java.sql.PreparedStatement;
import com.opensymphony.xwork2.ActionSupport;
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
List<Event> dataForBillsJspList;
private List state = new ArrayList();
private List status = new ArrayList();
String eventName;
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public RetrieveEvNaCoNaAction() {
// TODO Auto-generated constructor stub
}
public List<Event> getDataForBillsJspList() {
return dataForBillsJspList;
}
public void setDataForBillsJspList(List<Event> dataForBillsJspList) {
this.dataForBillsJspList = dataForBillsJspList;
}
public List getStatus() {
return status;
}
public void setStatus(List status) {
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_NAME,COMPANY_NAME,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo FROM EVENT");
ResultSet rs = ps.executeQuery();
//dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
/*dataForBillsJspList.add(new Event(rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo")));
System.out.println(rs.getString("EVENT_NAME"));*/
status.add(rs.getString("COMPANY_NAME"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
}
public List getState() {
return state;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
setState(this.state);
setStatus(this.status);
return "success";
}
public String showEventDetails(){
System.out.println("Hi.."+eventName);
return SUCCESS;
}
public void setState(List state) {
//implement the application specific logic to
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_ID,EVENT_NAME,COMPANY_NAME,CONTACT_PERSON,CONTACT_NO,EMAIL_ID,EVENT_VENUE,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME FROM EVENT");
ResultSet rs = ps.executeQuery();
dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"),rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),rs.getString("EVENT_VENUE"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo"),rs.getString("EVENT_TIME")));
//System.out.println(rs.getString("EVENT_NAME"));
state.add(rs.getString("EVENT_NAME"));
System.out.println(rs.getString("EVENT_ID"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
//Here for displaying the data on UI, we are using few hardcoded values//
}
}
After loading dynamic dropdown list now i am trying to call selected value in action class by S.O.P but it gives null pointer exception. Below is my POJO class:
package com.ca.pojo;
public class Dropdown
{
private String eventState;
private String companyState;
public Dropdown() {
// TODO Auto-generated constructor stub
}
public String getEventState() {
return eventState;
}
public void setEventState(String eventState) {
this.eventState = eventState;
}
public String getCompanyState() {
return companyState;
}
public void setCompanyState(String companyState) {
this.companyState = companyState;
}
}
and below is action class where I am trying to call that selected value by using name attribute :
package com.ca.actions;
import com.ca.pojo.Dropdown;
import com.opensymphony.xwork2.ActionSupport;
public class DropdownAction extends ActionSupport
{
Dropdown dp;
public DropdownAction() {
// TODO Auto-generated constructor stub
}
public Dropdown getDp() {
return dp;
}
public void setDp(Dropdown dp) {
this.dp = dp;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println(dp.getEventState());
return "success";
}
}
struts.xml is properly configured. Now after selecting two values I want to display data in the below table accordingly without any button click but in jsp i have created button just to see whether i am getting the selected value in action class but in actual i want it without any button click.
Well, there is a huge mess here :D
First of all, the NullPointerException is thrown because the values are not sent, and the values are not sent because they're not in the form.
You should enclose them in the form like this for them to be sent to the ActionSelect action:
<s:form action="ActionSelect">
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:submit value=" Click Here"/>
</s:form>
Solved the mistery, this doesn't solve your problem, though.
You have two main ways to contact actions from a page:
Using a standard submit (as you're doing):
you either submit a form with its content, or call a link by eventually passing parameters in the querystring. This creates a Request, that will contact an action, that will return an entire JSP, that will be loaded in place of the page you're on now.
Using AJAX:
you POST or GET to an action without changing the current page, and the action can return anything, like a JSP snippet, a JSON result, a binary result (through the Struts2 Stream result), etc...
You then can choose what to do with the returned data, for example load it inside a <div> that before was empty, or had different content.
Now your problem is that you're contacting an action that is not the one you're coming from (is not able to re-render the entire JSP you're on) and you're calling it without using AJAX, then whatever the object mapped to the "success" result is (the whole JSP, or a JSP snippet), it will be loaded in place of the JSP you're on, and it will fail.
Since you seem to be quite new to this, I suggest you start with the easy solution (without AJAX), and after being expert with it, the next time try with AJAX.
That said,
avoid putting logic in getters and setters;
avoid calling methods that are not setter as setters (setState, setStatus...);
always make your attributes private;
try giving speaking names to variables: state and status for event states and company states are really confusing; and what about "state" instead of "name" (in jsp and on DB is "name");
consider loading informations like selectbox content in a prepare() method, so they will be available also in case of errors;
you're not closing the connections (and BTW it would be better to use something more evoluted, like Spring JDBC, or better Hibernate, or even better JPA, but for now keep going with the raw queries)
The following is a refactoring of your code to make it achieve the goal. I'll use #Getter and #Setter only for syntactic sugar (they're Lombok annotations, but you keep using your getters and setters, it's just for clarity):
<head>
<script>
$(function(){
$("#event, #company").on('change',function(){
$("#myForm").submit();
});
});
</script>
</head>
<body>
<form id="myForm">
<div>
...
<s:select id="event" name="event" list="events" />
...
<s:select id="company" name="company" list="companies" />
...
</div>
</form>
<div>
...
Table - iterate **dataForBillsJspList** here
...
</div>
</body>
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
#Getter private List<Event> dataForBillsJspList = new ArrayList<Event>();
#Getter private List<String> events = new ArrayList<String>();
#Getter private List<String> companies = new ArrayList<String>();
#Getter #Setter private String event = null;
#Getter #Setter private String company = null;
#Override
public void prepare() throws Exception {
Connection con;
try {
con = new Database().Get_Connection();
// load companies
PreparedStatement ps = con.prepareStatement("SELECT DISTINCT company_name FROM event");
ResultSet rs = ps.executeQuery();
while (rs.next()) { companies.add(rs.getString("company_name")); }
// load events
ps = con.prepareStatement("SELECT DISTINCT event_name FROM event");
rs = ps.executeQuery();
while (rs.next()) { events.add(rs.getString("event_name")); }
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
}
#Override
public String execute() {
Connection con;
try {
con = new Database().Get_Connection();
// load the table. The first time the table is loaded completely
String sql = "SELECT EVENT_ID, EVENT_NAME, COMPANY_NAME, CONTACT_PERSON, CONTACT_NO, EMAIL_ID, EVENT_VENUE, " +
"date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom, date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME " +
"FROM event";
String where = "";
// if instead this action has been called from the JSP page,
// the result is filtered on event and company:
if (event!=null && company!=null) {
where = " WHERE event_name = ? AND company_name = ?";
}
// load companies
PreparedStatement ps = con.prepareStatement(sql + where);
if (where.length()>0) {
ps.setString(1,event);
ps.setString(2,company);
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),rs.getString("COMPANY_NAME"),
rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),
rs.getString("EVENT_VENUE"), rs.getString("dateAsFrom"), rs.getString("dateAsTo"),
rs.getString("EVENT_TIME")));
}
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
return SUCCESS;
}
}
It is a kickoff example, but it should work.
The next steps are:
create a POJO with id and description, show the description in the select boxes, but send the id
use header values ("please choose an event"...) and handle in action conditional WHERE (only company, only event, both)
PAGINATION
Good luck
Using Javascript/jQuery you can do this, it depends on what you want to do after reached action class.
If you want to navigate to another page use the code below.
Add onchange event as an attribute to your dropdown,
onchange="customFunction(this.value)"
create customFunction in header part,
function customFunction(selectedValue){
window.location="Action_URL?myValue="+selectedValue;
}
Or if you want to return back the same page use jQuery ajax,
$("#eventName").change(function(e){
var selectedValue = $(this).val();
$.ajax({
type : 'post',
url : 'Action_URL',
data: { myValue: selectedValue},
success : function(data) {
alert(data);
console.log(data);
}
});
});
Hope this helps.
I got a string replace issue when I pass Java String into android webView through JavaScriptInterface.
Below is the HTML (utf-8 file) inside the webView:
<html>
<head>
<script type="text/javascript">
a=window.MyAndroid.getPicEncStr(); //get string from Java side.
function getValue(){
b="ue";
if(a==b) {
d="match";
} else {
d="not match";
}
c=d+":"+a.replace("u","0")+b.replace("u","0");
document.getElementById("test").innerHTML=c;
}
</script>
</head>
<body>
<span id="test">test</span>
</body>
</html>
JavaScriptInterface code are below:
import java.io.UnsupportedEncodingException;
import android.content.Context;
public class JavaScriptInterface {
private String unicodeToUtf8(String s) {
String str=null;
try {
str=new String( s.getBytes("utf-8") , "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public String getPicEncStr() {
//return "ue"; //not work
return this.unicodeToUtf8("ue"); //not work
}
}
The result in span("id"="test") is "match:ue0e" when I call webView.loadUrl("javascript:getValue()") no matter I convert from "unicode" to "utf-8" or not.
Basically string "a" equals to string "b", but the replace function doesn't work on a, only works on b.
Could someone help me with that?
Thanks.
It seems I find a way to solve the problem:
<html>
<head>
<script type="text/javascript">
a=window.MyAndroid.getPicEncStr(); //get string from Java side.
function getValue(){
b="ue";
if(a==b) {
d="match";
} else {
d="not match";
}
a=new String(a); //<-- force convert java string to javascript string.
c=d+":"+a.replace("u","0")+b.replace("u","0");
document.getElementById("test").innerHTML=c;
}
</script>
</head>
<body>
<span id="test">test</span>
</body>
</html>
Still don't understand why. When I dump "a", it shows "ue", when I try to dump "a[0]", it shows "undefined", however "b[0]" is "u", I only can image Java/Javascript string are not compatible with each other, so, a explicit conversion is necessary.
I want to pass textfield with id value pat to the getautocomplete.action in Struts 2. Here I am using TINY.box to pop up the next page.
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
T$('tiny_patient').onkeypress = function(){
TINY.box.show('getautocomplete.action',1,0,0,1)
}
</script>
You need to append the id pat and its value to the url that you pass to the show function. For example
var url = 'getautocomplete.action?pat=' + $("#pat").val();
You can then use the variable url in your show function.
You also need to add the following in your action class. This also depends on the java type of pat. I am using String,
private String pat;
public String getPat()
{
return pat;
}
public void setPat(final String value)
{
this.pat = value;
}
Note
It is recommended to get your url using the following instead of hard-coding the extension
<s:url id="url_variable" namespace="/namespace_of_action" action="action_name" />
var url = '<s:property value="url_variable" />?pat=' + $("#pat").val();
If you are trying to populate the box based on previous box selection or any server side process you have to use ajax.
In your action class , write a getter-setter for variable named "pat" like this:
private string pat;
public getPat()
{
.........
}
public setPat(String pat)
{
this.pat=pat;
}
and change
TINY.box.show('getautocomplete.action',1,0,0,1)
to
TINY.box.show('getautocomplete.action?pat="xyz"',1,0,0,1)
Hope this will solve your problem unless you have an idea about ajax.
Try
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
document.getElementById("tiny_patient").onkeypress = function(e){
TINY.box.show("<s:url action='getautocomplete'/>"+"?pat="+document.getElementById("pat").value,1,0,0,1)
}
</script>
Can anyone teach me or direct to a working example to satisfy this requirement.
Scenario:
List item My Web App is using spring mvc.
One of the services it provides is that when the user clicks on a button a long running process will occur on the server. (Query database, write files, write logs, etc...) this process can take a few seconds or a few minutes.
*Problem***
How can I implement the service to update the client of its progress.
The service returns true or false if the process was successful.
Thanks for your replies. A code snippet or a complete tutorial will be most helpful.
Here is a possible solution to this progress bar problem:
task.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<script src="../js/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON(window.location.href.concat('/status'), function(data) {
if (data === "created") {
} else {
// task is already being executed
refreshProgress();
}
});
});
var width = 0;
function getProgress() {
$.getJSON(window.location.href.concat('/progress'), function(percentage) {
$('#progressBar').css('width', percentage+'%');
document.getElementById("label").innerHTML = percentage * 1 + '%';
width = percentage;
});
}
function start() {
$.ajax({
type: "post",
data: $('#task').serialize(),
success: function(data) {
$('#progressBar').css('width', 100+'%');
document.getElementById("label").innerHTML = 100 * 1 + '%';
// do sth with the data after finished task
}
});
width = 0;
$('#progressBar').css('width', 0+'%');
document.getElementById("label").innerHTML = 0 * 1 + '%';
refreshProgress();
}
function refreshProgress() {
$("#btnStart").prop("disabled",true);
var id = setInterval(frame, 1000);
function frame() {
if (width >= 100) {
clearInterval(id);
$("#btnStart").prop("disabled",false);
} else {
getProgress();
}
}
}
</script>
</head>
<body>
<div class="container">
<h2 class="text-center">Progress Bar Example</h2>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:0%">
<div id="label">0%</div>
</div>
</div>
<form:form method="POST" commandName="task" cssClass="form-horizontal">
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="btnStart">Actions</label>
<div class="col-md-8">
<button id="btnStart" name="btnStart" class="btn btn-success">Start</button>
<button id="btnStop" name="btnStop" class="btn btn-danger">Stop</button>
</div>
</div>
</fieldset>
</form:form>
</div>
<script>
$('#task').submit(function () {
start();
return false;
});
</script>
</body>
</html>
TaskController.java
#Controller
#RequestMapping(value = "/task")
public class TaskController {
private Task task;
#RequestMapping("")
protected ModelAndView page() {
ModelAndView model = new ModelAndView(VIEW_DIR + "task");
if (this.task == null) {
this.task = new Task();
}
model.addObject("task", this.task);
return model;
}
#RequestMapping(value = "/status", method = GET)
public #ResponseBody
String getStatus() {
return task.getStatus();
}
#RequestMapping(value = "/progress", method = GET)
public #ResponseBody
int getProgress() {
return task.getProgress();
}
public ModelAndView form(#ModelAttribute Task task) {
this.task = task;
ModelAndView model = new ModelAndView(VIEW_DIR + "task");
task.execute();
model.addObject("task", this.task);
return model;
}
}
Task.java
public class Task {
private int total;
private int progress;
private String status;
public Task() {
this.status = "created";
// TODO get total here or pass via form
}
public void execute() {
status = "executing";
int i = 0;
while (i < total && status.equals("executing")) {
progress = (100 * (i + 1) / total);
i++;
}
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
There are a good number of ways to handle a scenario like this. One way is to model the work in terms of a "Process", which contains a "status", including a percentage completion.
If you imagine what this might look like on a website, clicking the button to start the process would submit a form that begins the process and assigns some sort of identity to the process, almost like if you were creating any other sort of object. It would then redirect you to a "process status" page.
The process status page would query for the status of the process and display it. It'd probably have a URL parameter for the process's ID. It would perhaps update itself using an AJAX call to return a progress percentage.
On the backend, you now need to solve a couple of problems: finding out the current status of process N, and updating the status of process N. You could accomplish this in a number of ways, including storing the progress in the database or having some sort of in-memory table of running jobs. You could also use some sort of heuristic to estimate a percent. For example, if it's a "register new user" job, maybe it's 20% done if the user's table has an email address, 40% done if the user avatar table has data in it for this user, etc. I don't recommend this as much.
I have defined in my head tag a function <script> functionX(a,b,c) ....</script>
which calls some third party js. The actual function is this:
<script>
function fbc(d, s, id)
{ var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}
</script>
and later on I want to call that function. I'm calling it using and HTML widget in the following way:
HTML html = new HTML();
setHTML(
"<script>"+
" fbcomment(document, 'script', 'facebook-jssdk'); "+
"</script> "+
"<fb:comments width=\"600\" num_posts=\"2\" href=\"http://www.woojah.com\"></fb:comments>");
However, it is not executing properly. Any advice would be very useful.
It is more idiomatic to call external functions using JSNI:
native void facebookComment(Document d, String s, String id) /*-{
fbc(d, s, id);
}-*/;
void myFunction() {
facebookComment(Document.get(), "script", "facebook-jssdk");
}