I have this javascript code:
<html>
<head>
<script>
for(i=0;i<6;i++)
{
document.write("my number is "+ i );
}
</script>
</head>
</html>
I want to take the output of this javascript code and save in String in android.
like this:
my number is 0my number is 1my number is 2my number is 3my number is 4my number is 5
How can i do this in android?
There are a lof of topic already opened/answered for this question.
Check these links
using javascript in android webview
Android Calling JavaScript functions in WebView
Basic is binding your WebView injecting a javascript into the webpage, then you can call your java function in webpage with normal javascript.
Related
This is my controller:
#GetMapping("/getRandomWildSwimming")
public List<WildSwimming> getRandomWildSwimming() {
return wildSwimmingService.getRandomWildSwimming();
}
How I can access it with HTML? I'm confused, I saw some tutorials where I set return index.html for example, but I'm returning here actually service that show me collection data from Mongo in JSON when I send request for example: http://localhost:8080/wildswimming/getRandomWildSwimming page show me one collection from mongo in JSON format, how I can show that via html and stylize it a bit?
If you want to use this approach, you need a client. For example, you can use JS or PHP for it.
Then you need to create HTML pages, add scripts (using JS or PHP) to send requests, get responses and show it to user.
This looks like: user opens page -> client sends request to your spring controller -> spring controller returns response -> client gets and shows it to user.
OR
You can use Spring MVC if you do not how to launch client server.
You will need to add a dependency to your project so that spring boot knows how to convert an object into json. If you're using maven, add com.fasterxml.jackson.core:jackson-databind to your pom file.
Then, add the #ResponseBody annotation to the getRandomWildSwimming method so that it ends up looking like this...
#GetMapping("/getRandomWildSwimming")
public #ResponseBody List<WildSwimming> getRandomWildSwimming() {
return wildSwimmingService.getRandomWildSwimming();
}
This will make the controller respond with json when it is called in a web browser.
Assuming that it returns JSON that looks like this...
[{"rating":89},{"rating":24},{"rating":68}]
You can using the $.get function (from the jquery library), to make a call to the /getRandomWildSwimming api method, which will fetch the JSON and automatically convert it into a javascript array of objects...
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="resources/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Wild Swimming Records</h1>
<ul id="canvas">
</ul>
<script type="text/javascript">
$(document).ready(function(){
$.get("./getRandomWildSwimming", function(data) {
console.log(data[0].rating);
console.log("JSON: " + JSON.stringify(data));
$.each(data, function(index, value) {
$("#canvas").append("<li>" + value.rating + "</li>");
});
});
});
</script>
</body>
</html>
This should result in a page that looks something like this...
Wild Swimming Records
- 89
- 24
- 68
The first console.log line will take the rating property of the first object in the data array and print it to the browser console. The second console.log line will convert the entire array back into a json string and print it to the browser console.
I'm currently trying to show one Youtube user playlist in my Android app but it's all a tough problem.
Anyway, I had an idea but I can not get it to work. It would be using a WebView and its loadDataWithBaseURL() method, so I can parse the actual html/javascript code to show the playlist, and then show it within the WebView. After trying to do it myself without success, I finally found this working code here on Stack Overflow:
<head>
<script>
function load() {
var playListID = "YOUR_PUBLIC_YOUTUBE_PLAYLIST_ID";
var requestOptions = {
playlistId: playListID,
part: 'snippet',
maxResults: 10
};
var apiKey = "YOUR_API_KEY";
gapi.client.setApiKey(apiKey);
gapi.client.load('youtube','v3', function () { var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function (data) { console.log (data) });
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
</head>
<body>
</body>
What I do is to store this code into a String and then I pass this String to the loadDataWithBaseURL() method like this:
myWebView.loadDataWithBaseURL(baseUrl, code, "text/html", "UTF-8", null);
Where baseUrl is "https://www.googleapis.com/youtube/v3/" and code is a String containing the html-javascript code mentioned above.
The problem that I'm having is that I don't see anything in myWebView, it keeps being blank. It doesn't load. Moreover, I'm trying to make this code work in a html file but when I open it with my browser, once again it doesn't load. The API and the Playlist Keys are set fine, so in advice I can say it's not the cause of the problem.
Thanks and any help will be appreciated.
Well, after so many time trying to get this to work it seems that my mind was pretty confused. It finally was a lot simpler than that. I don't even know why I came up with the Javascript idea when, as I'm using a WebView, I can directly load the playlist's url with the loadUrl("http://youtube.com/USER_PLAYLIST...") method.
If I use:
String plain = Html.fromHtml(html).toString;
to render simple 'html' that contains:
<!doctype html>
<html>
<head><meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Google</title>
</head>
<body>any plain vanila HTML goes here
</body>
All is nice and dandy.
But what if that page contains tons of Javascript code that is nicely rendered by all web browsers but isn't available to me?
Is there a renderer that takes care of the Javascript as well, to output HTML or plaintext, that isn't necessarily going to a visual display?
(I know about WebView but my understanding that I can't really access its output. Or can I?)
Is there a renderer that takes care of the Javascript as well, to output HTML or plaintext, that isn't necessarily going to a visual display?
WebView or bust.
(I know about WebView but my understanding that I can't really access its output. Or can I?)
Create a Java object to receive your output
Add that Java object to the WebView via addJavascriptInterface()
Use loadUrl("javascript:...") on the WebView to invoke a hunk of Javascript that gathers your information and calls a method on your Java object
I have been looking into the GWT for a couple of days now and I have some confusion.
I come from a PHP/JSP background so when I wanted to create a website that had multiple pages I would just create a PHP page for each page and then let the user select what to view.
Now that I am looking into GWT I don't really understand how this is done?
Lets say I would like my site to have three pages (index.html, help.html, contact.html), when a GWT app is loaded the onModuleLoad() method is called. How would I then code each separate pages widgets then using only this one method?
Looking at the example GWT application that is created in Eclipse, A single HTML page is created. How would I create an application with multiple pages if there is only a single onModuleLoad() method?
GWT can be used in a Web 2.0, client-side application way as mentioned by Chris Lercher and nvcleemp or you can use it in conjunction with a more traditional page view/reload model. If you simply want to inject DHTML functionality into existing, static pages, you can look for specific element id's for injecting into or you could read a javascript embedded configuration variable when onModuleLoad() is called to determine what state/mode you are in and what type of GWT client functionality you should be running.
For example, using the different injection points:
page 1:
<html>
<head>
...
<script type="text/javascript" src="yourmodule.nocache.js"></script>
...
</head>
<body>
...
<div id="injectMode1"></div>
...
</body>
</html>
page 2:
<html>
<head>
...
<script type="text/javascript" src="yourmodule.nocache.js"></script>
...
</head>
<body>
...
<div id="injectMode2"></div>
...
</body>
</html>
Your GWT EntryPoint:
#Override
public void onModuleLoad() {
final Panel mode1 = RootPanel.get("injectionMode1");
if (mode1 != null) {
mode1.add(new ModeOneWidget());
}
final Panel mode2 = RootPanel.get("injectionMode2");
if (mode2 != null) {
mode2.add(new ModeTwoWidget());
}
}
EDIT:
Using javascript variables, on each page that you want to embed GWT functionality you can do something similar to:
page foo:
<html>
<head>
...
<script type='text/javascript'>
var appMode="mode1";
</script>
<script type="text/javascript" src="yourmodule.nocache.js"></script>
...
</head>
...
Your GWT EntryPoint:
private static final native String getAppMode()/*-{
return $wnd.appMode;
}-*/;
#Override
public void onModuleLoad() {
String appMode = getAppMode();
if(appMode != null){
if(appMode.equals(MODE1)){
...
}
...
}
}
GWT uses JavaScript to modify the page content. So you don't load a new page [*].
With GWT, you don't need the server to create dynamic HTML content anymore. It's created dynamically on the client side (using static JavaScript code). When you need to load something from the server, you just load data objects (in JSON or XML format, or using GWT-RPC). The client may then use this data to build HTML snippets (to set innerHTML) or DOM objects to modify the browser's DOM tree.
With GWT, you don't have to build these snippets manually: You can use Widgets and UiBinder (client side HTML templating, enhanced with GWT tags and dynamic parameters).
[*] There are some special cases (e.g. if you have a https login page, whereas the rest of the app might use http), where you do load a new page, but that means either that your other page doesn't use GWT at all, or that you create a separate GWT module for it. Of course you can share some of the Java classes between these modules.
GWT is used to build applications like e.g. Google Reader or Gmail: this means that there is just 'one' page. You could have a 'window' inside that page that shows the contact information and a 'window' that shows the help information. When the users clicks the corresponding link you show that 'window'
I'm using a JS Charts library to draw graphs in a WebView of my Android Application. I want to provide the data from the SQLite database. At this moment I'm stuck on how to pass array of data from Java to JavaScript. The JavaScript part expects something like that:
data = new Array([10, 10], [20, 10]);
I know about the addJavaScriptInterface and I managed to pass single values from my Activity to a WebView. It's only the array that gives me trouble. I thought about something like that:
final class ChartDataLoader {
public double[][] getData() {
double[][] data = {{10, 10}, {20, 10}};
return data;
}
}
Note that for now I'm just hard-coding the data, but eventually this will be pulled out from a database. So then I expose this to my JS:
webView.addJavascriptInterface(new ChartDataLoader(), "dataLoader");
And finally try to read it in JavaScript:
<html>
<head>
<script type="text/javascript" src="jscharts.js"></script>
</head>
<body>
<div id="chartcontainer">You should see a chart here.</div>
<script type="text/javascript">
myData = dataLoader.getData();
alert("DataReceived: " + myData.length);
alert("Element 0 : " + myData[0]);
var myChart = new JSChart('chartcontainer', 'line');
myChart.setDataArray(myData);
myChart.draw();
</script>
</body>
</html>
JavaScript fails on those two alert statements stating:
ERROR/Web Console(2455): Uncaught
TypeError: Cannot read property
'length' of undefined at
file:///android_asset/chart.html:15
Any hints? I saw some code online where other people convert arrays to a String and then recreate it back in JavaScript but that seems like an overkill to me and I was hoping for a better solution. An alternative is to pass an XML file to the chart library, but again, I thought it would be slow to create a new XML every time a user wants to see a graph.
Remove the line: alert("DataReceived: " + myData.length);
To fix the most recent error you need to define myData as a var.
What you talk about at the end of your question (converting arrays to string) is JSON. Any context switch is expensive (e.g. Android to web). The serialisation/de-serialisation probably won't slow you down too much.