Error in load html + JavaScript in android - android

I did try samples, demos from Google codes and other resources with WebView, but when i try to do it in my own code, it doesn't work for me.
I want to load index.html which i put in assets folder, and using:
public class MainActivity extends Activity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//define webview
webView = (WebView)findViewById(R.id.webView);
webView.setHorizontalScrollBarEnabled(false);
webView.loadUrl("file:///android_asset/www/index.html");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
On emulator i cannot see my file its still white background and not open my index.html.
Note:-
my index.html is include JavaScript than get data from web site online by ajax.
Is there any way of loading an existing .html file in the application package which works on all API versions ?
Thank you in advance for your help!
Edit :-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
MainActivity.this.setProgress(progress * 1000);
}
});
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(MainActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webView.loadUrl("file:///android_asset/www/index.html");
}
i will try this code but i have error :-
Multiple markers at this line
- WebViewClient cannot be resolved to a type
- The method setWebViewClient(WebViewClient) in the type WebView is not applicable for the arguments (new
WebViewClient(){})

If your index.html includes JavaScript code, try:
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);

Related

Android - Open URL in a WebView [duplicate]

I created an Activity that has a title and a web view in a LinearLayout. In the onResume() method it calls webView.loadUrl(url). The problem is that the activity first shows the title with the rest of the screen blank, then the device browser is launched with the page for the URL. What I want to see is the page being shown in the WebView below the title. What could be the problem?
Edit:
Ok, did some further search and found this one:
Clicking URLs opens default browser
It points to the WebView tutorial here.
Just implement the web client and set it.
Answering my question based on the suggestions from Maudicus and Hit.
Check the WebView tutorial here.
Just implement the web client and set it before loadUrl. The simplest way is:
myWebView.setWebViewClient(new WebViewClient());
For more advanced processing for the web content, consider the ChromeClient.
Use this:
lWebView.setWebViewClient(new WebViewClient());
use like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dedline);
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("https://google.com");
}
Make your Activity like this.
public class MainActivity extends Activity {
WebView browser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the WebView by name in the main.xml of step 2
browser=(WebView)findViewById(R.id.wvwMain);
// Enable javascript
browser.getSettings().setJavaScriptEnabled(true);
// Set WebView client
browser.setWebChromeClient(new WebChromeClient());
browser.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// Load the webpage
browser.loadUrl("http://google.com/");
}
}
I was facing the same problem and I found the solution
Android's official Documentation about WebView
Here is my onCreateView() method and here i used two methods to open the urls
Method 1 is opening url in Browser and
Method 2 is opening url in your desired WebView.
And I am using Method 2 for my Application and this is my code:
public class MainActivity extends Activity {
private WebView myWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_webpage_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
/* Method : 1
This following line is working fine BUT when we click the menu item then it opens the URL in BROWSER not in WebView */
//((WebView) rootView.findViewById(R.id.detail_area)).loadUrl(mItem.url);
// Method : 2
myWebView = (WebView) rootView.findViewById(R.id.detail_area); // get your WebView form your xml file
myWebView.setWebViewClient(new WebViewClient()); // set the WebViewClient
myWebView.loadUrl(mItem.url); // Load your desired url
}
return rootView;
} }
Try this code...
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (final WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(view.getContext());
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
}
If you see an empty page, enable JavaScript.
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl(url);
Simply Answer you can use like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
setContentView(webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com");
}
}
If you're using webChromeClient I'll suggest you to use webChromeClient and webViewClient together. because webChromeClient does not provides shouldOverrideUrlLoading. It is okay to use both.
webview.webViewClient = WebViewClient()
webview.webChromeClient = Callback()
private inner class Callback : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
if (newProgress == 0) {
progressBar.visibility = View.VISIBLE
} else if (newProgress == 100) {
progressBar.visibility = View.GONE
}
}
}
I just found out that it depends on the formatting of the URL:
https://example.com/example gets opened in the browser
https://example.com/example/ (with / at the end) gets opened in the webView
My code just uses
webview.loadUrl(url)
no need to set
webView.setWebViewClient(new WebViewClient())
at least in my case.
Maybe that's useful for some of you.
My problem ended up being that I needed to do a clearHistory before I could switch between sites without opening an external browser.
#Override
public void onPageFinished(WebView view, String url) {
webView_.clearHistory();
super.onPageFinished(webView_, url);
}

