28

I have been researching for 2 days and I haven't found a similar problem anywhere on the internet!

From the main activity, I'm trying to open a new activity containing a webview that will show an html page (about.html) in the android_asset folder.

I'm able to launch the new activity (test.java) with the webview properly displayed but the webpage content just doesn't show up. Even the webview's vertical scrollbar is displayed (as the page content is relatively long) and I can scroll the page up and down but with no content in it!

package com.example.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class test extends Activity {
private TextView apppagetitle;
private WebView browser_rn;

@Override
public void onCreate(Bundle saveInstanceState) {
    super.onCreate(saveInstanceState);

    setContentView(R.layout.test);

    browser_rn=(WebView)findViewById(R.id.webkit);
    browser_rn.getSettings().setJavaScriptEnabled(true);
    browser_rn.getSettings().setPluginsEnabled(true);
    browser_rn.setScrollBarStyle(0);       

    final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    apppagetitle=(TextView)findViewById(R.id.apppagetitle);


    browser_rn.setWebViewClient(new WebViewClient() {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;
        }

        public void onPageFinished(WebView view, String url) {               
            apppagetitle.setText(browser_rn.getTitle());                
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            if (!isInternetOn()) {
                alertDialog.setTitle("Connection Error");
                alertDialog.setMessage("You need to be connected to the internet.");
            } else {
                alertDialog.setTitle("Error");
                alertDialog.setMessage(description);
            }
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            alertDialog.show();
        }
    });

    browser_rn.loadUrl("file:///android_asset/about.html");
}

public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        browser_rn.clearCache(true);
        browser_rn.clearHistory();
        this.finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
}

The weird thing is that the new activity (test.java) can successfully get and display the webpage title in the textview when I call webview.gettitle() but the html content just doesn't render in the webview. All I see is a blank screen with scrollbars. I suspect it is the boolean "shouldOverrideUrlLoading" that might be causing it.

Update:

Thanks for replying.

test.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.example.test"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/green"
>
<TextView   
android:id="@+id/apppagetitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:text="Odd News"
android:textSize="25px"
android:padding="10px"
/> 
</LinearLayout>
<LinearLayout
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
<WebView  
android:id="@+id/webkit"
android:layout_width="fill_parent" 
android:layout_height="0px"
android:layout_weight="1"
/> 
</LinearLayout>
</LinearLayout>

about.html is as simple as what is below.

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>About</title> 
</head> 
<body> 
<h3 style="color:#0066dd">About</h3>  

<p>Some text here...</p>

</body> 
</html>

Oh yes, and I forgot to mention earlier that with the same piece of code, the about.html would sometimes show up if I force-stop and restart the app on my phone. However, it would then not appear in subsequent launches. On occasions when it successfully shows up about.html and I press the back button to return to the main activity, it will disappear again when I re-launch the activity from the main activity. I'm lost but I have a strong feeling it is "shouldOverrideUrlLoading" that I'm not doing correctly.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Lost
  • 281
  • 1
  • 3
  • 3

11 Answers11

8

Don't try to load the given url in shouldOverrideUrlLoading, and don't return true from it in your case either. Really, from what it looks like you're trying to do, you shouldn't need to override it at all.

Returning true from shouldOverrideUrlLoading indicates to the WebView that it should not load the specified URL. What you're doing - telling the WebView to begin loading it again - is likely to cause some sort of internal loop inside the WebView, which I'd guess is why you're seeing odd behavior.

tophyr
  • 1,658
  • 14
  • 20
  • Agree. You should not be overriding "shouldOverrideUrlLoading" unless you need to make decisions at runtime on whether to load the url. In your case, you just want it to load. You're creating an infinite loop by loading the url (again) in this method. – mikejonesguy Nov 13 '12 at 15:00
3

Use this

browser_rn.loadDataWithBaseURL(url); 

instead of

browser_rn.loadUrl("file:///android_asset/about.html");
SilentKiller
  • 6,944
  • 6
  • 40
  • 75
user181291
  • 719
  • 1
  • 5
  • 7
  • 1
    It may have changed since 2012, but now loadDataWithBaseURL() requires four arguments. See http://developer.android.com/reference/android/webkit/WebView.html#loadDataWithBaseURL(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String) – Tony Adams Apr 14 '16 at 18:29
  • `loadDataWithBaseURL()` instead of `loadData()` helped – Sigmund Dec 09 '19 at 12:23
1

I updated last week from 2.3.4 to 4.0 on my HTC Sensation. The two apps i wrote had a local HTML-Contact site. On 2.3 it ran fine, now i get a "Webpage not available" site.

I found another post here on this site with the comment: "Via some discussion with a Google engineer it seems that they've made the decision that the file:// scheme is insecure."

See here for the workaround: Android 4.0.1 breaks WebView HTML 5 local storage?

Community
  • 1
  • 1
1

I can give the another way to solve this problem. Just copy the asset file into the data path "/data/data/org.test.test/" and load it to WebView in the following way.

