Passing a Javascript Variable to Android Activity? - java

Basically I want get data I already have accessed from javascript and passing it to Java/Android so that I can work with it there.
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface {
#SuppressWarnings("unused")
public void setX(String html){
Activity.this.x = html;
Toast.makeText(myApp, Activity.this.x, Toast.LENGTH_LONG).show();
}
}
this works but I want to be able to call the same Toast line anywhere and get the same result. Currently it only returns null/empty when not called through loading through webview.loadUrl("Javascript:"...
Any tips?

You can not access stored javascript variables, you must do it through a function call.
You have to call it from javascript in your html page, for example:
TheNameOfYourInterface.setX('value');
TheNameOfYourInterface will be a javascript object when you add the interface to the webview via
YourWebView.addJavascriptInterface(new MyJavaScriptInterface(),"TheNameOfYourInterface");
so you can do the logic on your webview and call the interface when you set the data so the method in the Java side will be called.

I found a different solution to what I need, and I feel like it works for all who do not need get a value calc'd by javascript. My solution to my need was to HTTP GET the html/javascript and then parse it as a string. It saves me some time by not needing to load X WebViews and then (re)creating all my functions in the JavaScript Interface.

I think it will be a good idea to store the HTML in Shared Preferences ,which is a form of persistent storage.This way you will be able to access it from anywhere.
//------get sharedPreferences
SharedPreferences pref = context.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
//--------modify the value
pref.edit().putString("ToastString", html).commit();
//-------get a value from this from anywhere
String toastValue=pref.getString("ToastString", "");

Related

Call Java from Javascript with GWT JNSI

How do I call a Java method from Javascript? I tried the following
http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#calling
But it is not working. I can't put the JS into Java file because the library uses a callback. In my App.html file:
function pickerCallback(data) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var name= doc[google.picker.Document.NAME];
var fileId = data.docs[0].id;
// set the path text field
//[instance-expr.]#class-name::field-name
//[instance-expr.]#class-name::method-name(param-signature)(arguments)
// Call static method
//#com.onix.sdm.client.SDM_Mailer::setSelectedFolder(Ljava/lang/String;Ljava/lang/String;)(name, fileId);
$entry(#com.onix.sdm.client.SDM_Mailer::setSelectedFolder(name, fileId));
}
In SDM_Mailer.java:
private static void setSelectedFolder(String folder, String id) {
SDM_Mailer myThis = SDM_Mailer.getInstance();
myThis.textFolder.setText(folder);
myThis.folderId = id;
}
When I load the app, in gives this error in the browser console:
Uncaught SyntaxError: Unexpected token ILLEGAL
On this line:
$entry(#com.onix.sdm.client.SDM_Mailer::setSelectedFolder(name, fileId));
I also tried the line immediately before that (commented for now), which also gave the same error.
I can't put the JS into Java file because the library uses a callback
That's by design - the purpose of this syntax is not to expose methods where they can be called by external JS, but instead to let you call it from within JSNI. This is because the JSNI can be modified to actually call the java method.
If you want to call Java/GWT methods from in plain js, you must expose them for this. You linked http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#calling, but didn't actually use the important part:
public static native void exportStaticMethod() /*-{
$wnd.computeLoanInterest =
$entry(#mypackage.MyUtilityClass::computeLoanInterest(IFI));
}-*/;
This is the important piece - you must expose the function to where the outside JS can call it, but you must do this exposing from within a JSNI func. Note that we are not calling the function here, just referring to it.
I think you missed the Type Parameter:
$entry(#com.onix.sdm.SDM_Mailer::setSelectedFolder(Ljava/lang/String;Ljava/lang/String;)(name, fileId));
JSNI is well explained at DevGuideCodingBasicsJSNI

Getting raw HTML / adding Javascript to WebView pages

I have a mobile flow for registration that I want to use in my app, and I do not have control of the source --
I am looking for a way to grab a few pieces of data when the user finishes registering, (confirmation number, etc.) that will be sent to my app (hopefully via Android's addJavascriptInterface)
I am certain on one thing - the id of the element I need. The flow could change, and is already a few pages long, So I'm looking for a general solution. The basic Idea I'm hoping for is this:
Inject a JavaScript snippet to each page during shouldOverrideUrlLoading, which will automatically call my JavaScript Interface and check for the value of the field with the id I'm looking for. (or just return the entire HTML, and I'll do it in Java)
view.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//inject javascript here to get value
return false;
}});
I've seen tutorials on using addJavascriptInterface, but they all seem to assume some control or understanding of the 'single' page that will be navigated to. Since I have a potentially lengthy flow (3+ pages) and no control over the source, I am interested in hearing any suggestions.
Check URL of the current page and if it's the right one insert JavaScript in the curent page. With the help of Java-JS binding you could get some data out. See my previous answer: Determine element of url from webview shouldOverRideUrlLoading

