WebView blank page : How to fix it? - android

I have a problem, and I spent too much time to resolve it without any solutions to fix it.
I want to open a link in a webview.
My logcat and my run tabs show me the website is correctly loaded but my webview is still blank.
this is my code
public class WebviewFragment extends AppCompatActivity {
#BindView(R.id.webview)
WebView webView;
private String newString;
private String key = "KEY";
Activity activity;
Context mContext;
private ProgressDialog progDailog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview_fragment);
activity = this;
progDailog = ProgressDialog.show(activity, "Loading", "Please wait...", true);
progDailog.setCancelable(false);
webView = new WebView(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode( 10 * 1024 * 1024 );
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setAppCachePath(activity.getCacheDir().getPath());
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setLoadsImagesAutomatically(true);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
newString = null;
} else {
newString = extras.getString(key);
}
} else {
newString = (String) savedInstanceState.getSerializable(key);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progDailog.show();
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
progDailog.dismiss();
}
});
webView.loadUrl(newString);
}
}
newString is the good link.
no error in my "logcat" tab, and no error in my "run" tab.
But I cannot solve this problem.
If you have any suggestions, let me know.

You load the URL into the WebView that you never add to the screen:
webView = new WebView(this);
And you never show it in your layout.
If you have a WebView in your layout, you probably wanted to use it as
webView = findViewById(R.id.<something>);
Instead of
webView = new WebView(this);

Hey it seems like you are using Butterknife and forgot to call
Butterknife.bind(this);
As this call will bind Butterknife binding to webview.

Related

Android keyboard invisible

I have an activity A which has a button. On clicking this button, activity B launches. Activity B has WebView inside an xml layout which loads HTML page stored locally on the device. The whole webpage consist of several CSS(heavy material) and jsons(large in size). At this time the RAM usage is around 90MB. HTML have input fields both text and numeric in it. The problem is after opening and closing the webview 3-4 times, when I click on the input field the keyboard become invisible.
Click here for screenshot
This is my activity code.
public class LaunchActivity extends Activity {
WebView webView;
private final int FILECHOOSER_RESULTCODE = 1;
private Uri mCapturedImageURI = null;
public String mCameraPhotoPath;
String webViewUrl;
public String mMediaType;
public int flag = 0;
public File imageStorageDir;
Bundle bundle;
String mode;
public ProgressDialog progDailog;
int questionToBeLaunch;
Project project;
public void onBackPressed() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.launch_survey);
// getting data from intent and creating the url to load.
webView = (WebView) findViewById(R.id.webView1);
setWebViewProperties();
Map<String, String> header = new HashMap<String, String>(2);
header.put("Pragma", "no-cache");
header.put("Cache-Control", "no-cache");
webView.loadUrl(webViewUrl, header);
}
public void setWebViewProperties(){
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
// Javascript enabled on webview
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.addJavascriptInterface(jsInterface, "interface");
// Other webview options
webView.getSettings().setLoadWithOverviewMode(true);
//webView.getSettings().setUseWideViewPort(true);
//Other webview settings
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setSupportZoom(true);
progDailog = new ProgressDialog(LaunchSurvey.this);
//Load url in webview
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progDailog.setMessage("Loading...");
progDailog.setCanceledOnTouchOutside(false);
progDailog.setCancelable(false);
progDailog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.clearCache(true);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
// webView.setOnTouchListener(null);
webView.removeAllViews();
webView.clearCache(true);
webView.clearHistory();
// clearCache(getApplicationContext());
webView.destroy();
webView = null;
}
}
After struggling for many days, finally I figured out the root cause of your problem. It is probably because of the heavy javascript code that webview needs to parse. Try to lighten it a bit and you are all set, the numeric keypad won't get invisible.

WebView error in fragment

This code is working fine in Activity but same code doesn't work in Fragments. It gets error of ProgressDialog which can't be applied and another one is can't resolve method onBackPressed()
public class FacebookFragment extends Fragment {
private WebView webView;
public FacebookFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.fragment_facebook, container, false);
webView = (WebView)rootView. findViewById(R.id.webView1);
startWebView("https://betanews.in/");
return rootView;
}
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 (WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(FacebookFragment.this);
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);
}
// Open previous opened link from history on webview when back button pressed
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
replace this line progressDialog = new ProgressDialog(FacebookFragment.this); with progressDialog = new ProgressDialog(getActivity());
we need to pass a context to the ProgressDialog constructor, FacebookFragment.this will return object of Fragment, but the expected object is of Activity, you can get the Context of holding Activity.
onBackPressed() is method from class Activity , but here you are extending Fragment
override this method where you actually inflates this fragment. and check for the instance id of the fragment you needed, then do the stuff.
hope it help you

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);
}

Closing a webview on url detection

I have a webview in my activity and I need to close it once the final url is being loaded.
I tried destroy() in the custom Client but that wasn't allowed, finish() closed the entire app, back key closed the app too. Is there a way to just remove the webview and return to the rest of activity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
WebView webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(myUrl);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.matches(PATTERN)) {
Matcher matcher = Pattern.compile(PATTERN).matcher(url);
result = matcher.matches() ? matcher.group(1) : null;
// webview.destroy(); //doesn't work as destroy cannot be called from here
return false;
}
view.loadUrl(url);
return true;
}
}
You can just remove webView from parent by:
ViewGroup vg = (ViewGroup)webView.getParent();
if(vg != null)
vg.removeView(webView);
Or try just webView.setVisibility(View.GONE);

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