Android: Webview and Activity - android

I have hosted a web project in my system.I need to run the html content in Android application using WebView. I did that.My requirement is I need to get the content of the html page or Javascript inside it, in my activity.I sit possible.Please help me.
My html page contains one checkbox and some content inside . I also have Save button. When I click the Save button I should get the content of the hidden fields inside the html page in My Activity .IS that possible. pls help me.

Finally I got the problem resolved.. In my activity I added a JavaScript interface with a javascript function named saved() in it.In my html page I added a javascript function named clicked().In this function I collected all the values as a String and passed to the saved().
The saved() function is in my activity and so I could use the values in my Activity.
In Oncreate()
{
mWebView.addJavascriptInterface(new DemoJavaScript(),"demo");
mWebView.loadUrl("file:///android_asset/index.html");
}
final class DemoJavaScript {
DemoJavaScript() {
}
// This is the javascript function
public void saved(String values) {
Toast.makeText(getApplicationContext(), values, Toast.LENGTH_SHORT).show();
}
}
// my html page
<script language="JavaScript">
var values;
function clicked()
{
values="";
values=document.getElementById('myvalue');
window.demo.saved(values);
}
</script>
<body>
<br />
<input type="hidden" name="myvalue" id="myvalue" value="reebok"/>
<br/>
<table>
<tr><td width="100" align=right><input type="button" name="save" value="Save" onClick="clicked()"/></td><td><input type="button" name="cancel" align=center value="Cancel"/></td></tr>
</table>
</body>
</html>

Related

How can JSON be passed to AngularJS in Android webview?

I am trying to use an Android Webview to display some "active" content (sets of images that vary depending on some input settings). The content will be local (offline).
I would like to use Angular.js to control the media that will be displayed on the page.
So, to the problem... how can my Angular app receive JSON data on startup? The problem that I see is that the webview does not allow angular to lazy load additional files (I already ran into this while trying to use html templates for a custom directive. This required enclosing the HTML templates into the single HTML file).
My Android activity can write out the options somewhere, but how is Angular going to be able to read them? In other words, is there a way around the security settings of the webview which does not allow Angular.js to lazy load additional files?
I think that I've figured this one out. I realized that I can create a method in my Android Java code that is exposed to JavaScript (via #JavascriptInterface). This would allow me to call this method from my AngularJS app to get the JSON in a string (see this link for info on JavascriptInterface: http://developer.android.com/guide/webapps/webview.html). I'll post some code once I've proven that this works.
Here is the code. It works great.
MainActivity.java
public class MainActivity extends Activity {
private String MY_JSON_EXAMPLE = "{\"name\":\"John Doe\",\"email\":\"jdoe#testco.com\"}";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.myWebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.addJavascriptInterface(this, "AndroidMainAct");
wv.loadUrl("file:///android_asset/mypage.html");
}
#JavascriptInterface
public String getMyJSONData() {
return MY_JSON_EXAMPLE;
}
}
mypage.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello World, AngularJS</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h3>Load Test</h3>
<div ng-controller="MyController">
<div id="dataWaiting" ng-show="!myData.length">
Loading JSON...
</div>
<div id="dataLoaded" ng-show="myData.length">
Data Loaded: {{myData}}
</div>
</div>
</body>
</html>
app.js
var myApp=angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', function($scope) {
$scope.myData = '';
this.loadData = function() {
// get the data from android
return AndroidMainAct.getMyJSONData();
};
$scope.myData = this.loadData(); // load data on instantiation
}]);
Exposing the data through the android JavascriptInterface method works great.

refresh dynamic contents on common popup jQuery mobile

