Android webview not showing properly - javascript

I have an Android WebView and it is just showing the proper blue background of the site, but none of the content. I have the same site opening properly in an iOS webview.
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
if (url.contains("test.com")) {
return false;
}
}
// Otherwise allow the OS to handle things like tel, mailto, etc.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
return true;
}
});
mWebView.loadUrl("https://test.com");

Adding:
webSettings.setDomStorageEnabled(true);
fixed the issue.

Related

Change TextView Action when Button is clicked

In Android Studio I have made a TextView showing "dailyQuote1" when i press/tapping the TextView.
I also added a button with id "buttonquote2", when I press that button once I want that the "action" of the TextView to start showing "displayQuote2" instead of "displayQuote1" when press/tapping TextView.
How should the code for the button look like to do this?
TextView "action":
TextView mTextView = (TextView)findViewById(R.id.textViewNextQuote);
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayQuote1(); //I want this to change
}
});
for this What you can do is implement
View.OnClickListener with the class or activity you are working with and then check for the id of the view which is being clicked/tapped and choose the method according to the id. Like this
class MainActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView=findViewById....
Button button=findViewById...
textView.setOnClickListener(this)
button.setOnclickListener(this)
}
override onClick(View view) {
switch(view.getId())
{
case textView.getId():
displayQuote1();
case button.getId():
displayQuote2();
}
}
}
Try this:
public void buttonClick(View v)
{
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(displayQuote2());
}

triggering JavascriptInterface from a android webview

I followed an instruction to trigger the JavascriptInterface from a webview, but it isnt triggered in my case.
I have an class QuickTextViewer with following:
public class QuickTextViewer {
private WebView webView;
...
...
public QuickTextViewer(){
webView = dialog.findViewById(R.id.mywebview);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
super.onPageFinished(view, url);
}
}
#JavascriptInterface
public void resize(final float height) {
System.out.print(height);
}
I also added the following to proguard-rules.pro (actually public only for testing)
-keepclassmembers class fqcn.of.javascript.interface.for.webview {
public *;
}
In my case onPageFinished is triggered but resize() not !
Any suggestions/help ?
Found the problem now.
Just had to add:
webView.getSettings().setJavaScriptEnabled(true);

Android WebView "Cannot read property 'getAttribute' of undefined"

I am trying to run a web page in a WebView. The page that I am loading has javascript in it, and it works on my desktop browser but doesn't work in the android emulator. In the emulator, I get this error:
09-13 18:29:18.496 32087-32087/com.gamesmart.gamesmart I/chromium: [INFO:CONSOLE(91)] "Uncaught TypeError: Cannot read property 'getAttribute' of undefined", source: http://dev.gamesmart.com/mobile (91)
The JavaScript that I am running on the page looks like this:
<script>
window.onload = function(){
var items = document.querySelectorAll('a.item');
for(var i = 0; i < items.length; i++){
var item = items[i];
item.addEventListener('click', function(event){
event.preventDefault();
window.JSInterface.playGame(items[i].getAttribute('href'));
});
}
}
</script>
Then The Java that I am running looks like this:
public class MainActivity extends AppCompatActivity {
private WebView webView;
private WebViewClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
// Setup the WebView
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.setWebChromeClient(new WebChromeClient());
webView.setInitialScale(1);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setDomStorageEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
// Load a default URL into the webview
webView.loadUrl("http://dev.gamesmart.com/mobile");
}
}
Am I missing something?
Try replacing this
window.JSInterface.playGame(items[i].getAttribute('href'));
with this
window.JSInterface.playGame(item.getAttribute('href'));

onPreExecute as preloader for webview in a fragment