WebView fails to load webpage

I have a WebView trying to load a WebPage like this:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
wv=(WebView)findViewById(R.id.webview);
WebSettings ws=wv.getSettings();
ws.setJavaScriptEnabled(true);
wv.loadUrl("http://pro39.blutechnologies.com/crimes.aspx");
}
I have added the internet permission to the manifest
<uses-permission android:name="android.permission.INTERNET"/>
However the WebView is blank,it neither throws an error nor loads the web-page.How do I load webpages like this,I have only tried loading local html files before and I would like to know if I have to do something different.
Try like this way:
mWebView.loadUrl("http://pro39.blutechnologies.com/crimes.aspx");
mWebView.setWebViewClient(new HelloWebViewClient());
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
Use this code .shouldOverrideUrlLoading() not use compulsary.use this code and please reply me this code work or not
Try below code.
public class Main extends Activity {
private WebView mWebview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
mWebview = (WebView)findViewById(R.id.webview);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
mWebview .loadUrl("http://pro39.blutechnologies.com/crimes.aspx");
setContentView(mWebview );
}
}

Error while performing action in WebView

I'm able load the URL in my WebView. But if I perform some action (like click event), I'm getting following error in LogCat:
Unable to get value of the property 't': object is null or undefinedundefined
But if I perform some events from the emulator's browser, it is working fine.
Here is the code, based on the post:
public class MainActivity extends Activity {
WebView mWebview = null;
String URL = "********"; // Masked intentionally.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main); //Not required as per comment given by Raghunandan.
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebChromeClient(new WebChromeClient());
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
mWebview .loadUrl(URL);
setContentView(mWebview );
}
}
Note: Web page is developed using AngularJS.
I've added the below property in Manifiest.xml:
<uses-permission android:name="android.permission.INTERNET" />

Can not acess url that are present in the html files from Webview in Android

I am trying to access the url using the shouldOverrideUrlLoading method. For some reason when I try to access the url that are present in the html files, I get Web page not available error.Previously I could access the url because I stored my html file in the raw folder but I needed to move it to assets folder as the code looks cleaner this way. This is my code, could anyone let me know how I can resolve this.
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("file:///android_asset/myfile/file.html");
webview.setVerticalScrollBarEnabled(false);
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equalsIgnoreCase("some text")){
setDialog("some fancy text");
}
Try to get the Real Path of the file first and then try as your way like this:
String YourURI="/android_asset/myfile/file.html";
YourURI = new File(getRealPathFromURI(YourURI));
//Got the Real Path Of the File
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient());
webview.loadUrl(YourURI); //**Used the Real Path**
webview.setVerticalScrollBarEnabled(false);
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equalsIgnoreCase("some text")){
setDialog("some fancy text");
}
}
If the File is in the SDCARD :-
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient());
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
Log.d(TAG, "No SDCARD");
}
else
{
webview.loadUrl("file://"+Environment.getExternalStorageDirectory()
+"/android_asset/myfile/file.html");
}
webview.setVerticalScrollBarEnabled(false);
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equalsIgnoreCase("some text")){
setDialog("some fancy text");
}
}
Final Edit:- This Code Works Perfectly for Asset Folder
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView webview;
webview = (WebView) findViewById(R.id.webView1);
webview.loadUrl("file:///android_asset/myfile/file.html");
}
}
There is another way that would also work for you---
webView.loadData(customHtml, "text/html", "UTF-8");
where custromHtml is the HTML line that is used to be displayed.
on the place of "custromHtml" you just pass "file://android_asset/myfile/file.html".
I think this should work.
You may try for this too -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String myURL = "file:///android_asset/index.html";
myBrowser=(WebView)findViewById(R.id.mybrowser);
/*By default Javascript is turned off,
* it can be enabled by this line.
*/
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.setWebViewClient(new WebViewClient());
myBrowser.loadUrl(myURL);
}
and also check you have placed the file in correct folder of main project. If all this is ok, make a clean project and fix project. Then try to run it.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String myURL = "file:///android_asset/index.html";
myBrowser=(WebView)findViewById(R.id.mybrowser);
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.setWebViewClient(new WebViewClient());
myBrowser.loadUrl(myURL);
}
This would work well try it-----
"android.resource://[package]/[res type]/[res name]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/raw/myvideo");
This link is also useful -
http://developer.android.com/reference/android/webkit/WebView.html
Loading an Android Resource into a WebView
shouldOverrideUrlLoading does not work on ICS for file://, but works for fine for external urls. loadURL works fine loading from the assets folder.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView web=(WebView)findViewById(R.id.webView1);
web.setWebViewClient(new MyWebClient());
//web.loadUrl("file:///android_asset/index.html");
web.loadUrl("http://google.com");
.....
class MyWebClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("MyWebClient", "url is: " + url);
if (url.equalsIgnoreCase("google.com")){
Log.d("MyWebClient","url is: " + url);
}
return false;
}
}
I found this forum solution which solved the problem for me: http://www.cynosurex.com/Forums/DisplayComments.php?file=Java/Android/Android_4_has_a_.file....android_asset.webkit.._bug
I think you should try this ....
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("file://android_asset/myfile/file.html");
webview.setVerticalScrollBarEnabled(false);
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equalsIgnoreCase("some text")){
setDialog("some fancy text");
}

