'WebView is not loading page in Android 9.0?

 public abstract class MainActivity extends AppCompatActivity {

        private static WebView web;
        private WebView mWebView;
        private java.lang.String url;
        Boolean isInternetPresent = false;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo i = manager.getActiveNetworkInfo();
            boolean hasConnect = (i != null && i.isConnected() && i.isAvailable());

            if (hasConnect) {
            } else {
            }
            Timer repeatTask = new Timer();
            repeatTask.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mWebView.loadUrl("http://www.smedk.ru/wp-content/uploads/files/education/rasp/1151.htm");
                        }
                    });
                }
            }, 0, 60000);

            setContentView(R.layout.activity_main);
            final ProgressDialog pd = ProgressDialog.show(MainActivity.this, "Загрузка расписания...", "Обновление данных...", true);
            mWebView = (WebView) findViewById(R.id.web1);
            mWebView.getSettings().setJavaScriptEnabled(true);
            if (savedInstanceState == null) {
                mWebView.loadUrl("http://www.smedk.ru/wp-content/uploads/files/education/rasp/1151.htm");
                mWebView.getSettings().setJavaScriptEnabled(true);
                mWebView.getSettings().setUseWideViewPort(true);
                String newUA = "User Agent";
                newUA = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0";
                mWebView.getSettings().setUserAgentString(newUA);
                mWebView.getSettings().setLoadWithOverviewMode(true);
                mWebView.clearCache(true);
                mWebView.getSettings().setBuiltInZoomControls(true);
                mWebView.getSettings().setSupportZoom(true);
                mWebView.getSettings().setDisplayZoomControls(false);
            }
            mWebView.setWebViewClient(new MyWebViewClient());
            mWebView.setWebViewClient(new WebViewClient() {
                public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
                    try {
                        webView.stopLoading();
                    } catch (Exception e) {
                    }

                    if (webView.canGoBack()) {
                        webView.goBack();
                    }

                    webView.loadUrl("about:blank");
                    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                    alertDialog.setTitle("Нет интернет подключения!");
                    alertDialog.setMessage("Пожайлуйста убедитесть включен ли " +
                            "Wi-Fi или мобильные данные и повторите попытку. ");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });

                    alertDialog.show();
                    super.onReceivedError(webView, errorCode, description, failingUrl);
                }

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    pd.show();
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    pd.dismiss();
                    Toast.makeText(MainActivity.this, "Расписание загружено", Toast.LENGTH_SHORT).show();
                    Toast.makeText(MainActivity.this, "Обновление данных завершено", Toast.LENGTH_SHORT).show();
                    String webUrl = mWebView.getUrl();
                }
            });
        }




        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            mWebView.saveState(outState);
        }

        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onSaveInstanceState(savedInstanceState);
            mWebView.restoreState(savedInstanceState);
            mWebView.setDownloadListener(new DownloadListener() {

                public void onDownloadStart(String url, String userAgent,
                                            String contentDisposition, String mimetype,
                                            long contentLength) {

                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                    request.allowScanningByMediaScanner();

                    request.setNotificationVisibility(
                            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                    request.setDestinationInExternalPublicDir(
                            Environment.DIRECTORY_DOWNLOADS,
                            "image.png");


                    DownloadManager dm = (DownloadManager) getSystemService(
                            DOWNLOAD_SERVICE);

                    dm.enqueue(request);

                }
            });
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
        }

        private void TakeScreenshot() {
            Picture picture = mWebView.capturePicture();
            Bitmap b = Bitmap.createBitmap(picture.getWidth(),
                    picture.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b);

            picture.draw(c);
            FileOutputStream fos = null;
            try {

                fos = new FileOutputStream("mnt/sdcard/Download/image.jpg");
                if (fos != null) {
                    b.compress(Bitmap.CompressFormat.JPEG, 100, fos);

                    fos.close();
                }
            } catch (Exception e) {
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
            return super.onCreateOptionsMenu(menu);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.exit:
                    finish();
                    break;
                case R.id.about:
                    Intent intent = new Intent(MainActivity.this, AboutActivity.class);
                    startActivity(intent);
                    break;
                case R.id.save:
                    Picture picture = mWebView.capturePicture();
                    Bitmap b = Bitmap.createBitmap(picture.getWidth(),
                            picture.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas c = new Canvas(b);
                    Toast.makeText(MainActivity.this, "Изображения сохранено в формате JPG", Toast.LENGTH_SHORT).show();
                    Toast.makeText(MainActivity.this, "Файл находится:" +
                            " /sdcard/image.jpg ", Toast.LENGTH_SHORT).show();
                    picture.draw(c);
                    FileOutputStream fos = null;
                    try {

                        fos = new FileOutputStream("mnt/sdcard/image.jpg");
                        if (fos != null) {
                            b.compress(Bitmap.CompressFormat.JPEG, 100, fos);

                            fos.close();
                        }
                    } catch (Exception e) {
                        break;
                    }
                    return true;
            }
            return false;
        }
    }

