WebView not loading after internet permissions granted? - java

I'm trying to use a WebView to display a webpage in my application. At first, I didn't have any permissions in the AndroidManifest.xml and I got the error 'the webpage at could not be loaded because net::ERR_CACHE_MISS'
But now that I have added the permission to the AndroidManifest.xml, the WebView loads as a empty white box.
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package= ... >
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</application>
</manifest>
And my Java class:
public class location_Fragment extends Fragment {
private WebView webView;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.location_layout, container, false);
webView = (WebView)rootview.findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("https://www.google.com");
return rootview;
}
}

Try this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.location_layout, container, false);
webView = (WebView)rootview.findViewById(R.id.webView);
webView.setWebViewClient(new MyBrowser());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("https://www.google.com");
return rootview;
}
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}

Use The Following Code
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Bundle b = getIntent().getExtras();
String data =b.getString("link");
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
if(data.equals("")||data.equals("null")) {
Toast.makeText(WebViewActivity.this,"No Link Available",Toast.LENGTH_SHORT).show();
}
{
webView.loadUrl(data);
}
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
// activity.setProgress(progress * 1000);
WebViewActivity.this.setTitle("Loading...");
WebViewActivity.this.setProgress(progress * 100);
if(progress == 100)
WebViewActivity.this.setTitle(R.string.app_name);
}
});
}
private class MyWebViewClient extends WebViewClient {
private ProgressDialog pDialog;
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// pDialog = new ProgressDialog(WebViewActivity.this,R.style.DialogTheme);
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (WebView view, String url) {
if (pDialog == null) {
// in standard case YourActivity.this
pDialog = new ProgressDialog(WebViewActivity.this,R.style.DialogTheme);
pDialog.setMessage("Loading...");
pDialog.show();
}
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
public void onPageFinished(WebView view, String url) {
try{
pDialog.dismiss();
if (pDialog.isShowing()) {
pDialog.dismiss();
pDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}

Related

Getting this error when using webview net::ERR_CONTENT_DECODING_FAILED

Using webview on java.
The request I am sending is throwing an error.
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView=(WebView) findViewById(R.id.webview);
mywebView.setWebViewClient(new WebViewClient());
WebView.setWebContentsDebuggingEnabled(true);
mywebView.loadUrl("https://lighthearted-platypus-a4a153.netlify.app/");
WebSettings webSettings=mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
public class mywebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view,url,favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view,String url){
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed(){
if(mywebView.canGoBack()) {
mywebView.goBack();
}
else{
super.onBackPressed();
}
}
}
Need to send get request successfully on the api.

Reopened applciation does not load url in webview

I have a fragment with WebView inside to open url and login to some service and then receive some cookie. The issue is that when I open application and fragment inside activity, url loads into WebView normally, but when I close application (programmatically with activity.finishAndRemoveTask()) and open it again (manually) - url does not load. After next app restart (manually) everything goes back to normal. Url which I want to open has two redirects.
It is my fragment class:
public class MyFragment extends Fragment implements WebResourceClient.CookieListener {
private String URL = "https://someurl.com";
#OnClick(R.id.close)
public void detachFragment() {
FragmentManager manager = getFragmentManager();
if (manager != null) {
manager.popBackStackImmediate();
}
}
#BindView(R.id.web_container)
WebView webContainer;
#BindView(R.id.progress_bar)
ProgressBar progressBar;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ny_fragment, container, false);
ButterKnife.bind(this, view);
startWebView();
return view;
}
#SuppressLint("SetJavaScriptEnabled")
private void startWebView() {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookies(null);
WebSettings settings = webContainer.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
settings.setMediaPlaybackRequiresUserGesture(false);
settings.setUserAgentString(Core.USER_AGENT_FOR_GOOGLE);
settings.setAppCacheEnabled(false);
webContainer.clearCache(true);
WebView.setWebContentsDebuggingEnabled(false);
webContainer.setWebViewClient(new WebResourceClient(this));
webContainer.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress < 100) {
webContainer.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
} else {
webContainer.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
}
}
});
webContainer.loadUrl(URL);
}
#Override
public void onDestroyView() {
webContainer.stopLoading();
super.onDestroyView();
}
#Override
public void onReceiveCookie(String cookie) {
detachFragment();
...
}
#Override
public void showProgress() {
webContainer.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
}
}
It's my WebViewClient:
public class WebResourceClient extends WebViewClient {
private final static String someUrl = "https://someOtherUrl";
private CookieListener listener;
public WebResourceClient(CookieListener listener) {
this.listener = listener;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains(someUrl)) {
listener.showProgress();
}
view.loadUrl(url);
return true;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(someUrl)) {
listener.lockWebView();
}
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// if (url.contains(someUrl)) {
String cookies = CookieManager.getInstance().getCookie(url);
String cookie = getCookie(cookies);
if (!TextUtils.isEmpty(cookie)) {
view.stopLoading();
listener.onReceiveCookie(cookie);
}
super.onPageFinished(view, url);
}
private String getCookie(String cookies) {
...
}
public interface GoogleLoginListener {
void onReceiveCookie(String cookie);
void showProgress();
}
}
I open fragment like there:
MyFragment fragment = new MyFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction tr = fm.beginTransaction();
tr.addToBackStack(fragment.getClass().getSimpleName());
tr.replace(R.id.fragment_root, fragment);
tr.commit();