String strHTMLFilePath = "file:///data/data/org.test.test/Files/help_android.html";
webView.loadUrl(strHTMLFilePath);

Use the following code to copy the HTML file from asset to data path

void getAssetFiles() {

    String  WriteFileName = "/data/data/org.test.test/";
        try {
            String list[] = thisActivity.getAssets().list("Files");
            String outFileName = WriteFileName+"Files/";
            if (list != null)
                for (int i=0; i<list.length; ++i){                          
                if(!new File(outFileName).exists()){
                    new File(outFileName).mkdirs();
                }

                OutputStream myOutput = new FileOutputStream(outFileName+list[i]);

                byte[] buffer = new byte[1024];
                int length;

                String strWritePath = "Files" + "/" + list[i];

                InputStream myInput = thisActivity.getAssets().open(strWritePath);

                while ((length = myInput.read(buffer))>0){
                    myOutput.write(buffer, 0, length);
                }
                myInput.close();

                myOutput.flush();
                myOutput.close();                           
               }
        } catch (IOException e) {

        }

    }
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
Durai
  • 481
  • 6
  • 10
1

You need to return true in shouldOverrideUrlLoading method

public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
Vikalp Patel
  • 10,669
  • 6
  • 61
  • 96
1

Add following line in your activity which contains WebView activity android:hardwareAccelerated="false"

hope it will help

sappu
  • 6,665
  • 4
  • 19
  • 18
1

Try this change in your text.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.example.test"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".text" > <!-- Here is the change -->
<LinearLayout
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/green"
>
<TextView   
android:id="@+id/apppagetitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:text="Odd News"
android:textSize="25px"
android:padding="10px"
/> 
</LinearLayout>
<LinearLayout
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
<WebView  
android:id="@+id/webkit"
android:layout_width="fill_parent" 
android:layout_height="0px"
android:layout_weight="1"
/> 
</LinearLayout>
</LinearLayout>
Dhasneem
  • 4,037
  • 4
  • 33
  • 47
1

May be it was due to hardware acceleration

webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

worked for me.

https://developer.android.com/guide/topics/graphics/hardware-accel.html

0

meet same problem.

I tried the solutions in link. It failed all the time.

My situation is same to it. There is H5 video in webview,It does well first time and fail then. when It fails,I found some message from log

  1. onProgressChanged and not to 100% whitout more progress
  2. chromium: [ERROR:in_process_view_renderer.cc(193)] Failed to request GL process. Deadlock likely: 0

when I invoke method

mWebView.loadUrl(url)//webview's height is 0px now
//some code change webView's height here

My solutions is set webview height some dp or match_parent default. It works well!

Cui Qing
  • 157
  • 2
  • 5
-1

Just delete your virtual device and create a new one or test on your own Phone.

Jayant Dhingra
  • 526
  • 6
  • 11
-3

try change in your code

 public boolean shouldOverrideUrlLoading(WebView view, String url) { 
                        return true; 
        } 

Have a look at this tutorial.

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • Please read the tutorial attentive and for the end before making such wrong conclusion. – Евгений Шевченко Apr 28 '16 at 13:34
  • What is your problem? @ЕвгенийШевченко 1 - Solution is only the same which is mentioned in answer. 2 - Blog , describes the same thing with example. 3 - This is 2012's thread. 4 - the same answer is given by 3 different users, why not downvote them too? – MKJParekh Apr 29 '16 at 05:57
  • shouldOverrideUrlLoading should return true only in case when WebView should not load the page! Its used for filtering, TRUE means that URL should be overriden as meant by method name, so your answer completely wrong. Please read the reference, before answering: http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading(android.webkit.WebView, java.lang.String) . PS:Don't worry, Vikalp Patel's answer downvoted too – Евгений Шевченко May 02 '16 at 07:56
  • @ЕвгенийШевченко Put references aside, Check practically. Did you ever have such issue? how you solved? have you written your answer here?. The given answer solves the issue and it's used by many developers around. I don't care about getting up/down voted, the point you misunderstood and still suggesting answers wrong. – MKJParekh May 02 '16 at 09:18
  • I listed this topic because I have same issue, but it's not with WebView for now, WebView's "white page" in the past for me, because I found real solutions, not recursive URL loading as you and Vikalp Patel offers. Sorry for that my patience finished on this topic because I'm tired to see a lot of such wrong answers according to shouldOverrideUrlLoading method! In my previous comment at the end you can find reference and there you may read what the method means. If its not enough, you may re-read page which you linked in your answer - its only one right thing there. – Евгений Шевченко May 02 '16 at 14:28
  • PS: Main thing that was wrong in the question is "view.loadUrl(url);" string in shouldOverrideUrlLoading method. Other issues have various solutions (manual onDraw() calling, reAttachement or drawState updation) according to Android SDK version till v19, where Chromium bring new life for WebView. – Евгений Шевченко May 02 '16 at 14:36