I am trying to show a preloader before loading the complete page as webview but here is a small problem which I already made a preloader but it goes on and on and there is no end to it .
How can I tell the script to stop showing dialog when the page is loaded .
public class EzFragment extends Fragment {
public ProgressDialog pDialog;
public EzFragment(){}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new getFeed().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ez, container, false);
WebView myWebView = (WebView) rootView.findViewById(R.id.webView1);
String summary = "<html><head> <link rel=\"stylesheet\" type=\"text/css\"
href=\"http://www.example.com/demo/android_connect/assets/style/jquery.fullPage.css\" /></head></html>";
myWebView.loadData(summary, "text/html", null);
myWebView.loadUrl("http://www.example.com/demo/android_connect/get_ez_webmob.php");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
return rootView;
}
private class getFeed extends AsyncTask<Void, Void, Document> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Connect to Server");
pDialog.setMessage("This process can take a few seconds to a few minutes, depending on your Internet Connection Speed.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Document doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
}
Is it possible to add webview to Document doInBackground in order to load the page in background ?!
How can I tell the script to stop showing dialog when the page is
loaded .
Use onPageFinished to dismiss ProgressDialog because onPageFinished method is called when page is fully loaded in WebView :
myWebView.setWebViewClient(new WebViewClient(){
//.....
#Override
public void onPageFinished(WebView view, String url) {
Log.d("mytag","Page Loading Finished!");
super.onPageFinished(myWebView, url);
// dismiss ProgressDialog here
}
});
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
Stop the dialog in postexecute..

Android/WebView - Change Orientation

I have a webView in an Activity. Inside, the webView I have a button that opens a new HTML page. When this button is pressed and the new html page opens I would like the screen orientation to change to horizontal.
var searchButton = $('<button/>',
{
text:'Search!',
"class":"buttons",
id: "searchButtonID",
click: function(){
var select = document.getElementById("subCategory");
var option = select.options[select.selectedIndex];
var subCategoryId = option.id;
window.location.href = "deals.html?subCategoryId=" + subCategoryId;
Android.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
});
I recently learnt about WebAppInterfaces that allows Javascript to interact with Android. I tried adding the line:
Android.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
However, I get an error message saying:
Uncaught ReferenceError: ActivityInfo is not defined
I imported import android.content.pm.ActivityInfo; in the relevant class.
Not sure if what I'm doing is even possible...
Any help would be greatly appreciated!
private void rotate(float degree) {
final RotateAnimation rotateAnim = new RotateAnimation(0.0f, degree,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotateAnim.setDuration(0);
rotateAnim.setFillAfter(true);
oWebView.startAnimation(rotateAnim);
}
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
rotate(90);
}
});
try this
Do something like this
boolean rotationRequired = false;
private void openWebviewDialog(String days)
{
dialog = new Dialog(MainActivity.GLOBAL_CONTEXT);
dialog.setContentView(R.layout.simple_webview);
WebView wb = (WebView) dialog.findViewById(R.id.simple_webview);
WebSettings webSettings = wb.getSettings();
wb.setWebViewClient(new MyWebViewClient());
webSettings.setJavaScriptEnabled(true);
wb.addJavascriptInterface(this, "javaScriptInterface");
String url = "http://www.yourdomain.com" // your url here
String title = "Hello";
wb.loadUrl(url);
dialog.setCancelable(true);
dialog.setTitle(title);
dialog.show();
}
class MyWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if(url.contains("openExternal"))
{
return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
}
else
{
view.loadUrl(url); // Stay within this webview and load url
return true;
}
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
if(rotationRequired)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
}
}
#JavascriptInterface
public void passResult(String status)
{
rotationRequired = status.equalsIgnoreCase("true") ? true : false;
}
and don't forget to add this to your manifest:
android:configChanges = "orientation"
control the rotation as
<p>rotate...</p><script type='text/javascript' language='javascript'>javaScriptInterface.passResult('true');</script>
Please define and import packages
WebView myWebView;
WebAppInterface mWebAppInterface;
add this code to onCreate() of your activity
mWebAppInterface = new WebAppInterface(this);
myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(mWebAppInterface, "Android1");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//load your URL by myWebView.loadUrl("www.example.com");
Add this public function also
#JavascriptInterface
public void setorientation(){
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
Now you can call this public function for setting orientation from javascript button click function
Android1.setorientation();
visit also
http://developer.android.com/guide/webapps/webview.html
using javascript in android webview

Categories