I am trying to open an url in a new webview (created in a non activity class).
When debugging the mContext is not null, and i am on the main thread. I can see the toast and the last print but the webview is not shown. I don't understand what i am doing wrong.. can you spot a mistake? Thank you
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, "test", Toast.LENGTH_LONG).show();
System.out.println("creating a new webview");
WebView wv = new WebView(mContext);
wv.loadUrl("urlhere");
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
System.out.println("finished loading url: " + url);
}
public void onLoadResource(WebView view, String url) {
}
public boolean shouldOverrideUrlLoading(WebView view,
String url) {
return true;
}
});
wv.setVisibility(View.VISIBLE);
System.out.println("should see the webview now");
}
});
You are creating a new WebView but not giving it a parent where it can attach and display. Or use it in a setContentView.
Related
I am getting message 'Server hangup' when loading url into webView and this message is not implemented in either Android side or server side. If anyone knows how to solve this issue, Please help. Thanks
I have used following code:
private WebView mWebview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyWebChromeClient(this));
mWebview .loadUrl("our server url");
setContentView(mWebview);
}
private class MyWebChromeClient extends WebChromeClient {
Context context;
public MyWebChromeClient(Context context) {
super();
this.context = context;
}
}
Please check screenshot
Google.com is secure domain. You have to use https://www.google.com instead of http://www.google.com.
Please use this method and set your website url :
Example :startWebView("https://stackoverflow.com");
private void startWebView(String url) {
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Error:" + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl(url);
}
Webview shows you the HTML returned by the URL that has been loaded.
onReceivedError() will not be called if you get response containing the error message.
Check what you receive as HTML from server using the following code in onPageFinished().
webView.evaluateJavascript(
"(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();",
new ValueCallback<String>() {
#Override
public void onReceiveValue(String html) {
// displays the HTML received after the URL is loaded.
Log.e("#Eval", "Html -> " + html);
}
});
As you have mentioned that the message is not implemented in your app, it must have been be received from the server end.
I am loading a website in webview,we have used Ajax in website and its working fine on web browser and mobile browser also but in android webview ajax is not working no error is there in the console.Here is my code:-
public class Activity_WebView extends AppCompatActivity implements
ConnectivityReceiver.ConnectivityReceiverListener {
WebView webview;
ProgressDialog pro_dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setPluginState(WebSettings.PluginState.ON);
webview.setWebViewClient(new loadinsame());
pro_dialog = new ProgressDialog(Activity_WebView.this);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
boolean connection = checkConnection();
if (connection) {
webview.loadUrl("website url");
} else {
Toast.makeText(Activity_WebView.this, "Sorry! Not connected to
internet", Toast.LENGTH_SHORT).show();
dialog_Show(webview, "Please check you Inernet connect and Reload.",
false);
}
}
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if (!isConnected) {
Toast.makeText(Activity_WebView.this, "Sorry! Not connected to
internet", Toast.LENGTH_SHORT).show();
}
}
private class loadinsame extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pro_dialog.setCancelable(false);
pro_dialog.setMessage("Loading...");
pro_dialog.show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pro_dialog.dismiss();
}
#Override
public void onReceivedError(final WebView webview, WebResourceRequest
request, WebResourceError error) {
super.onReceivedError(webview, request, error);
pro_dialog.dismiss();
// dialog_Show(webview, "Error Occur, Do you want to Reload?", true);
}
}
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
}
private boolean checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
return isConnected;
}
#Override
protected void onResume() {
super.onResume();
MyApplication.getInstance().setConnectivityListener(this);
}
}
when i inspect the website in chrome using emulator, find that my ajax remain pending and then cancel after sometime.
Thanks in advance.
Just promoting #Jeff Thomas comment, by setting
mWebView.getSettings().setDomStorageEnabled(true);
worked!!
When i enabled the java script, its working.
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("");
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebClient());
Solutions
If you want to load web url in WebView so you need follow my code It's code working fine and In web any type of script language used in web page.
public void webviewCallBack(String coverUrl) {
WebView WebView webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.clearView();
webView.measure(100, 100);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.setWebViewClient(new WebViewClient() {
// For api level bellow 24
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("weburl__", url);
if (url.startsWith("http") || url.startsWith("https")) {
// Return false means, web view will handle the link
return false;
} else if (url.startsWith("tel:")) {
// Handle the tel: link
handleTelLink(url);
// Return true means, leave the current web view and handle the url itself
return true;
}
return false;
}
// From api level 24
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
// Get the tel: url
String url = request.getUrl().toString();
Log.d("weburl_____", url);
if (url.startsWith("http") || url.startsWith("https")) {
// Return false means, web view will handle the link
return false;
} else if (url.startsWith("tel:")) {
// Handle the tel: link
handleTelLink(url);
// Return true means, leave the current web view and handle the url itself
return true;
}
return false;
}
});
// Load the url into web view
webView.loadUrl(coverUrl);
hoadler();
}
public void hoadler() {
Runnable task = new Runnable() {
public void run() {
material_design_progressbar.setVisibility(View.VISIBLE);
}
};
worker.schedule(task, 5, TimeUnit.SECONDS);
}
I hope this code is helpful for you!
Here is how to edit the AndroidManifes.xml:
Find AndroidManifest.xml file in application folder at:
android/app/src/main/AndroidManifest.xml
Locate the application subelement.
Add the following tag:
android:usesCleartextTraffic=”true”
The application subelement should now look like:
<application
android:name=”io.flutter.app.Test”
android:label=”bell_ui”
android:icon=”#`enter code
here`mapmap/ic_launcher”
android:usesCleartextTraffic=”true”>
Save the AndroidManifest.xml file.
The question can be a little vague, I have created a webview and showing the webpage of the URL which I get from some server. Now When i navigate to different pages , On one page there is only a button which will send me a different URL , I need that when user is on that page and click on that button the webview should hide and user continue other operation. I have read that addJavascriptInterface is needed to do this , can anyone tell me if this is possible and how to achieve this , any good tutorial will work.
I also tried this but of no use
wv.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
HitTestResult result = wv.getHitTestResult();
if (result.getType() == HitTestResult.UNKNOWN_TYPE) {
Message msg = mHandler.obtainMessage();
wv.requestFocusNodeHref(msg);
}
return false;
}
});
topupWV.setWebViewClient(new WebViewClient());
topupWV.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("XXXXX")) {
try {
URL urls = new URL(url);
query = urls.getQuery();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
}
you can do something like this for detecting click within a webview
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isNetworkConnected()) {
//DO YOU OPERATION HERE
}
return true;
}
});
I'm trying to use a facebook login button that uses JS Facebook SDK on Android Webview. When I click it open a new page and redirects to https://www.facebook.com/dialog/oauth... which is a blank page with a javascript code. And the webview stays here.
I'm using:
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
Thank you!
You need to add logic to redirect back to the original url of your website.
In order to do this, you need to first create a new java class that extends the WebViewClient class and overrides the onPageFinished method like this:
public class CustomWebViewClient extends WebViewClient
{
#Override
public void onPageFinished(WebView view, String url) {
//https://www.facebook.com/dialog/permissions.request
//actually works for me, but I put the URL you say is coming up
//blank in there instead, whatever works for you:
if(url.startsWith("https://www.facebook.com/dialog/oauth")){
String redirectUrl = "http://www.mydomain.com/MyApp/";
view.loadUrl(redirectUrl);
return;
}
super.onPageFinished(view, url);
}
}
Second, just add it to your WebView:
webview.setWebViewClient(new CustomWebViewClient());
Once that page is finished loading, it will redirect back to your original page
I dont know what exactly i did at that time, but the problem was solved. I'll give you the code. Try finding out :)
WebView browser,mWebviewPop;
private void open(){
browser = (WebView)findViewById(R.id.webView1);
browser.getSettings().setLoadsImagesAutomatically(true);
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setAppCacheEnabled(true);
browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
browser.getSettings().setSupportMultipleWindows(true);
browser.setWebViewClient(new MyBrowser());
browser.setWebChromeClient(new MyCustomChromeClient());
mContext=this.getApplicationContext();
browser.loadUrl(target_url);
MainActivity.this.progressBar.setProgress(0);
browser.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
private class MyBrowser extends WebViewClient {
String redirectUrl = "MY URL";
private void noInternet() {
WebView webview = (WebView) findViewById(R.id.webView1);
RelativeLayout tryAgainLayout = (RelativeLayout)findViewById(R.id.tryAgainLayout);
RelativeLayout progressLayout = (RelativeLayout)findViewById(R.id.progressLayout);
tryAgainLayout.setVisibility(View.VISIBLE);
webview.setVisibility(View.GONE);
webview.destroy();
progressLayout.setVisibility(View.INVISIBLE);
}
public void visible(){
WebView webview = (WebView) findViewById(R.id.webView1);
RelativeLayout tryAgainLayout = (RelativeLayout)findViewById(R.id.tryAgainLayout);
RelativeLayout progressLayout = (RelativeLayout)findViewById(R.id.progressLayout);
tryAgainLayout.setVisibility(View.INVISIBLE);
webview.setVisibility(View.INVISIBLE);
progressLayout.setVisibility(View.VISIBLE);
}
public void unvisible(){
WebView webview = (WebView) findViewById(R.id.webView1);
RelativeLayout tryAgainLayout = (RelativeLayout)findViewById(R.id.tryAgainLayout);
RelativeLayout progressLayout = (RelativeLayout)findViewById(R.id.progressLayout);
tryAgainLayout.setVisibility(View.INVISIBLE);
webview.setVisibility(View.VISIBLE);
progressLayout.setVisibility(View.INVISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
if (host.equals(target_url_prefix))
{
if(mWebviewPop!=null)
{
mWebviewPop.setVisibility(View.GONE);
baseLayout.removeView(mWebviewPop);
mWebviewPop=null;
}
return false;
}
if(host.equals("m.facebook.com"))
{
return false;
}
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
noInternet();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
visible();
}
#Override
public void onPageFinished(WebView view, String url) {
unvisible();
System.out.println("\n" +view.getUrl());
if(url.startsWith("https://m.facebook.com/v2.1/dialog/oauth")){
if(mWebviewPop!=null)
{
mWebviewPop.setVisibility(View.GONE);
baseLayout.removeView(mWebviewPop);
mWebviewPop=null;
}
view.loadUrl(redirectUrl);
return;
}
super.onPageFinished(view, url);
}
}
private class MyCustomChromeClient extends WebChromeClient
{
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
mWebviewPop = new WebView(mContext);
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new MyBrowser());
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(false);
mWebviewPop.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
baseLayout.addView(mWebviewPop);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mWebviewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
OK so from what I can tell, what's happening here is that there are two "ways" for oauth to work, either it will call back "to aparent page" (like popup "log me in" that disappears), or it can redirect you to a login page, then to some other url (non popup style), after success or failure (kind of a chain forward). Unfortunately it appears WebView is not well suited for the "callback to the parent page" style, so you have to do some shenanigans like have a second WebView (jincy's answer here, or see also this).
I have loaded an url in WebView in android, when i click a link in that loaded url in WebView , the link loaded in WebView ugly, to remove this problem I had used setIntialScale(50) , this made my initial url becomes small
Works like a charm.
Check it out
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});
I am not sure but i think you need to implement WebViewClient.
For example:
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
alertDialog.setTitle("Error!! Something went wrong");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl("http://www.google.com");
When you click the link, the phone is opening the new page in the browse instead of your webview. If you disable Url Overriding all subsequent pages will load in the webview and preserve the zoom.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});