Android webview launches browser when calling loadurl

I created an Activity that has a title and a web view in a LinearLayout. In the onResume() method it calls webView.loadUrl(url). The problem is that the activity first shows the title with the rest of the screen blank, then the device browser is launched with the page for the URL. What I want to see is the page being shown in the WebView below the title. What could be the problem?
Edit:
Ok, did some further search and found this one:
Clicking URLs opens default browser
It points to the WebView tutorial here.
Just implement the web client and set it.
Answering my question based on the suggestions from Maudicus and Hit.
Check the WebView tutorial here.
Just implement the web client and set it before loadUrl. The simplest way is:
myWebView.setWebViewClient(new WebViewClient());
For more advanced processing for the web content, consider the ChromeClient.
Use this:
lWebView.setWebViewClient(new WebViewClient());
use like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dedline);
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("https://google.com");
}
Make your Activity like this.
public class MainActivity extends Activity {
WebView browser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the WebView by name in the main.xml of step 2
browser=(WebView)findViewById(R.id.wvwMain);
// Enable javascript
browser.getSettings().setJavaScriptEnabled(true);
// Set WebView client
browser.setWebChromeClient(new WebChromeClient());
browser.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// Load the webpage
browser.loadUrl("http://google.com/");
}
}
I was facing the same problem and I found the solution
Android's official Documentation about WebView
Here is my onCreateView() method and here i used two methods to open the urls
Method 1 is opening url in Browser and
Method 2 is opening url in your desired WebView.
And I am using Method 2 for my Application and this is my code:
public class MainActivity extends Activity {
private WebView myWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_webpage_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
/* Method : 1
This following line is working fine BUT when we click the menu item then it opens the URL in BROWSER not in WebView */
//((WebView) rootView.findViewById(R.id.detail_area)).loadUrl(mItem.url);
// Method : 2
myWebView = (WebView) rootView.findViewById(R.id.detail_area); // get your WebView form your xml file
myWebView.setWebViewClient(new WebViewClient()); // set the WebViewClient
myWebView.loadUrl(mItem.url); // Load your desired url
}
return rootView;
} }
Try this code...
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (final WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(view.getContext());
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
}
If you see an empty page, enable JavaScript.
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl(url);
Simply Answer you can use like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
setContentView(webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com");
}
}
If you're using webChromeClient I'll suggest you to use webChromeClient and webViewClient together. because webChromeClient does not provides shouldOverrideUrlLoading. It is okay to use both.
webview.webViewClient = WebViewClient()
webview.webChromeClient = Callback()
private inner class Callback : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
if (newProgress == 0) {
progressBar.visibility = View.VISIBLE
} else if (newProgress == 100) {
progressBar.visibility = View.GONE
}
}
}
I just found out that it depends on the formatting of the URL:
https://example.com/example gets opened in the browser
https://example.com/example/ (with / at the end) gets opened in the webView
My code just uses
webview.loadUrl(url)
no need to set
webView.setWebViewClient(new WebViewClient())
at least in my case.
Maybe that's useful for some of you.
My problem ended up being that I needed to do a clearHistory before I could switch between sites without opening an external browser.
#Override
public void onPageFinished(WebView view, String url) {
webView_.clearHistory();
super.onPageFinished(webView_, url);
}

Categories

Resources