I am working on a web app where, I have a Common popup as a direct child of , it contains few popups created dynamically from the JSON. There are two separate pages having user input form. JSON file is updated using the form data.
I am updating the contents of the popups using the updated JSON in the form submit function. I am facing the problem to refresh the popup contents on form submit. I have to restart the APP to see the changes on popups.
I tried triggering 'refresh' and 'create' events on popups in form submit function, but still no result.
Moreover even if I set the contents of popup div to be empty using $('#popup-div').empty() in submit function, I can still see the popup. Don't know if this is the caching problem.
Please advice for some solution, Thanks
Example Code:
<body>
<div id="common-popup">
<div id="data-popup" data-role="popup">';
<p>Name: N/A<p>
<p>DOB: N/A <p>
</div> <!--Popup div ends -->
</div>
<div data-role="page" id="page1">
<input type='text' id='p1_name' value=''>Name: </input>
<input type='text' id='p1_dob' value=''>DOB: </input>
<button class="update-data" id="b1"/>
Watch Data
</div>
<div data-role="page" id="page2">
<input type='text' id='p2_name'>Name: </input>
<input type='text' id='p2_dob'>DOB: </input>
<button class="update-data" id="b2"/>
Watch Data
</div>
</body>
<script type="text/javascript">
$('.update-data').on('vclick', function(){
var id = $(this).id;
id = id.split('');
var htm = '<div id="data-popup" data-role="popup">';
htm += '<p>Name: ' + $('#p' + id[1] + '_name').val() +'<p>';
htm += '<p>Name: ' + $('#p' + id[1] + '_name').val() +'<p>';
$('#common-popup').html(htm).trigger('create');
});
</script>
Here is the working demo
$( "#common-popup #data-popup")
.enhanceWithin().popup()
.on('popupafterclose', function(event) {
$(this).remove();
});
JS Fiddle Demo
The dynamic popup created should be removed after its closed. Creating it again and again makes multiple popups..but you are still referring to the first one, which created the problem.

How to read HTML Tag in Android?

In my application, I have to make url from getting data from one static url, I have to read value from that page (means from HTML tag i.e. ) and build new url and display it in webview.
I am facing problem, how to get page source of given url and get particular tag value
like
<HTML>
<Head>
<Title>ABCDE</Title>
</Head>
<div>
<input type="hidden" name="_MYNAME" id="_MYNAME" value="" />
<input type="hidden" name="_EVENT" id="__EVENT" value="" />
<input type="hidden" name="__MYSTATE" id="__MYSTATE" value="">
</div>
I need to read value of tab , I try with htmlcleaner but I was not got success. any suggestion ?
You can use YQL (Yahoo query Language) to write query for fetching HTML data.
YQL returns JSON or XML result which you can read using HttpGet inside AsyncTask.
This is developer guide:
http://developer.yahoo.com/yql/guide/
This is the guide to read JSON response in android:
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Just Override the onpagefinished method in WebViewClient for your webview. you just need to write some javascript to get the value fromvthe html page using name or id as simple as we are doing in simple html pages , form the url and load it using js itself
String javascript;
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
javascript="javascript:var yourValue=document.getElementById('tad_id').value;
window.location = "form your url using yourValue here";"
wv.loadUrl(javaScript);
}
I am using it to fill the form from my preferences file and working fine for me.

String from android activity to string in html inside assets folder

