Yesterday I began a project for my father to have all his web radio's on an app using the embed code that radionomy provides.
I think the code is well formed but when I execute the application, the app just shows a blank page.
Main activity code:
import android.annotation.TargetApi;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class CalsicaActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calsica);
WebView clasica = new WebView(this);
clasica.getSettings().setJavaScriptEnabled(true);
setContentView(clasica);
clasica.setWebViewClient(new WebViewClient() {
#Override
#TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView clasicav, WebResourceRequest request) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
#Override
#SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView clasicav, String url) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
});
//clasica.loadUrl("file:///android_asset/index.html");
}
}
Html code:
<html>
<head><script>
(function (win, doc, script, source, objectName) {
(win.RadionomyPlayerObject = win.RadionomyPlayerObject || []).push(objectName);
win[objectName] = win[objectName] || function (k, v) {
(win[objectName].parameters = win[objectName].parameters || { src: source, version: '1.1' })[k] = v;
};
var js, rjs = doc.getElementsByTagName(script)[0];
js = doc.createElement(script);
js.async = 1;
js.src = source;
rjs.parentNode.insertBefore(js, rjs);
}(window, document, 'script', 'https://www.radionomy.com/js/radionomy.player.js', 'radplayer'));
radplayer('url', 'bravo-clasic');
radplayer('type', 'medium');
radplayer('autoplay', '1');
radplayer('volume', '50');
radplayer('color1', '#000000');
radplayer('color2', '#ffffff');
</script></head>
<body>
<div class="radionomy-player"></div>
</body>
</html>
I already added <uses-permission android:name="android.permission.INTERNET"/> on the android manifest.
I have no idea of what I could've done wrong, I'd appreciate some help.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView clasica = new WebView(this);
clasica.loadUrl("file:///android_asset/index.html");
setContentView(clasica);
}
try this first load url in to your web view that perform setContentView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView clasica = new WebView(this);
clasica.getSettings().setJavaScriptEnabled(true);
clasica.loadUrl("file:///android_asset/index.html");
setContentView(clasica);
//clasica.loadUrl("file:///android_asset/index.html");
}
Well below code will be called only when load some url (by loadUrl() method ). Please check method signature it says should override.
By setting webview client you are just stating that what should happen during load time. But the things that your trying to make happen should start first. Am i making any sense ?
clasica.setWebViewClient(new WebViewClient() {
#Override
#TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView clasicav, WebResourceRequest request) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
#Override
#SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView clasicav, String url) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
});
Solution :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_calsica);
WebView clasica = new WebView(this);
clasica.getSettings().setJavaScriptEnabled(true);
// remove below code you dont need this
/* clasica.setWebViewClient(new WebViewClient() {
#Override
#TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView clasicav, WebResourceRequest request) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
#Override
#SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView clasicav, String url) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
});*/
// you need this line
clasica.loadUrl("file:///android_asset/index.html");
setContentView(clasica);
}
Related
I'm developing an Android app. In past projects, I used to use WebView to show web content. This gave me the capability to intercept events like page loaded and so on. The important thing that I was able to do was to get page content and use it in the Java code. To be honest, I use a trick, but it works. I put the essential code of my fragment to use a WebView to open an URL, do something and when the user arrives in a specific page and get the page content (with MyJavaScriptInterface):
public class LoginFragment extends MyAppFragment {
#BindView(R.id.webView)
public WebView webView;
public LoginFragment() {
}
#Override
public void onResume() {
super.onResume();
webView.setVisibility(View.VISIBLE);
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
initBinder(rootView);
...
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.setWebViewClient(mWebViewClient);
/* Register a new JavaScript interface called HTMLOUT */
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webView.loadUrl(getResources().getString(R.string.url_login).trim());
return rootView;
}
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface {
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(String token) {
if (token.contains(URL_LANDING)) {
...
}
}
}
private WebViewClient mWebViewClient = new WebViewClient() {
#Nullable
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
Logger.info("shouldInterceptRequest " + request.getUrl().toString());
if (URL_LANDING_SESAPP.equals(request.getUrl().toString())) {
...
}
return super.shouldInterceptRequest(view, request);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
...
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onLoadResource(WebView view, String url) {
...
super.onLoadResource(view, url);
}
#Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
...
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
...
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pageLoading = false;
if (loginDone) {
view.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('body')[0].innerHTML);")
}
}
};
}
Is there an equivalent way to do this with Chrome Custom Tags? Thank you in advance.
I'm using android studio
I need to replace the body of an html document with other codes, this is an example that I tried to follow
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grafico);
wv = (WebView) findViewById(R.id.prova);
wv.setWebViewClient(new MyWebViewClient());
new BackgroundWorker().execute();
}
// load links in WebView instead of default browser
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#RequiresApi(21)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return false;
}
}
private class BackgroundWorker extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
getDarewod();
return null;
}
public void getDarewod() {
try {
Document htmlDocument = Jsoup.connect(url).get();
Element element = htmlDocument.select("#gkHeaderMod > div.grafico-quotazione").first();
// replace body with selected element
htmlDocument.body().empty().append(element.toString());
final String html = htmlDocument.toString();
uiHandler.post(new Runnable() {
#Override
public void run() {
wv.loadData(html, "text/html", "UTF-8");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
I want to replace the all body with the code in my element variable. However this line doesn't works. How can I do?
htmlDocument.body().empty().append(element.toString());
Wondering how to make webview go back.
Tried putting in the webview back on press but it seems that with my code it's not working. Not sure if i initiated it, still confused about this.
Also is it possible to get rid of scrollbars in webview? i found some posts about it but am still on the fence about how exactly to put it into my code
package com.webapp.area956;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebViewClient yourWebClient = new WebViewClient()
{
// Override page so it's load on my view only
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// This line we let me load only pages inside Firstdroid Webpage
if ( url.contains("area956") == true )
// Load new URL Don't override URL Link
return false;
// Return true to override url loading (In this case do nothing).
return true;
}
};
String url = "http://www.area956.com";
WebView view = (WebView) this.findViewById(R.id.webView1);
view.setWebViewClient(yourWebClient);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadUrl(url);
}
public void onBackPressed (){
if (WebView.canGoBack()) {
WebView.goBack();
}
else {
super.onBackPressed();
finish();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Have webview as a class member
WebView view;
#Override
public void onCreate(Bundle savedInstanceState) {
Then initialize
view = (WebView) this.findViewById(R.id.webView1);
view.setWebViewClient(yourWebClient);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadUrl(url);
Then use onKeyDown
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
view.goBack();
return true;
}
else
{
finish();
return true;
}
}
You have declared WebView view in onCreate and initialized it there. So it becomes local to onCreate.
Edit:
You can also use onBackPressed as of 2.0
http://android-developers.blogspot.in/2009/12/back-and-other-hard-keys-three-stories.html
public void onBackPressed (){
super.onBackPressed();
if (view.canGoBack()) {
view.goBack();
}
else {
finish();
}
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview1);
web.setWebChromeClient(new MyWebChromeClient());
web.addJavascriptInterface(new DemoJavaScriptInterface(), "temp_1");
web.loadUrl("file:///android_asset/temp_1.html");
}
}
final class DemoJavaScriptInterface {
private Handler mHandler = new Handler();
WebView web;
DemoJavaScriptInterface() {
}
public void clickOnAndroid() {
mHandler.post(new Runnable() {
public void run() {
web.loadUrl("javascript:init();");
}
});
}
}
final class MyWebChromeClient extends WebChromeClient {
private static final String LOG_TAG = "WebViewDemo";
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.e(LOG_TAG, message);
result.confirm();
return true;
}
}
Try to write this line
web = (WebView) findViewById(R.id.webview1);
web.setWebChromeClient(new MyWebChromeClient());
web.getSettings().setJavaScriptEnabled(true);
web.addJavascriptInterface(new DemoJavaScriptInterface(), "temp_1");
web.loadUrl("file:///android_asset/temp_1.html");
[2]: Both Elements are coming from html file ,when going to click on "Click It" nothing happens instead of displaying xml data that i want
hello i am new to android developing,
I want to set my javscript turn on in my android webview. I tried everything, but it doesn't work. My code below is my webview class. I hope someone can help me.
package visuals.Webview;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class VisualsActivity extends Activity {
/** Called when the activity is first created. */
final Activity activity = this;
WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
// webview.setWebViewClient(new myWebClient());
webview.loadUrl("http://192.168.0.62/lastversion/index.php");
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setUserAgentString(getString(R.string.user_agent_suffix));
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
return true;
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
return true;
} else {
view.loadUrl(url);
return true;
}
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Thank you for helping
WebView webView;
webView.getSettings().setJavaScriptEnabled(true);
Pretty easy :)
webview.getSettings().setPluginState(PluginState.ON);
or when using older version ( < API 8)
webView.getSettings().setJavaScriptEnabled(true);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
And if you want your webview's javascript to be able to interact with your android application. Take a look at webview's addJavascriptInterface method documentation.