Android - Easiest way to pass values from HTML or Javascript to Java?

I need to pass some simple values from HTML or Javascript to Java. I have reviewed all the documentation but can't find a straight forward way.
I have a HTML form with a couple of values that are needed in Java. I'm already calling Java from Javascript just not sure how to get the data the other way around.
For instance Java is emailing a local file for me. I need to tell Java the name of the file which is named in Javascript by document.getElementById('CompanyName').value + .html.
How can I do this?
Here is the current Java code I'm using to email the file: (I need all the "test" phrases to be replaced by values from the form.)
public class JavaScriptInterface {
private WebView mAppView;
private DroidGap mGap;
public JavaScriptInterface (DroidGap gap, WebView view)
{
mAppView = view;
mGap = gap;
}
public void doEmail(){
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/html");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT,"test text");
sendIntent.putExtra(Intent.EXTRA_SUBJECT,"test subject");
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file:///sdcard/test co.html"));
mGap.startActivity(sendIntent);
}
}
Just add a parameter. In your case I'm assuming that your JavaScript already calls doEmail(). Change the signature to something like doEmail(String filename), use the parameter in the Java method, and when you call it, pass the parameter like:
window.whateverYouCalledThis.doEmail(document.getElementById('CompanyName').value + '.html');

simple example of native app passing string to website?

Can somebody give a simple example for java code of a native app passing a string to a website?
For example: when a string has the value Hello everybody, the text Hello everybody should get pasted into the Google search field.
For the most simple use, you can try:
public static void browseURL(Activity activity, String url)
{
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
}
catch (Exception e)
{
message(activity, "Sorry, failed to view the desired page.");
}
}
and then call:
browseURL("http://www.google.com/search?q=Hello+World")
Do you want to fill the fields and submit them? If so, just do the request with the request parameters filled, and parse the response given by the server. Look into Apache HttpClient.
You don't actually have to add text to the Google search field explicitly. You can send a URL with a query string.
Depending on the website the query string will always be different. For Google it is http://www.google.ca/search?q=something . Anything after a ? is considered a query string which any good web developer will include in a webpage. That query string takes custom commands in the form of ?command=query for command&command2=query for command 2.
Since this is tagged blackberry, I assume you want to implement a blackberry app, and you don't explicitly explain what you want to do, so you have two options,
Invoke the browser
On that page it describes how to open a browser session. So within the
browserSession.displayPage("http://http://www.google.ca/search?q=searching%20for%20something");
If you need a class for URL encoding, let me know and I'll send one your way.
Http Request to pull the html of the webpage into the code. To do that, you'll have to look at my blog this week as I'll be posting a full in code network class either tomorrow or tuesday, which I'll edit this post to contain a link to.
OR you can send me a message if you need it NOW and I can email the non-cleaned up code to you.

how to access inner class field inside javascript

I am having a inner class(static) named SelectProdLineAssociationForm
I have also given a declaration like this--
public SelectProdLineAssociationForm selectProdLineAssociationForm =
new SelectProdLineAssociationForm();
now on onclick event I want to set the field in the inner class a value
so i am
document.forms[0].selectProdLineAssociationForm.selectedProdLineAssociationKey =
selectedProdLineAssociationKey;
where selectedProdLineAssociationKey is passed in javascript method
then it giving javascript error that
document.forms[0].selectProdLineAssociationForm is undefined
can any one plz tell me why and how it can be resolved
you cannot access a java method or property from javascript. Javascript is purely client side.
one way you can do this is to print the property into a block, and then you can access it from javascript, e.g.:
<script>
var selectedProdLineAssociationKey = '<%= SelectProdLineAssociationForm.selectProdLineAssociationForm.toString();=%>';
//...you can then use this variable else where in your script block
</script>
But you will not be able to change the value, unless you POST it back (and have the logic to change it on the serverside).
I am going for Struts here ... (as Massimiliano Fliri said, you have to provide more details).
You have to verify how your input tags were named in the HTML. Depending on how you wrote your JSP you might have an input tag named selectProdLineAssociationForm.selectedProdLineAssociationKey (one element).
This code :
document.forms[0].selectProdLineAssociationForm.selectedProdLineAssociationKey
says that your form contains selectProdLineAssociationForm that in turn contains selectedProdLineAssociationKey (two elements).
This is just a guess of what you are doing. You must provide more info if you want more help.

Categories

Resources