Change element's visibility when javascript calls a function in a WebView - java

I'm building a simple android app based on a WebView of a website that I personally built, so I'm just making the mobile app for it that shows the mobile version of the website. The app has an adMob Ad at the top of the page that I want to hide in certain cases after the user logs in(for example because he has a different account type and ads can't be shown when he logs in). So I tried using addJavascriptInterface to my WebView and calling a function from javascript when the Ad needs to be hidden but I can't make it work. I'm new to android programming so it may be I'm just missing something fundamental but I couldn't find an answer anywhere on internet. Here's my code:
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.addJavascriptInterface(new WebAppInterface(this, mAdView), "Android");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
absoluteUrl = "myWebSiteUrl";
mWebView.loadUrl(absoluteUrl);
mWebView.setWebViewClient(new MyAppWebViewClient(this, mAdView));
}
}
WebAppInterface:
public class WebAppInterface {
Context mContext;
AdView mAdView;
/** Instantiate the interface and set the context */
WebAppInterface(Context c, AdView mAdView) {
this.mContext = c;
this.mAdView = mAdView;
}
/** Show a toast from the web page and hide the Ad */
#JavascriptInterface
public void hideAd(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
mAdView.setVisibility(View.GONE);
}
}
Javascript code in my page
//..Some variables here
var accountType = 1;
$(document).ready(function() {
if (accountType == 1) {
Android.hideAd('The Ad is now hidden');
}
//Other js functions
It works when in hideAd() I only show the toast, but when I add
mAdView.setVisibility(View.GONE);
The Ad at the top doesn't hide and all the javascript code in the page no longer works, please help me understand what I'm doing wrong.

Related

How to create a wrapper object for a webview

so I have a working webview that is simple, but most of the work is done in the main activity. I am trying to break it out to its own little class so I can load other classes into the main activity on the fly. I am stuck on how to do this. I have tried this a few times and been debugging it but I just dont know if I am using the right findByValue(R.id.webView); thing here. it keeps giving me a
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.webkit.WebView.findViewById(int)' on a null object reference
issue. I have tried passing the reference in as a parameter and also hard coded it. I am missing something but dont know what. There is a WebView in my activity_main that is called wevView that is what I am trying to find out where i'm did mistake.
Thanks for any help with this.
So this is my webview class:
public class NewWebView {
//variables need for webview
private final String myPage = "http://www.google.com";
WebView myWebView = null;
//consturctor
public NewWebView(){}
//This method creates the WebView
public void createWebView(WebView webView)
{
//WebView code
//Find the Webview in the Activity.xml file
//myWebView = webView;
myWebView = (WebView)myWebView.findViewById(R.id.webview);
// myWebView = (android.webkit.WebView)findViewById(R.id.webview);
//Use the custom WebViewClient for internal app browsing
myWebView.setWebViewClient(new MyWebViewClient());
//now for enabling the settings
WebSettings webSettings = myWebView.getSettings();
//Enable JavaScript
webSettings.setJavaScriptEnabled(true);
//Enable andriod zoom features
webSettings.setBuiltInZoomControls(true);
//Loading the Url
myWebView.loadUrl(myPage);
}
//Methods Used for WebViewer
//custom WebViewClent needed for internal app navigatiion
private class MyWebViewClient extends WebViewClient
{
public boolean shouldOverRideUrlLoading(android.webkit.WebView view, String url)
{
if(Uri.parse(url).getHost().equals(myPage))
{
//this is Apivita remain in the APP
return false;
}
/*
//if it is not in my site redirect it to mobile browers
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
*/
return true;
}
}
//Enable the use of the system back button for navigation
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//if the back button was pushed
if((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
{
myWebView.goBack();
return true;
}
//if not
return false;
}
}
and here is the main activity
public class MainActivity extends AppCompatActivity {
WebView myWebView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create the webview
myWebView = (android.webkit.WebView)findViewById(R.id.webview);
NewWebView apWebView = new NewWebView();
apWebView.createWebView(myWebView);
}
}
It looks like you are finding your webview in the main activity and then passing it into your class. In your custom class, you're then trying to find another view, which you technically already have. So its trying to find a webview, inside of the webview. It obviously can't find this, so it's null.
In theory, you should be able to just use myWebView = webView;, however, you need to make sure that it is finding it in the first place.

Android call JS from Native Code

I'm trying to call JS functions from Android native code, but they don't seem to be working. I've tried many solutions but to no solution. Here is my code:
public class MainActivity extends Activity {
private WebView webView;
#SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MyCustomWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.loadUrl("http://google.com");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:alert('shadow');");
Toast.makeText(getApplicationContext(), "DONE", Toast.LENGTH_LONG).show();
}
}
}
Please help.
Thanks
You can't do alert() with Android's WebView. If you want to show alert dialogs, you need to handle it in your Activity code or use a WebChromeClient. Per the docs:
Creating and setting a WebChromeClient subclass. This class is called
when something that might impact a browser UI happens, for instance,
progress updates and JavaScript alerts are sent here (see Debugging
Tasks).
See: https://developer.android.com/reference/android/webkit/WebView.html
With a WebView you can still write a JavaScript function that sets the value of a textbox to some string. If you need specific code to help you with this, let me know. If you've gotten this far though, you probably can handle it on your own is my guess.
Edit 1
First create a method in JavaScript called sendValueToAndroid()
myWebView.loadUrl("javascript:sendValueToAndroid()");
In the JavaScript method, call an exposed method in your Android code.
function sendValueToAndroid()
{
val divValue = ...
Android.sendValueToAndroid(divValue);
}
Expose a method in the Android app in any object of your choosing.
#JavascriptInterface
public String sendValueToAndroid(String val)
{
//do something in your app
}
Basically, what you're doing is telling the WebView to invoke a JavaScript method which invokes a callback method in your own app.