My WebView does not finish loading

Hi I have totally no idea why my webview is not call the onPageFinished method, and the it was showing the loading dialog all the time, I hope there is someone out there help me for my this issue. In the Android manifest file I already put the internet permission and also the network access state.
so this is my code:
public class MainActivity extends AppCompatActivity {
WebView mWebView;
RelativeLayout rLoading;
Map<String, String> header;
String urlToLoad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
rLoading = (RelativeLayout) findViewById(R.id.loading);
if ( isNetworkAvailable() == true ) //check if internet available or not
{
mWebView.setFocusable(true);
mWebView.setFocusableInTouchMode(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
urlToLoad = "https://www.google.com/";
UsernamePasswordCredentials creds= new UsernamePasswordCredentials("username", "password");
Header credHeader = BasicScheme.authenticate(creds, "UTF-8", true);
header = new HashMap<String, String>();
header.put(credHeader.getName(), credHeader.getValue());
//show loading dialog
mWebView.loadUrl(urlToLoad, header);
mWebView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
rLoading.setVisibility(View.GONE);
}
});
}
else //Not connected
{
Toast.makeText(
this,
"No internet connection",
Toast.LENGTH_LONG
).show();
}
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityMgr.getActiveNetworkInfo();
/// if no network is available networkInfo will be null
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()){
mWebView.goBack();
}else {
super.onBackPressed();
}
}
}
Someone please help me
Try this Android WebView implementation:
webview= (WebView) findViewById(R.id.webview);
webview.loadUrl("www.google.com");
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//stop the ProgressBar
mProgressBar.setVisibility(View.INVISIBLE);
}
});
You can do it by this way
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap facIcon) {
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
}
});

trying to open in webview a link thats jumps another page

yes I searched the site and didn't find something that helps me
because every one are saying use "shouldOverrideUrlLoading"
but that's not helping me - its not working
I am trying to open - In the same page an URL that supposed to open a new page link, but when I press it - nothing happens
I am using it as a fragment
public class FlightFragment extends Fragment {
private WebView webView;
public FlightFragment(){};
private String currentUrl;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.flight_fragment,container,false);
currentUrl = "https://flights.travelor.me/?locale=he";
webView = (WebView)rootView.findViewById(R.id.flightweb);
WebViewClient MyWebViewClient= new WebViewClient();
MyWebViewClient.shouldOverrideUrlLoading(webView, currentUrl);
ourWebViewClient(currentUrl);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new FlightFragment.MyBrowser());
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (keyEvent.getAction() == keyEvent.ACTION_DOWN) {
if (webView.canGoBack()) {
webView.goBack();
return true;
}
}
return false;
}
});
webView.loadUrl(currentUrl);
return rootView;
}
public void ourWebViewClient(String currentUrl) {
this.currentUrl = currentUrl;
}
private class MyBrowser extends WebViewClient {
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.equals(currentUrl)) {
view.loadUrl(request.getUrl().toString());
}
return true;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equals(currentUrl)) {
view.loadUrl(url);
}
return true;
}
}
}
You are returning false when your url is intercepted, try changing like this
webView.setWebViewClient(new WebViewClient() {
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equals(currentUrl)) {
Intent intent=new Intent(CurrentActivity.this,NewActivity.class);
intent.putExtra("url to load in NewActivity",url);
startActivity(intent); //get this url using getextra in new activity
}
}
}});
If your target version is >= 26
then override both the function below
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
Because shouldOverrideUrlLoading(WebView view, String url) is deprecated since Android N. Write the code for Android N and above in the first override method.
In your code remove this
webView.setWebViewClient(new WebViewClient() {
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equals(currentUrl)) {
return false;
}
view.loadUrl(url);
return true;
}
}});
as you are setting your WebViewClient again below this code and change your MyBrowser class
private class MyBrowser extends WebViewClient {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return true;
}
}
#golan Try to make your Webview fragment as a Activity which will work like a generic view and will open web pages as per requirement based on input url.
shouldOverrideUrlLoading loading method will required if you want to check the input urls.
Do all required web settings like
WebSettings webSettings = webviewBinding.detailWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDisplayZoomControls(false);
webSettings.setLoadWithOverviewMode(false);
webSettings.setUseWideViewPort(true);
webSettings.setSupportZoom(true);
Override onBackPressed() method with following code:
if (detailWebView.canGoBack()) {
detailWebView.goBack();
}
else {
super.onBackPressed();
}
The canGoBack() will allow you to go back upto all web pages and if no more pages to go back it will redirect to you to last loaded activity or view.

android: WebView canGoBack() Error

I'm following (Building Web Apps in WebView) tutorial, but I have problem with (Navigating web page history) I'm runing it on my device and I click on a link but when I click the back button the application shuts down:
That's my activity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
WebView myWebView = null;
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
}
public class MainActivity extends Activity {
WebView myWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}

Categories

Resources