How to pass html string to webview on android? - android

I am parsing xml and then loading it to web view. After parsing, I am creating four strings so that I could append all strings to one view. I am able to get two views on the web view, but not the first two strings.
Please suggest in my code, where I am going wrong and the correct way to get the formatted html strings on the web view.
#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;
}
}
I am able to get chapterIntro and chaptercontent on the web view, but not the first two strings.

i have successfully done by below line
//data == html data which you want to load
String data = "Your data which you want to load";
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadData(data, "text/html; charset=utf-8", "UTF-8");
Or You can try
webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);

To load your data in WebView. Call loadData() method of WebView
webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");
You can check this example
http://developer.android.com/reference/android/webkit/WebView.html

Passing null would be better. The full codes is like:
WebView wv = (WebView)this.findViewById(R.id.myWebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadDataWithBaseURL(null, "<html>...</html>", "text/html", "utf-8", null);

I was using some buttons with some events, converted image file coming from server.
Loading normal data wasn't working for me, converting into Base64 working just fine.
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");
Find details on WebView

After struggling the 2 hours of effort I found the solution
I want to run this code in webview
"<div style='width:100%;height:0px;position:relative;padding-bottom:56.250%;background:#000;'><iframe src='https://www.scorebat.com/embed/v/N09DWllRdlNraERnSXRRa1VJMTF4Zz09/?token=MTkxMTdfMTY1MjEyMzY2MF9kNzRkZTI4MTc3ZDAxZTNkOTQyOTg1OWE3MTcyYmFhY2EyYTI2YTZh&utm_source=api&utm_medium=video&utm_campaign=apifd' frameborder='0' width='100%' height='100%' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;'></iframe></div>"
But I only got the white screen after trying all the answers
Now do this as your code will also work
WebView webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setPluginState(WebSettings.PluginState.ON);
webview.getSettings().setMediaPlaybackRequiresUserGesture(false);
webview.setWebChromeClient(new WebChromeClient());
webview.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);
Here webview.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null); data is the HTML and javascript code
Add this line in your application tag as well
android:hardwareAccelerated="true"
I hope it will solve your issue

Related

Webview webcontent not loading

I am trying to load some HTML content (it is a hyperlink) in WebView. But when I click that link nothing is opening. But the same link is working in browser or iOS WebView perfectly.
The code I try:
htmlContent.getSettings().setJavaScriptEnabled(true);
htmlContent.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
htmlContent.loadDataWithBaseURL(null, Html.fromHtml(categoryItemsBean.getContent()).toString(), "text/html", "utf-8", null);
Value of categoryItemsBean.getContent().
<p><a title="كتاب مساعدة الأصدقاء"
href="https://www.manhal.com/platform/stories/demo/index.php?storyid=31"
target="_blank">كتاب مساعدة الأصدقاء </a></p>
Using loadData() method for loading html content on webview
Sample
String unencodedHtml ="<html><body>'%23' is the percent code for ‘#‘ </body></html>";
String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(),Base64.NO_PADDING);
htmlContent.loadData(encodedHtml, "text/html", "base64");
Convert your html content into base64

Android Studio Assets file cannot be accessed in WebView

I have been trying to figure out almost 2 weeks.
I have read previous posts and tried the proposed solutions but they didn't work for me.
Iam using Android Studio, I need Webview to access a local Jpg stored in Android Assets file.
Here is my code:
webView = (WebView) findViewById(R.id.webview);
startWebView("file:///android_asset/railchinese.jpg");
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
private void startWebView(String url) {
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl(url);
Here is the Assets location screen:
Kindlly let me know where is the mistake?..
Try this
String htmlData="<img src= railchinese.png>";
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "utf-8", null);

How can I read special character in webview?

I am developing an article managing android application, where articles are parsed through JSON.
All the values that are parsed by JSON are loaded in web view, but there are some special character that are not read by WebView.
{
web1 = (WebView) findViewById(R.id.webView2);
web1.setWebViewClient(new myWebClient());
web1.getSettings().setJavaScriptEnabled(true);
web1.loadData(c,"text/html", "UTF-32");
}
you can do like this way,
WebView webview = new WebView(collection.getContext());
webview.loadDataWithBaseURL(url, textWithQuotesIn, "text/html", "UTF-8", url);

