How can I load video into an app from backend? - android

My problem is how to a show video from the admin backend into my android app. When I and adding the iframe from TinyMCE Editor, it looks like this:
But in my android app I get this:
I cannot understand what exactly is happening and I'm sharing you a section of my code of what I'm doing in the fragment.
if (item.getContent().length() != 0) {
mWebView.setVisibility(View.VISIBLE);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setMinimumFontSize(14);
String htmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<head>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>"
+ "<style type=\"text/css\">body{color: #525252;} img {max-width: 100%; height: auto}</style>"
+ "</head>"
+ item.getContent()
+ "";
mWebView.loadData(htmlContent, "text/html; charset=utf-8", "UTF-8");
} else {
mWebView.setVisibility(View.GONE);
}
if (item.getImgUrl().length() > 0) {
imageLoader.get(item.getImgUrl(), ImageLoader.getImageListener(mItemImg, R.drawable.img_loading, R.drawable.img_loading));
mItemImg.setVisibility(View.VISIBLE);
mItemImgSeparatorLine.setVisibility(View.VISIBLE);
} else {
mItemImg.setVisibility(View.GONE);
mItemImgSeparatorLine.setVisibility(View.GONE);
}
mPostTopSeparatorLine.setVisibility(View.GONE);
mPostMessage.setVisibility(View.GONE);
if (item.getAllowComments() == 0 && App.getInstance().getId() != 0) {
mPostTopSeparatorLine.setVisibility(View.VISIBLE);
mPostMessage.setVisibility(View.VISIBLE);
mPostMessage.setText(getString(R.string.msg_comments_disabled));
}
if (App.getInstance().getId() == 0) {
mPostTopSeparatorLine.setVisibility(View.VISIBLE);
mPostMessage.setVisibility(View.VISIBLE);
mPostMessage.setText(getString(R.string.msg_auth_prompt_comment));
}
}
For my Android App I'm working with a WebView as you can see in the above code. Do you have any idea why is it not working as expected? Thanks for your help.

You are trying to load an iFrame in WebView. To do so, use first create a string with the HTML.
String html = "<iframe width=\"560\" height=\"315\" src=\"your_src\" frameborder=\"0\" allowfullscreen></iframe>";
Now call loadData.
mWebview.loadData(html, "text/html", null);

Related

How to load correctly a string from asset html file in a webview

