Cómo pasar una cadena html a webview en android


141

Hola, estoy analizando xml y luego cargándolo a la vista web, después de analizar estoy creando cuatro cadenas para poder agregar todas las cadenas a una vista. Puedo obtener dos vistas en la vista web pero no las dos primeras cadenas.

Pls me sugiere con mi código, dónde me estoy equivocando y cuál es la forma correcta de obtener las cadenas HTML formateadas en la vista web. Eche un vistazo a mi código y ayúdeme a resolver este problema.

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        String chapterTitle = "";
        String SubChapterTitle="";
        String chapterIntro ="";
        String chapterContent="";
        View view = convertView;
        if (convertView == null) {
            // view = inflater.inflate(resourceid, null);
            view = getLayoutInflater().inflate(R.layout.webviewitem, null);
        }
        synchronized (view) {
            WebView wv = (WebView) view.findViewById(R.id.contentWebView);

            WebSettings settings = wv.getSettings();
            settings.setUseWideViewPort(true);
            settings.setLoadWithOverviewMode(true);
            settings.setJavaScriptEnabled(true);
            settings.setDefaultZoom(ZoomDensity.FAR);
            // wv.setBackgroundColor(0);
            wv.setVerticalScrollBarEnabled(false);
            wv.setHorizontalScrollBarEnabled(false);
            /*String txtChapTitle = Intro.book.getsecretList().get(position)
                    .getChtitle().toString();*/

            if (!(Intro.book.getsecretList().get(position).getChtitle()
                    .toString().equals(""))){
            chapterTitle = "<b><fontSize=4>"+Intro.book.getsecretList().get(position)
            .getChtitle().toString()+"</font></b>";
            }
            if (!(Intro.book.getsecretList().get(position)
                    .getSubtitle() == null)) {
                SubChapterTitle = "<b><fontSize=4>"+Intro.book.getsecretList().get(position)
                .getSubtitle().toString()+"</font></b>";
            }
            if (!(Intro.book.getsecretList().get(position)
                    .getIntro() == null)) {
            chapterIntro = "<b><fontSize=2>"+Intro.book.getsecretList().get(position)
                .getIntro().toString()+"</font></b>";
            }
            if (!(Intro.book.getsecretList().get(position)
                    .getContent() == null)) {
            chapterContent = "<fontSize=2>"+Intro.book.getsecretList().get(position)
                .getContent().toString()+"</font>";
            }

            StringBuilder content = new StringBuilder();
            content.append(chapterTitle+SubChapterTitle+chapterIntro+chapterContent);

            JsInterface Jsi = new JsInterface();
            Jsi.wordDef = content ;
            Log.v("Content", "" +content);
            wv.addJavascriptInterface(Jsi, "interfaces");

            wv.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    view.setHapticFeedbackEnabled(false);
                }
            });

            wv.setWebChromeClient(new WebChromeClient() {
                @Override
                public boolean onJsAlert(WebView view, String url,
                        String message, JsResult result) {
                    return super.onJsAlert(view, url, message, result);
                }
            });

            wv.loadUrl("file:///android_asset/wordview.html");
        }
        return view;
    }
}

Puedo obtener el capítulo Introducción y el contenido del capítulo en la vista web, pero no las dos primeras cadenas, por favor, ayúdenme amigos.

Respuestas:


190

He hecho con éxito por debajo de la línea

 //data == html data which you want to load 
 WebView webview = (WebView)this.findViewById(R.id.webview);
 webview.getSettings().setJavaScriptEnabled(true);
 webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");

¿agrega esto a la <head> en index.php / index.html?
— El beseti

1
si quieres, de lo contrario estará bien
— Siddhpura Amit

Actualiza la interfaz de usuario después de un pequeño retraso. ¿Cómo arreglar esa cosa?
— Narendra Singh

¿Puedo usar "text / html", "UTF-8", si quiero pasar el html a la función javascript usando webView.loadUrl ("javascript: MyFunction (data," text / html "," UTF-8 ")?
— user1788736

No, no he usado así
— Siddhpura Amit

168

Para cargar sus datos en WebView. Llame al método loadData () de WebView

webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");

Puedes consultar este ejemplo

http://developer.android.com/reference/android/webkit/WebView.html


Lo intenté con eso, todavía no sucede, también lo intenté con loadbaserul
— cavallo

¿Se supone que eso funciona con una cadena que contiene JavaScript? No me funciona
— Edu

27
debería serwebView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");
— Jaroslav

55
El "text / html; charset = utf-8" hace una gran diferencia, los caracteres de símbolo no se representan correctamente sin él.
— Mic Fok

29

Pasar nulo sería mejor. Los códigos completos son como:

WebView wv = (WebView)this.findViewById(R.id.myWebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadDataWithBaseURL(null, "<html>...</html>", "text/html", "utf-8", null);

¿agrega esto a la <head> en index.php / index.html?
— El beseti

@mthethelelibeseti se trata de códigos de Android, no de HTML. ¿O entendí mal tu pregunta?
— Jeffrey Neo

Es la solución de trabajo para todo tipo de cadenas html. Gracias @JeffreyNeo
— Akash Bisariya

2

Cargar datos normales no funcionaba para mí, convertir a Base64 funcionaba bien.

String unencodedHtml ="<html><body>'%28' is the code for '('</body></html>";
tring encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");

Encuentre detalles en WebView

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.