Android WebView fit content to screen

I'm trying to fit webview content with screen but it display very ugly and show different results, please see below link for screen capture :
http://postimg.org/image/jy0g268p1/0294ca52/
http://postimg.org/image/603z8qhab/e06b655e/
Please find below my code :
WebSettings settings = webView.getSettings();
settings.setMinimumFontSize(30);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
webView.loadData(htmlContent, "text/html", "UTF-8");
webView.setInitialScale(1);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
Kindly advise what should I do to fit content nicely?
Really appreciate for any kind help.
This worked for me:
webview.Settings.LoadWithOverviewMode = true;
webview.Settings.UseWideViewPort = true;
I think I have found my own solution, I put here for someone who need it in future.
I just create one method to change head of html :
public static String changedHeaderHtml(String htmlText) {
String head = "<head><meta name=\"viewport\" content=\"width=device-width, user-scalable=yes\" /></head>";
String closedTag = "</body></html>";
String changeFontHtml = head + htmlText + closedTag;
return changeFontHtml;
}
And I'm using it inside webview as follow :
public static void displayHtmlText(String htmlContent, String message,
WebView webView,
RelativeLayout videoLayout, LinearLayout standardLayout, LinearLayout webviewLayout){
WebSettings settings = webView.getSettings();
settings.setMinimumFontSize(18);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
webView.setWebChromeClient(new WebChromeClient());
String changeFontHtml = Util.changedHeaderHtml(htmlContent);
webView.loadDataWithBaseURL(null, changeFontHtml,
"text/html", "UTF-8", null);
webviewLayout.setVisibility(View.VISIBLE);
standardLayout.setVisibility(View.GONE);
videoLayout.setVisibility(View.GONE);
}
So my content in webview now is fit to device and can show nicely.
I have create my own method with set background color and font color also.
WebSettings settings = desc.getSettings();
settings.setMinimumFontSize(50);
desc.getSettings().setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
desc.setWebChromeClient(new WebChromeClient());
String changeFontHtml = changedHeaderHtml(description);
desc.setBackgroundColor(context.getResources().getColor(R.color.all_app_bg_color));
desc.loadDataWithBaseURL(null, changeFontHtml,"text/html", "UTF-8", null);
desc.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:document.body.style.setProperty(\"color\", \"white\");"
);
}
});
public static String changedHeaderHtml(String htmlText) {
String head = "<head><meta name=\"viewport\" content=\"width=device-width, user-scalable=yes\" /></head>";
String closedTag = "</body></html>";
String changeFontHtml = head + htmlText + closedTag;
return changeFontHtml;
}

Facebook like for android

String htmlCodeGoesHere="<div id=\"fb-root\"></div>"+
"<script>(function(d, s, id) {"+
"var js, fjs = d.getElementsByTagName(s)[0];"+
"if (d.getElementById(id)) {return;}"+
"js = d.createElement(s); js.id = id;"+
"js.src = \"//connect.facebook.net/en_US/all.js#xfbml=1&appId="xxxxxxxxxxx"\";"+
"fjs.parentNode.insertBefore(js, fjs);"+
"}(document, 'script', 'facebook-jssdk'));</script>"+
"<div class=\"fb-like\" data-href=\"http://www.facebook.com/xxxxxxxxx\" data-send=\"true\" data-width=\"450\" data-show-faces=\"true\"></div>";
WebView webview=new WebView(this);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSavePassword(false);
webview.getSettings().setBuiltInZoomControls(false);
webview.getSettings().setUseWideViewPort(true);
//webview.getSettings().setLoadWithOverviewMode(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.setHorizontalScrollBarEnabled(false);
webview.setBackgroundColor(0xff2e2e2e);
webview.loadDataWithBaseURL(null, htmlCodeGoesHere, "text/html", "utf-8", null);
this.addContentView(webview,params);
trying to add js and div to webview. showing a blank screen.
i am trying to do like functionality for android app. please help me.
Check the output of your logcat and add something like this:
/* WebChromeClient must be set BEFORE calling loadUrl! */
view.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
Log.e("js ", message);
return false;
}
});/ // for debugging convenience.
to also log the javascript errors to logcat.

Categories

Resources