I have an html file in asset folder and i would like to load it in a webview. I would like to use the string, and not the file in order to replace the content of file when i want (keep only one file and change the content i want to display).
For example my html file is like this:
<!DOCTYPE html>
<html>
<head>
<title>This is demo</title>
</head>
<body>
<p data-height="265" data-theme-id="0" data-slug-hash="dYPxYp" data-default-tab="html,result" data-user="sckarolos" data-embed-version="2" data-pen-title="SVG Shape Example" class="codepen">
See the Pen SVG Shape Example
by sckarolos (#sckarolos) on CodePen.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
</body>
</html>
I have these two methods for reading the html file from assets as string and load it in a webview:
private String getHtmlFromAsset() {
InputStream is;
StringBuilder builder = new StringBuilder();
String htmlString = null;
try {
is = getAssets().open(htmlFilename);
if (is != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
htmlString = builder.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return htmlString;
}
/**
* Loads html page with the content.
*/
private void loadHtmlPage(WebView webView) {
String htmlString = getHtmlFromAsset();
if (htmlString != null) {
webView.loadDataWithBaseURL(null, htmlString, "text/html", "UTF-8", null);
}
else
Toast.makeText(this, "No such page", Toast.LENGTH_LONG).show();
}
And in my activity i use webview like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
AssetManager assetManager = getAssets();
//try to display html content
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
loadHtmlPage(webView);
}
On debuging i can see that my file read successfully and my string has the content of html file. But when i am trying load it in webview, the result is nothing. If i try to load the local html file using this:
webView.loadUrl("file:///android_asset/myFile.html");
then the file loads and displays successfully.
I suppose that my fault is in the way i use the string that i take back from getHtmlFromAsset and pass in loadHtmlPage.
Any help will be appreciated.
Here, code pan required javascript access so when link load you need to provide javascript access. this is working code also check into my emulator. Also, don't forget to give internet permission on the manifest.
XML:
<WebView
android:id="#+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA:
String str = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <title>This is demo</title>\n" +
"</head>\n" +
"<body>\n" +
"\n" +
"<p data-height=\"265\" data-theme-id=\"0\" data-slug-hash=\"dYPxYp\" data-default-tab=\"html,result\" data-user=\"sckarolos\" data-embed-version=\"2\" data-pen-title=\"SVG Shape Example\" class=\"codepen\">\n" +
" See the Pen SVG Shape Example\n" +
" by sckarolos (#sckarolos) on CodePen.</p>\n" +
"<script async src=\"https://production-assets.codepen.io/assets/embed/ei.js\"></script>\n" +
"\n" +
"\n" +
"</body>\n" +
"</html>";
WebView wv = findViewById(R.id.wv);
wv.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
wv.loadData(str, "text/html", "UTF-8");

Youtube video is not loaded in webview in android

I want to display youtube URL in a web view. But it is not loading into the web view.
Here is my code.
WebView web_view = (WebView) findViewById(R.id.web_view);
web_view.setWebViewClient(new WebViewClient());
web_view.getSettings().setJavaScriptEnabled(true);
web_view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
web_view.getSettings().setPluginState(WebSettings.PluginState.ON);
web_view.getSettings().setMediaPlaybackRequiresUserGesture(false);
web_view.setWebChromeClient(new WebChromeClient());
web_view.loadUrl("https://www.youtube.com/watch?v=s8n16rns-iM");
the video is not loaded into the web view.It is showing error:
[INFO: CONSOLE(16)] "The key "target-densitydpi" is not supported.", source: https://m.youtube.com/watch?v=s8n16rns-iM
try this
String frameVideo = "<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/watch?v=ue80QwXMRHg&app=desktop\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
WebView displayYoutubeVideo = (WebView) findViewById(R.id.mWebView);
displayYoutubeVideo.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = displayYoutubeVideo.getSettings();
webSettings.setJavaScriptEnabled(true);
displayYoutubeVideo.loadData(frameVideo, "text/html", "utf-8");
To get a html frame for a particular video, use this function with a Video Id,
public String getHtmlfromVideoId(String videoId) {
String html = "<iframe class=\"youtube-player\" " + "style=\"border: 0; width: 100%; height: 96%;"
+ "padding:0px; margin:0px\" " + "id=\"ytplayer\" type=\"text/html\" "
+ "src=\"http://www.youtube.com/embed/" + videoId
+ "?&theme=dark&autohide=2&modestbranding=1&showinfo=0&autoplay=1\fs=0\" frameborder=\"0\" "
+ "allowfullscreen autobuffer " + "controls onclick=\"this.play()\">\n" + "</iframe>\n";
return html;
}
Video Id usually comes after the v parameter of the youtube url. For example, the Video Id of https://www.youtube.com/watch?v=s8n16rns-iM&app=desktop is s8n16rns-iM
Once you get the html frame, load it directly in the WebView,
webView.loadData(html, "text/html", "UTF-8");

Play Vimeo video in Android , video url containing iframe

Hello i am working on android application in which i want to play vimeo videos , i am getting response from Api in json and playing video using webview and it is playing good , but the webview is displaying very small and the playing video is also small my problems are
I want playing video width to be according to android device width. I can get it from Displaymetrics but how to set to iframe ?
I want to inflate custom view of media controller for playing videos.
Custom controller like play pause icon
I am getting this kind of url response from api
<iframe src="https://player.vimeo.com/video/video_id" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
at video_id i am getting the video id
Below is the code which i used
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
String data_html=getexplore_list.get(pos).getVideo_url();
webView.loadDataWithBaseURL("http://vimeo.com", data_html, "text/html", "UTF-8", null);
Please Provide any solution or link will be grateful
use style in html,
String url = "<iframe src=\"" + videoUrl + "\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";
mViewHolder.webView.getSettings().setJavaScriptEnabled(true);
String yourData = "<div id='made-in-ny'></div>\n" +
"\n" +
"<script src='https://player.vimeo.com/api/player.js'></script>\n" +
"<script>\n" +
" var options = {\n" +
" id: 59777392,\n" +
" width: 540,\n" +
" loop: true\n" +
" };\n" +
"\n" +
" var player = new Vimeo.Player('made-in-ny', options);\n" +
"\n" +
" player.setVolume(0);\n" +
"\n" +
" player.on('play', function() {\n" +
" console.log('played the video!');\n" +
" });\n" +
"</script>";
mViewHolder.webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");
change id and width. it is working.

Android WebView link color

I am using WebView to show websites inside my application, and I was wondering is it possible to change link color and style which is by default blue and underlined?
I searched about it but there are all questions and solutions about removing the highlight around the link, nothing about the link itself. I just want to know is there some solution as easy as TextView's android:textColorLink or will I need to alter the website body somehow?
Thanks!
Okay, I managed to do it and wanted to share my way for the future visitors.
First I created a css file with the desired style, named style.css, saved under assets folder
a {color:purple; text-decoration:none}
Then, in the code I loaded the page as follows where content is the actual html content of the page
String htmlBody = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + content;
mWebView.loadDataWithBaseURL("file:///android_asset/", htmlBody, "text/html", "utf-8",
null);
That's it! Hope it helps somebody.
Here is an example of how to add html links and customize them:
WebSettings webViewSettings = webView.getSettings();
webViewSettings.setDefaultFontSize(AppSettings.defaultFontSize);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadDataWithBaseURL("file:///android_asset", Util.replaceLinkTags(myText), "text/html", "utf-8", null);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("file")) {
Intent intent = new Intent(MyActivity.this, MyActivity.class);
intent.putExtra("word", Uri.parse(url).getLastPathSegment());
startActivity(intent);
return true;
} else
return false;
}
});
public static String replaceLinkTags(String text) {
text = "<html><head>"
+ "<style type=\"text/css\">body{color:" + "#424242" + ";} a{color:#00B8D4; text-decoration:none; font-weight:bold;}"
+ "</style></head>"
+ "<body>" + text + "</body></html>";
String str;
while ((text.indexOf("\u0082") > 0)) {
if ((text.indexOf("\u0082") > 0) && (text.indexOf("\u0083") > 0)) {
str = text.substring(text.indexOf("\u0082") + 1, text.indexOf("\u0083"));
text = text.replaceAll("\u0082" + str + "\u0083", "" + str + "");
}
}
return text;
}