import android.webkit.WebView; import android.webkit.WebViewClient;

public class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
    @Override
    public void onPageFinished(WebView view, String url) {
        }
    }

I created an application to view call schedules and in general decided to test my application on an emulator. On older versions, webview is working fine, but when I decided to test on android 9, I wrote a web page unavailable.

On older versions of Android, webView loads fine, but on Android 9 not load. What is the reason?



Solution 1:[1]

Actually you should avoid using http, but if there is no way you can do this:

  1. Add @xml/network_security_config into your resources:

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">www.smedk.ru</domain>
        </domain-config>
    </network-security-config>
    
  2. Add this security config to your Manifest like this:

    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
    
        ...
    </application>
    
  3. Now you allowed using HTTP connection on www.smedk.ru subdomains.

You can read more in https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted

Note: The guidance in this section applies only to apps that target Android 8.1 (API level 27) or lower. Starting with Android 9 (API level 28), cleartext support is disabled by default.

Solution 2:[2]

This method works for all domains also with Android 9. Add this property to your Manifest like this:

<application
    ...
   android:usesCleartextTraffic="true"
    ...>
</application>

Solution 3:[3]

Please try to use secure url. Use https instead of http. Android 9.0 don't allow unsecured urls

Solution 4:[4]

Same issue occurred in my project but all of the above answers not worked for me. so after wasting a whole day on this issue,what i got is

In Android version 8.1/9/10 if your are using wrap_content attribute for height in WebView ,then it will always set to 0dp. In earlier versions(below 8.1) wrap_content in WebView works fine. but from 8.1 and above you can give height either statically or you can set it dynamically through program using setLayoutParameters(). And also add extra attribute to Application ( android:usesCleartextTraffic="true" ) in android manifest.

Solution 5:[5]

     //  Step 1:    in manifest :
  <application
        android:networkSecurityConfig="@xml/cleartextTrafficPermitted">
    //   Step 2:       
                  <uses-library
                         android:name="org.apache.http.legacy"
                        android:required="false" />
  </application>

    // Step 3 Create drawable XML>>cleartextTrafficPermitted  :

      <?xml version="1.0" encoding="utf-8"?>
        <network-security-config>
           <base-config cleartextTrafficPermitted="true">
           <trust-anchors>
              <certificates src="system" />
           </trust-anchors>
           </base-config>
        </network-security-config>

Solution 6:[6]

In android 10 finally, this is worked for me to load full content rather partial.

webView.loadDataWithBaseURL(null, contentText, "text/html", "UTF-8", null);

Solution 7:[7]

You can use Base64 to load HTML into WebView.

String base64version = Base64.encodeToString(htmlString.getBytes(), Base64.DEFAULT);
webView.loadData(base64version, "text/html; charset=UTF-8", "base64");

Solution 8:[8]

I had a problem with buttons and components not rendering in the webview, and the only option that solved my problems with buttons and other components that insisted on not rendering was:

webView.getSettings().setDomStorageEnabled(true);

I hope this helps someone.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alexey Ozerov
Solution 3 Meenakshi Khandelwal
Solution 4 vivek
Solution 5 Ashif
Solution 6 Shailendra Madda
Solution 7 gulshan shringi
Solution 8 Grégori Fernandes de Lima