How to setup Android WebView to make it work identically Android browser?

What are the settings to enable or disable in WebView to do this?
If you want to use a webview with exactly the same features as the native android browser, you have to check MANY options and settings. A WebView is made to NOT use all of the browsers options and settings for better performance and for having more controll on what the users can and can not do while browsing. to figure out all the opportunities you should read through the api documentation here:
http://developer.android.com/reference/android/webkit/WebView.html
For some further dealing and handling with the WebView class also here are some usefull sample codelines:
http://pankajchunchun.wordpress.com/2013/01/09/example-of-webview-with-result-handler-and-connection-timeout-handler/
I hope this will help you.
this is the webview example source..
what kind of setting do you wanna know??
public class MainActivity extends Activity {
WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
webview.setWebViewClient(new WebClient());
WebSettings set = webview.getSettings();
set.setJavaScriptEnabled(true);
set.setBuiltInZoomControls(true);
webview.loadUrl("http://www.google.com");
findViewById(R.id.btnStart).setOnClickListener(onclick);
}
OnClickListener onclick =new OnClickListener() {
#Override
public void onClick(View v) {
String url= null;
EditText add = (EditText)findViewById(R.id.add);
url = add.getText().toString();
webview.loadUrl(url);
}
};
class WebClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
In addition to #Ssam's answer, you might want to manage the back button press so your app/Activity doesn't get closed on back press.
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
}else
super.onBackPressed();
}
where webview is your webview

ANDROID: Facebook and Browser Open inside my app, not in their own

this will be a bit annoying to explain, but bear with me:
So i have a simple android app with buttons, one opens a facebook page (first checks if the app is installed, and will open in that, else will open same page in browser), the other opens a website url in the browser
The problem i'm having is that, instead of opening them as seperate applications, it seems to be opening the browser/fb app inside my original app.
So if i open the fb page through my app, and click the back button, it brings me back to my app's home screen. If i click the fb button, and minimize the app, and go into the ACTUAL fb app, it hasn't changed anything there.
So my app is not actually using the standalone fb app, just calling it up inside itself.
(hope that makes sense...) here is the code i used;
//just defined button variables
button facebook, shop;
//now for the onCreate method
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
facebook = (Button) findViewById(R.id.facebook);
shop = (Button) findViewById(R.id.shop);
facebook.setOnClickListener(new View.onClickListener(){
public void onClick(View v) {
try{ //left out the profile id on purpose...
Intent facebook = new Intent(Intent.ACTON_VIEW, Uri.parse("fb://profile/xxxx"));
startActivity(facebook);
}catch(Exception e){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse ("http://www.facebook.com/example")));
}
}
});
The shop button is set up the same, only without the try/catch, it will only open in the browser.
How do i make it so that it sends the request to the actual fb app/browser, instead of what it's currently doing? Any help/tips are gratefully welcome :)
Create a new layout with layout/a.xml
Open the layout file & then add a WebView, assign an ID so you can access the widget later.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Insert Permission in your manifest file as you are accessing INTERNET in your application
<uses-permission android:name="android.permission.INTERNET" />
Inside the new Activity -->WebActivity.java
public class WebActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
WebView mywebview = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mywebview.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebview.loadUrl("http://www.facebook.com");
}
}
If you want to handle navigation inside the webView on your own
mywebview.setWebViewClient(new WebViewClient())
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
Now to redirect from your main activity to these new activity ::
facebook.setOnClickListener(new View.onClickListener(){
public void onClick(View v) {
try{
ApplicationInfo info = getPackageManager().getApplicationInfo("com.facebook.katana", 0 );
boolean isFacebookInstalled = true;
}
catch( PackageManager.NameNotFoundException e ){
isFacebookInstalled=false;
}
if(isFacebookInstalled)
{
//start the facebook app
Intent intent = new Intent("android.intent.category.LAUNCHER");
intent.setClassName("com.facebook.katana", "com.facebook.katana.LoginActivity");
startActivity(intent);
}
else
{
Intent facebook = new Intent(getApplicationContext(),WebActivity.class);
startActivity(facebook);
}
});
Same way you can also insert for your shop button

Loading PDF in webview using Google Docs gview

I am trying to use the Google Docs gview to load a pdf in my webview. It is loading the viewer but the pdf page itself is not shown. I have used this technique with other projects (other target url's) without any problem but I can not get the Google Docs Gview page to work with this. I use
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webView1);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new MyWebViewClient());
HttpHelper httphelper = new HttpHelper();
String pdf = "https://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
String result = httphelper.GetPage(Uri.parse("https://docs.google.com/gview?embedded=true&url=" + pdf));
webview.loadDataWithBaseURL("https://docs.google.com", result, "text/html", "utf-8", "https://docs.google.com");
}
Any idea why this is not working with the gview page?
Thanks
mWebview.getSettings().setJavaScriptEnabled(true);
String strPdf="https://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
mWebview.loadUrl("https://docs.google.com/gview?embedded=true&url=" + strPdf);

Categories