Android: WebView load image in center

I want to load an image at the web view, but it shows all at top_left of the web view. My picture is on the internet not local.
gifView.loadUrl(mImageUrl);
gifView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.getSettings().setLoadsImagesAutomatically(true);
if (mProgressBar != null) {
mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (mProgressBar != null) {
mProgressBar.setVisibility(View.VISIBLE);
}
}
});
Here is my xml:::
<WebView
android:id="#+id/gif_image"
android:background="#null"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Edit:i used:
String HTML_FORMAT = "<html><body style=\"text-align: center; background-color: null; vertical-align: middle;\"><img src = \"%s\" /></body></html>";
final String html = String.format(HTML_FORMAT, mImageUrl);
gifView.loadDataWithBaseURL("", html, "text/html", "UTF-8", "");
but my image only Horizontal Center,how to center
Try this.
myWebView.loadData("<html><head><style type='text/css'>body{margin:auto auto;text-align:center;} img{width:100%25;} </style></head><body><img src='www.mysite.com/myimg.jpeg'/></body></html>" ,"text/html", "UTF-8");
I did it by using some code and xml :
<WebView android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="251dp"
android:layout_below="#+id/download"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
and this (for horizental center) :
WebView loading = (WebView)rootView.findViewById(R.id.webview);
loading.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
loading.loadDataWithBaseURL("file:///android_asset/", "<html><center><img src=\"done.png\"></html>", "text/html", "utf-8", "");
Or this for (horizontal & vertical center) :
WebView loading = (WebView)rootView.findViewById(R.id.webview);
loading.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
loading.loadDataWithBaseURL("file:///android_asset/", "<html>\n" +
"<body bgcolor=\"white\">\n" +
" <table width=\"100%\" height=\"100%\">\n" +
" <tr>\n" +
" <td align=\"center\" valign=\"center\">\n" +
" <img src=\"loading.gif\">\n" +
" </td>\n" +
" </tr>\n" +
" </table>\n" +
"</body>", "text/html", "utf-8", "");
Try something like this:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
String data = "<body><center><img width=\"" + width + "\" src=\"" + url
+ "\" /></center></body></html>";
webview.loadData(data, "text/html", null);
Try this, this will make the content fit to your webview
WebView web = (WebView) findViewById(R.id.gif_image);
web.getSettings().setDefaultZoom(ZoomDensity.FAR);
Do you use Linear layout? So you will require to use the gravity property of the parent linear layout.
A good explanation of gravity in android: http://sandipchitale.blogspot.com/2010/05/linearlayout-gravity-and-layoutgravity.html
The reason is not in the webview, it is the html code.
W3c wants that "text-align" should no longer take effekt on block elements like images.
You can read more at center-image-using-text-align-center
So either you make your image display:inline or you center it in a different way e.g.
.center {
left: 50%;
margin-left: -50%;
}

Categories

Resources