//solution is:
import android.webkit.WebView;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
//in my case I call it the JS function when I press the back button
#Override
public void onBackPressed() {
WebView webView = getBridge().getWebView();
webView.loadUrl("javascript:pressBack()");
// in Index.html create tag
// <script type="text/javascript">
//function pressBack(){
// alert('yes!!')
//} </script>
return;
}
}
// it works fine 100%
Related
I'm trying to change images when an image button is clicked. Even without the code for changing image my application is crashing whenever I use an onClickListener or try to set an onClick listener. How do i fix this I'm running app on kitkat api 19
package com.example.t11;
import android.R.string;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Scene extends ActionBarActivity {
ImageView scene=(ImageView) findViewById(R.id.images);
int i=0;
int[] imgarray = {R.drawable.i1,R.drawable.i2,R.drawable.i4,R.drawable.i6,R.drawable.i7,R.drawable.i8,R.drawable.i9,R.drawable.i10,R.drawable.i12};
//Just set one Click listener for the image
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scene);
Intent sceneint = getIntent();
ImageButton left = (ImageButton) findViewById(R.id.left);
ImageButton right= (ImageButton) findViewById(R.id.right);
// Left and right button listener creation
left.setOnClickListener(leftlistener);
right.setOnClickListener(rightlistener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.scene, menu);
return true;
}
View.OnClickListener rightlistener = new OnClickListener() {
public void onClick(View v1) {
//Increase Counter to move to next Image
i++;
scene.setImageResource(imgarray[i]);
}
};
View.OnClickListener leftlistener = new OnClickListener() {
public void onClick(View v) {
//Increase Counter to move to Previous Image
i--;
scene.setImageResource(imgarray[i]);
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Instantiate the listener as an anonymous function :
left.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Increase Counter to move to Previous Image
i--;
scene.setImageResource(imgarray[i]);
}
});
if you want the reference of the listener as well for some reason then try instantiating and assigning the listener before registering it with the button.
My Android application is mainly a Webview (labeles WebViewActivity) that navigates a mobile website. I have a connection detector that opens another activity on every URL load if there is no wireless connection. From this next activity there is a button that opens up the Wireless Settings. Upon pressing the back button I would like for the second activity (labeled MainActivity) to refresh itself and continue back to whichever page my Webview had loaded. What do I need to change in the MainActivity.java to execute that?
My MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
}
#Override
protected void onRestart(){
if(checkConnection()){
Intent intent= new Intent(this, WebViewActivity.class);
startActivity(intent);
}
}
#Override
// Detect when the back button is pressed
public void onBackPressed() {
super.onBackPressed();
}
public void openSettings(View view){
Intent intent= new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
public boolean checkConnection(){
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
//Get Internet Status
isInternetPresent = cd.isConnectingToInternet();
if(!isInternetPresent)
return false;
return true;
}
}
My WebviewActivity:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends Activity {
private WebView mWebView;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TODO Auto-generated method stub
if (checkConnection()) {
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
mWebView.loadUrl("http://my.fellowshipnwa.org/?publicapp");
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new myWebClient());
} else {
openSplash();
}
}
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
// Let the system handle the back button
new AlertDialog.Builder(this)
.setTitle("Exit myFellowship App?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
WebViewActivity.super.onBackPressed();
}
}).create().show();
}
}
public class myWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(!checkConnection()){
openSplash();
return true;
}else{
if( url.startsWith("tel:")){
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
else if( url.startsWith("mailto:")){
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
startActivity(intent);
return true;
}
}
return false;
}
}
public void openSplash(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public boolean checkConnection(){
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
//Get Internet Status
isInternetPresent = cd.isConnectingToInternet();
if(!isInternetPresent)
return false;
return true;
}
}
Any help is Greatly Appreciated! Even if it means telling me I goofed up on creating this question.
Thank you friends.
I played with it for a while and used a few other examples to piece together something that is working. One small hitch is if the user turns on a connection, but it is not quite connected when they return to the app it will stay on the ConnectorActivity. So I intercept the back button to check for a connection. If present, it will finish the current activity. Then, upon returning to the webview it will reload.
ConnectorActivity.java:
#Override
protected void onRestart(){
super.onRestart();
if(checkConnection()){
finish();
}
}
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(checkConnection()){
super.onBackPressed();
}
}
Piece from WebViewActivity.java:
#Override
protected void onRestart(){
super.onRestart();
mWebView.reload();
}
I want to partially view a webpage on webview android and remove some div element from the webpage. I have a webpage like this
<!DOCTYPE html>
<body>
<div id="a"><p>Remove aa</p></div>
<div id="b"><p>bb</p></div>
</body></html>
Now I want to remove the div with id 'a' from the webpage.
I tried to code it with Jsoup but I am not well enough to make it out. Please see my full code:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class CustomWebsite extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_website);
Document doc;
String htmlcode = "";
try {
doc = Jsoup.connect("http://skyasim.info/ab.html").get();
doc.head().getElementsByTag("DIV#a").remove();
htmlcode = doc.html();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webView = (WebView) findViewById(R.id.webView_test);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("htmlcode");
}
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) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
}
You can do this without using Jsoup you know. Just use plain old javascript. The following code will show how to remove an element from the HTML page and display the rest.
final WebView mWebView = (WebView) findViewById(R.id.mWebViewId);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"document.getElementById('a')[0].style.display='none'; " +
"})()");
}
});
mWebView.loadUrl(youUrl);
Remove it from the document by selecting it and then using the remove-method.
doc.select("div#a").remove();
System.out.println(doc);
Example:
Document doc = Jsoup.parse(html);
System.out.println("Before removal of 'div id=\"a\"' = ");
System.out.println("-------------------------");
System.out.println(doc);
doc.select("div#a").remove();
System.out.println("\n\nAfter removal of 'div id=\"a\"' = ");
System.out.println("-------------------------");
System.out.println(doc);
will result in
Before removal of 'div id="a"' =
-------------------------
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="a">
<p>Remove aa</p>
</div>
<div id="b">
<p>bb</p>
</div>
</body>
</html>
After removal of 'div id="a"' =
-------------------------
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="b">
<p>bb</p>
</div>
</body>
</html>
I had tried to use Jsoup to do something similar before, but my app always crash. If you are open to using Javascript only (which helps to make your app size smaller), here is what I did for my app:
webview3.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:var con = document.getElementById('a'); " +
"con.style.display = 'none'; ");
}
});
Hope my Javascript is correct. The idea here is to use Javascript to hide the div after the page has finished loading.
With the following code, I add trackingpixel to some page page.html by overriding the method renderHead(Component component, IHeaderResponse response). This works fine.
page.html looks like this:
<!doctype html>
<html xmlns:wicket="http://wicket.apache.org/">
<head>
..
<wicket:container wicket:id="header"></wicket:container>
</head>
<body>
..
<script wicket:id="scriptHolder" type="text/javascript" > I would like to add my script here
</script>
..
</body>
</html>
TrackingPixel.java:
public abstract class TrackingPixel extends AbstractDefaultAjaxBehavior {
protected TrackingPixel(TrackingPixelType type) {
..
}
#Override
public void renderHead(Component component, IHeaderResponse response) {
response.renderOnDomReadyJavaScript("WebtrekkInstance = {
..
'path' : 'anyPath',
...:...
..
};
");
}
}
renderHead-method adds a trackingpixel to the main page. Right mouse click on the page -> source code shows that the following script is added to the page:
<script type="text/javascript" >
Wicket.Event.add(window, "domready", function(event) {
WebtrekkInstance = {
..
'path' : 'anyPath',
...:...
..
};
..
;});
</script>
Now I would like to add trackingpixel to a popup. My problem is that I can't add a script to the body. The method renderHead(Component component, IHeaderResponse response) doesn't do that, because (I guess) the popup pops up on the same page, so there is only one head and it will not render twice. So I tried to do this with WebMarkupContainer as you can see below.
OurServicePopup.java
/**
* Class to display our service as popup
*/
public class OurServicePopupPage<T> extends WebPage {
public OurServicePopupPage(PageParameters parameters) {
super(parameters);
}
#Override
protected void onInitialize() {
add(new OurServicePixel());
super.onInitialize();
}
}
OurServicePixel.java looks like this:
public class OurServicePopupPixel extends TrackingPixel{
public OurServicePopupPixel() {
}
WebMarkupContainer scriptContainer = new WebMarkupContainer("scriptContainer");
#Override
public void renderHead(Component component, IHeaderResponse response) {
scriptContainer.add(new AttributeAppender("type", Model.of("text/javascript")));
scriptContainer.add(
new AttributeAppender("src","WebtrekkInstance = {
..
'path' : 'anyPath',
...:...
..
};
");
}
add(scriptContainer); //this shows error
}
The problem here is that I cannot add the scriptContainer. add(scriptContainer); will not work, because OurServicePopupPixel is a behaviour and not a page.
Maybe you can simple use a Label component with setEscapeModelStrings(false). But it seems a bit strange.
I didn't full understand what is your javascript doing, but maybe you can try to execute it when the DOM is ready. Using a renderHead like this:
public void renderHead(IHeaderResponse response) {
response.render(OnDomReadyHeaderItem.forScript( ... YOUR SCRIPT HERE ... ));
}
I hope it helps.
I am exporting a GWT method to native javascript in the following manner:
public class FaceBookGalleryEntryPoint implements EntryPoint {
#Override
public void onModuleLoad() {
FacebookGallery facebookGallery = new FacebookGallery();
RootPanel.get().add(facebookGallery);
initLoadGallery(facebookGallery);
}
private native void initLoadGallery(FacebookGallery pl) /*-{
$wnd.loadGallery = function (galleryId) {
pl.#com.example.fbg.client.FacebookGallery::loadGallery(Ljava/lang/String;)(galleryId);
};
}-*/;
}
In the host page, I am trying to invoke it:
<html>
<head>
<title>Facebook image gallery</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" src="/fbg/fbg.nocache.js"></script>
<h1>Facebook gallery test</h1>
<script type="text/javascript">
$(document).ready(function() {
loadGallery('blargh');
});
</script>
</body>
</html>
Unfortunately, when the document.ready callback is invoked, the function is not yet defined. When manually executed from the Firebug console the function works just fine.
I could perform some polling every 50 milliseconds until I find a defined function by that name, but it seems like a horrible approach.
How can I get notified when the module is loaded and therefore when the function is available?
I would try to define a callback function in the hostpage and call it from GWT at the end of the onModuleLoad() method.
Hostpage function:
<script type="text/javascript">
function onGwtReady() {
loadGallery('blargh');
};
</script>
GWT:
public void onModuleLoad() {
FacebookGallery facebookGallery = new FacebookGallery();
RootPanel.get().add(facebookGallery);
initLoadGallery(facebookGallery);
// Using a deferred command ensures that notifyHostpage() is called after
// GWT initialisation is finished.
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
notifyHostpage();
}
}
}
private native void notifyHostpage() /*-{
$wnd.onGwtReady();
}-*/;