Using webView.loadUrl is working for https site , but not with my local page which is located in /Applications/MAMP/htdocs/test.html
webView.loadUrl("/Applications/MAMP/htdocs/test.html") is not working
webView.loadUrl("http://localhost:8080/test.html"); is not working
Below is the test.html file
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h2>JS alert Example</h2>
<button onclick="myFunction()" >Try it</button>
<script>
function myFunction (){
Android.showToast("Sample Android toast message");
}
</script>
</body>
</html>
Now I want to load this page using webView .
Below is the mainactivity.java code
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("http://127.0.0.1:8080/test.html");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.addJavascriptInterface(new WebAppInterface (this), "Android");
}
}
Below is my WebInterface java class :
public class WebAppInterface {
private Context context;
public WebAppInterface (Context context){
this.context = context;
}
#JavascriptInterface
public void showToast (String message){
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
}
Now ,I cant understand why it is not loading the web page mentioned in webView.loadUrl . Note: I having given internet permissions in manifest file.
So if the file is local in the device (android phone), you need to have the path of the file. If the file is bundled in the assets, you can open the file like:
webView.loadUrl("file:///android_asset/filename.html");
Or if you can't find it, you can put the file in the raw resources and read the file into a string and then use:
webView.loadData(htmlString, "text/html", "utf-8");
In any case, most probably the problem you have is you can't find the file. So make sure you are placing the file in the proper place in the assets, or resources. And you are accessing the file correctly.
Here is the documentation on how to access the resources:
https://developer.android.com/guide/topics/resources/providing-resources
If what you mean by local is on your computer, and you are hosting the file (which I assume would be just for testing), then you need to connect the android device / emulator to the same local network as your computer and then access via the local ip of your computer.
And here is another question similar to this that has already been answered:
Load HTML file into WebView
Related
I have a webview in my android app, the html file which gets loaded is on a server, however I need to address some files from app's assets folder. I wanted to ask how can I address those files.
Thanks
public class ViewWeb extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView wv;
wv = (WebView) findViewById(R.id.webView1);
wv.loadUrl("file:///android_asset/aboutcertified.html"); // now it will not fail here
}
}
And in general you can use
getAssets().open("filename.txt"))
To get filea from assets
On a side note:please put some code next time that you have triedget
Lets take a look at this for example: Loading existing .html file with android WebView
I load my HTML file but it contains references to other local css and js files. Do I need use the same file:/// URL inside the HTML file?
No, your structure should be like this:
/assets/html/index.html
/assets/scripts/index.js
/assets/css/index.css
Then just do ( Android WebView: handling orientation changes )
//in onCreate() for Activity, or in onCreateView() for Fragment
if(WebViewStateHolder.INSTANCE.getBundle() == null) { //this works only on single instance of webview, use a map with TAG if you need more
webView.loadUrl("file:///android_asset/html/index.html");
} else {
webView.restoreState(WebViewStateHolder.INSTANCE.getBundle());
}
Make sure you add
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
}
Then just use urls
<html>
<head>
<meta charset="utf-8">
<title>Zzzz</title>
<script src="../scripts/index.js"></script>
<link rel="stylesheet" type="text/css" href="../css/index.css">
EDIT:
That particular code will work only if you add the code that I linked
public class WebViewFragment extends Fragment { //could be activity
private enum WebViewStateHolder
{
INSTANCE;
private Bundle bundle;
public void saveWebViewState(WebView webView)
{
bundle = new Bundle();
webView.saveState(bundle);
}
public Bundle getBundle()
{
return bundle;
}
}
#Override
public void onPause()
{
WebViewStateHolder.INSTANCE.saveWebViewState(myWebView);
super.onPause();
}
As for whatever "security issue" you speak of, you didn't share enough data.
According to Rendering HTML in a WebView with custom CSS, you dont have to specify each CSS or JS. Include them in the HTML file itself.
I got a html file like this:
<body>
<h2>My html</h2>
<p> You could save #value per year.</p>
</body>
I load this page in android with a WebView
I got a stored value that I need to replace with #value , is this possible?
Update PagerAdapterClass where i need to use it :
#Override
public Object instantiateItem(ViewGroup container, final int position) {
WebView Content;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.view_pager_item, container,
false);
Content= (WebView) itemView.findViewById(R.id.iaps_url);
Content.loadUrl(myUrl.get(position));
((ViewPager) container).addView(itemView);
return itemView;
}
myUrl.get(position) reprezents the file location like "file:///android_asset/ScreenOne.html"
Yes.
First read the HTML from assets/raw to a String. And then use the replaceAll function of the string.
InputStream is = getAssets().open("webpage.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String page = new String(buffer);
page = page.replace("#value", "new string");
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("", page, "text/html", "UTF-8", "");
Hi You can use the Android JavaScript Bridge technique. Look at below steps.
Steps 1. For enabling the Java script in a web view by default the JavaScript is disabled. You can enable through the WebSettings attached to your webview then enable the javascript with setJavaScriptEnabled()
For example
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
Steps 2. Building java script code to the android code
To bind the javascript and android code, it call addJavascriptInterface().passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.
For example, you can include the following class in your Android application:
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** call the stored value from java to javascript */
#JavascriptInterface
public integer getStoreValue() {
return 1;
}
}
You can bind this class to the JavaScript that runs in your WebView with addJavascriptInterface() and name the interface Android. For example:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
This creates an interface called Android for JavaScript running in the WebView. At this point, your web application has access to the WebAppInterface class. For example, here's some HTML and JavaScript that call the java stored value using the new interface when html widnow load: #see this link
<html>
<script type="text/javascript">
function getStoredValue() {
var output = document.getElementById('values');
output.innerHTML = Android.getStoreValue();
}
</script>
<body onload="getStoredValue()">
<h2>My html</h2>
<p> You could save <a id= 'values'>
</a> per year.</p>
</body>
</html>
Let me know if you have any doubt, thank you.
I have User registration page in Phonegap www folder.I want to validate email id and phone number using native android functions.How do I do that?
We have to write JS interface to execute java code from javascript.
Write following code in your onCreate method:
public class MainActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
WebView webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Object()
{
public void performClick(String emailAdress, String phoneNo)
{
// Validate email address and Phone number here
}
},"MyAndroid");
}
}
To call JS interface in phonegap app, write javascript function:
<script>
document.getElementById("validateButton").addEventListener('touchstart',touchPagePressed);// you can use 'onclick' also
function touchPagePressed()
{
// MyAndroid interface will execute java's performClick method
MyAndroid.performClick($("#emailId").val(),$("#phoneNo").val());
}
</script>
I have defined some webview and I open some webpage on it
WebView wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("http://mypage.com/");
My question is how can I count the number of links in that webpage ?
my first idea was to parse the html code and to count the "href" string in that html, but this solution sound like a noob solution to me. Is there more intelligent way to do this ?
If you can edit the HTML I think you can do that with a simple javascript function that sends the count data back to Android. You can see an answer about that here
The function in Javascript to count links can be as simple as this:
<script type="text/javascript">
function countLinks()
{
var all_a = document.getElementsByTagName("a");
return all_a.length;
}
</script>
First declare a JavaScriptInterface in android code:
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Get number of links */
public void getNumOfLinks(int numOfLinks) {
// Use the count as you like
}
}
Then add this interface to your webview, when you call it:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
Finally in the HTML code get the number of links from DOM and pass it to the java code via the interface:
<script type="text/javascript">
Android.getNumOfLinks(document.getElementsByTagName("a").length)
</script>