I Have an application with an html file inside of the assets folder. I want it so that when the user clicks a button, inside of the Android applications activity, the contents of the button get put into a string and passes the string to a string inside of the html file. Taking the contents of the button and passing them to a string inside of the activity I can do. I want to know how can I take the string, that I got from the button, and pass the information to the html file inside of my assets folder?
Are you just trying to display the HTML file with different data based on a button push? You can use %s or %d in your HTML file as well as $1..$n to do multiple replacements:
You have $1%d new $2%s.
Pseudo-Code
getHtmlFromAssets(myfile.html, unReadThings, things) where unReadThings is a number and things is a string.
Make sense?
Conceptually (though you'll be using HTML): http://mobile.tutsplus.com/tutorials/android/android-sdk-format-strings/
Or less Android specific: http://javarevisited.blogspot.com/2011/12/java-string-replace-example-tutorial.html
Resources (including Assets) are meant to be read. You can open a raw file, call a anim file, get a string from String xml file. However, you can't write to a resource.
As AssetsManager documentation states:
This class presents a lower-level API that allows you to open and read raw files that have been bundled with the application as a simple stream of bytes.
Now, what to do? I suggest you look into other types of Storage Options. For your case, I strongly suggest Using the Internal Storage.
addJavaScriptInterface method helps us pass values from a webpage to your android XML view or vice-versa. You can invoke your activity class method form your webpage
On create:
WebView Wv = (WebView) findViewById(R.id.webView);
Wv.getSettings().setJavaScriptEnabled(true);
JavaScriptInterface myJavaScriptInterface
= new JavaScriptInterface(this);
Wv.getSettings().setJavaScriptEnabled(true);
Wv.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
Wv.loadUrl("file:///android_asset/index.html");
then create a class myJavaScriptInterface
class JavaScriptInterface {
Context mContext;
int tpressure;
JavaScriptInterface(Context c) {
mContext = c;
tpressure=0;
}
public int Pressure(){
return tpressure++;
}
}
Sample html file would be:
<head>
<title>jQuery Mobile page</title>
<script src="jquery-1.9.1.min.js"></script>
<script src="jquery.mobile-1.3.2.min.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.3.2.css" />
<script type="text/javascript">
$(document).ready(function () {
setInterval(function() {
$("#tire1").html(AndroidFunction.Pressure())
}, 2000);
});
</script>
</head>
<body>
<div id="some">
Tire Pressure:
</div>
<div id="tire1">
0
</div>
</body>

How to send data from one page to another page using Jquery mobile? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How-to store variable beetween jQM pages?
I am new to jquery mobile and a bit confused of sending data to another page. In my html file it consists of listview. when i click on list it needs to redirect to another page and at the same time i want to send data in that list to second page.
Actually my code is..
Polls.html
<body>
<section id="pollsscreen" data-role="page">
<header data-role="header" >
<h1> Video </h1>
Back
</header>
<div data-role="content">
<ul id="pollslist" data-role="listview" data-theme="e" >
</ul>
</div>
</section>
</body>
Polls.js (my javascript file)
var addPollsList = function addPollsList() {
$("#pollslist").prepend("<li><a href='pollsdetails.html'>What is your name?</a></li>");
$("#pollslist").prepend("<li><a href='pollsdetails.html'>Give review of new movie..</a></li>");
$("#pollslist").listview("refresh");
}
pollsdetails.html
<section id="pollsdetailspage" data-role="page">
<header data-role="header">
<h1> Polls </h1>
Back
</header>
<div data-role="content" class="pollsdetailsscreen">
<p>Polls details page</p>
</div>
</section>
</body>
As per the code everything is working good. when i click on list it is redirecting to "pollsdetails.html" file. But here i am not getting any idea how to send the data to that html page and i want to set that data to tag in pollsdetails.html page. can anyone help me with this.......
Thanks in advance...
you can use global variables for this..
In Polls.js
var addPollsList = function addPollsList() {
$("#pollslist").prepend('<li>What is your name?</li>');
$("#pollslist").prepend('<li>Give review of new movie..</li>');
$("#pollslist").listview("refresh");
}
function test1(data){
// set urs global variable here
global_variable = data;
$.mobile.changePage( "pollsdetails.html");
}
function test2(data){
// set urs global variable 2 here
global_variable_2 = data;
$.mobile.changePage( "pollsdetails.html");
}
and in pollsdetails.js you can access global_variable and global_variable_2.
You could use Query string parameters if you are trying to pass simple name-value pairs to the next page.
var addPollsList = function addPollsList() {
$("#pollslist").prepend("<li><a href='pollsdetails.html?myparam=value1'>What is your name?</a></li>");
$("#pollslist").prepend("<li><a href='pollsdetails.html?myparam=value2'>Give review of new movie..</a></li>");
$("#pollslist").listview("refresh");
}
I would go with Localstorage
var userReview = {
"Name":"Bob",
"Review":"Awesome party movie!!",
"MovieTitle":"Project X"
};
//Store the object in local storage
localStorage.setItem('UserReview',JSON.stringify(userReview));
then you can always call the localstorage to get the info back when you navigate to a different page.
var userReview = JSON.parse(localStorage.getItem("UserReview"));
var userName = userReview.Name;
var review = userReview.Review;
var movieTitle = userReview.MovieTitle;

Categories

Resources