Android Back button on webview kills app - android

*Solved
I just had to publicly declare my webview variable for my back button class to work correctly. Thanks for the help
I've got a unique setup with the webview class and everything I've googled I've gotten nowhere.
I'm using buttons to launch webview's and I'm getting the issue that when I press the back button to return to my main app screen it will just kill the app. I have added some code in at the bottom to try and fix my issue but it has not worked.
btw the below code has been updated to what is currently working for me.
package my.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;
public class MobileAppActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
WebView wb;
public void onMyButtonClick01(View view)
{
Toast.makeText(this, "Pay your dues here!", Toast.LENGTH_SHORT).show();
wb = new WebView(this);
wb.loadUrl("http://www.link1.html");
setContentView(wb);
}
public void onMyButtonClick02(View view)
{
Toast.makeText(this, "Re-Sign here!", Toast.LENGTH_SHORT).show();
wb = new WebView(this);
wb.loadUrl("http://www.link2.html");
setContentView(wb);
}
public void onBackPressed () {
if(wb != null) {
if(wb.canGoBack()) {
wb.goBack();
} else {
setContentView(R.layout.main);
wb = null;
}
} else {
super.onBackPressed();
}
}
}

I assume you're saving off wb elsewhere? Not sure how you're accessing that from onBackPressed(). Let's say you do have a way to fetch it.
public void onBackPressed () {
if(wb != null) {
if(wb.canGoBack()) {
wb.goBack();
} else {
setContentView(R.layout.main);
wb = null;
}
} else {
super.onBackPressed();
}
}

Related

Why does the back button close apps instead actions back in Webview?(react native)

i add this code im my MainActivity.java but nothing happens.
I use android emulator
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
it`s my MainActivity.java
package com.mobile;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import expo.modules.splashscreen.singletons.SplashScreen;
import expo.modules.splashscreen.SplashScreenImageResizeMode;
public class MainActivity extends ReactActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
// SplashScreen.show(...) has to be called after super.onCreate(...)
// Below line is handled by '#expo/configure-splash-screen' command and it's discouraged to modify it manually
SplashScreen.show(this, SplashScreenImageResizeMode.CONTAIN, ReactRootView.class, false);
}
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
#Override
protected String getMainComponentName() {
return "main";
}
#Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
#Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
I think you could fix it using fragments.
You have to create a fragment(exampleFragment.kt & fragment_example.xml) with the view and associate it to the activity.
And them, in your activity add de manager:
supportFragmentManager .beginTransaction() .replace(R.id.---Fragment, ---Fragment()) .addToBackStack(null) .commit()
"addToBackStack(null)" is what makes the window go back
The official page explains the fragments.
https://developer.android.com/guide/components/fragments?hl

Webview hide CSS elements

I've been trying to alter my Webview app to not show the header of the source url that it loads. I've gone trough all the methods provided in Stack Overflow's history and havent't got any of them working - so i'm doing something right, or those aren't working anymore?
My goal is to find a way to affect the CSS of the page loaded to the webview app (hide the header and footer for example). Most of the methods provided here earlier based on Javascript, which is not familiar with me. I'm open for any help, since it is my first project that i'm building, and my knowledge at this point is not too good.
Here's my MainActivity.java at the moment:
package com.U247;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView WebView;
/* dawdaw */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = (WebView)findViewById(R.id.U247);
WebView.getSettings().setJavaScriptEnabled(true);
WebView.setWebViewClient(new WebViewClient());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
WebView.evaluateJavascript("var FunctionOne = function () {"
+ " try{document.getElementsByClassName('random-postaus')[0].style.display='none';}catch(e){}"
+ "};", null);
} else {
WebView.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('random-postaus')[0].style.display='none';}catch(e){}"
+ "};");
}
WebView.loadUrl("https://thewebsite.com");
}
#Override
public void onBackPressed() {
if (WebView.canGoBack()){
WebView.goBack();
} else {
super.onBackPressed();
}
}
}
Okay finally found a way to hide the CSS elements. Added the whole code below and the key was to use the onPageFinished method. While it is not perfect, and only activates after the whole page is loaded, it's still a valid method to hide elements in my case.
package com.U247;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView WebView;
/* dawdaw */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = (WebView)findViewById(R.id.U247);
WebView.getSettings().setJavaScriptEnabled(true);
/* HIDE UNWANTED CSS ELEMENTS */
WebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
// hide element by class name
WebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('class-name-here')[0].style.display='none'; })()");
// hide element by id
WebView.loadUrl("javascript:(function() { " +
"document.getElementById('header').style.display='none';})()");
}
});
WebView.loadUrl("https://thewebsite.com");
}
#Override
public void onBackPressed() {
if (WebView.canGoBack()){
WebView.goBack();
} else {
super.onBackPressed();
}
}
}

Android NFC foreground dispath error to two instance of same activity

I had made the application which was using NFC to read card in Android. The application get NFC tag data by using NfcAdapter.enableForegroundDispatch() method in ReadActivity, and it work well except one case.
here is the flow of case:
start the ReadActivity(firstly instance)
back to home
launch a third App who calls ReadActivity by intent ;
read card by the secondly ReadActivity
something strange happend !! the firstly ReadActivity instance was
brought to front and got the nfc data !
here is the partly code:
I: ReadActivity
package com.song.nfctest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcB;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;
import java.io.IOException;
public class ReadActivity extends Activity {
private NfcAdapter mAdapter;
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textView = new TextView(this);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
setContentView(textView);
mAdapter = NfcAdapter.getDefaultAdapter(this);
resolveIntent(getIntent());
if (getCallingActivity() == null){
textView.append("\ncalled by self");
}else {
textView.append("\ncalled by other app");
}
textView.append("\n\n\n\n\n\ntap your nfc tag to phone to continue ");
}
void resolveIntent(Intent intent) {
printLog("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
Parcelable p = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (p == null) {
return;
}
Tag nfcTag = (Tag) p;
final NfcB nfcb = NfcB.get(nfcTag);
try {
nfcb.connect();
printLog("----------- complete with read logic----- ");
textView.append("\n\n\n\n\n\n get nfc event !!!");
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
nfcb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onResume() {
super.onResume();
if (mAdapter == null) return;
mAdapter.enableForegroundDispatch(this,
PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0),
new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)},
new String[][]{new String[]{NfcB.class.getName()}});
}
#Override
public void onNewIntent(Intent intent) {
resolveIntent(intent);
}
#Override
public void onPause() {
super.onPause();
if (mAdapter == null) return;
mAdapter.disableForegroundDispatch(this);
}
void printLog(String message) {
Log.e("krik", message);
}
}
II: clientActivity:
public class TestActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
Button button = new Button(this);
button.setText("call main app");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callApp();
}
});
linearLayout.addView(button);
setContentView(linearLayout);
}
private void callApp() {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.song.nfctest", "com.song.nfctest.ReadActivity"));
startActivityForResult(intent, 1001);
}
}
PS1: I had guessed it caused by requestCode of pendingIntent, I had changed it but it not worked finally.
PS2: I got a very simple demo and upload to github: https://github.com/songsyl1207/nfctest.git .run app module and otherapp module to the android device, then operate as the question flow ,you will see it.
hope somebody can help me !

Android studio, what is wrong with this onBackPressed() code?

I used below code to close app after back button pressed. Some time ago it worked but I tried to use it again and have:
Error:(88, 13) error: class, interface, or enum expected.
If I remove this code app can be build, I don't see where is problem?
Here is the MainActivity where onBackPressed is implemented:
package com.example.chab.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.os.Handler;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image = (ImageView) findViewById(R.id.a);
ImageView image1 = (ImageView) findViewById(R.id.b);
ImageView image2 = (ImageView) findViewById(R.id.c);
ImageView image3 = (ImageView) findViewById(R.id.d);
ImageView image4 = (ImageView) findViewById(R.id.e);
ImageView image5 = (ImageView) findViewById(R.id.f);
ImageView image6 = (ImageView) findViewById(R.id.g);
Picasso.with(this).load("http:/1.jpeg").into(image);
Picasso.with(this).load("http://1.jpeg").into(image1);
Picasso.with(this).load("http://1.jpeg").into(image2);
Picasso.with(this).load("http://1.jpeg").into(image3);
Picasso.with(this).load("http://1.jpeg").into(image4);
Picasso.with(this).load("http://1.jpeg").into(image5);
Picasso.with(this).load("http://1.jpeg").into(image6);
Button btnOne = (Button) findViewById(R.id.Btn);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), Activitydwa.class);
startActivity(intent);
}
});
}
} //THIS BRACKET MUST BE MOVED TO THE END OF CODE!
private Boolean exit = false;
#Override
private void super.onBackPressed() {
if (exit) {
this.finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
EDIT:
Solved.
Bracket before Boollean must be moved to the end of code. Then all works. Thank you.
Your first problem is that you have your method implemented outside of the class. In java, methods need to belong to a class, interface, or enum. Double check your brackets and move your method to the inside of your class brackets. Your second problem is that you have the wrong signature for the onBackPressed method. See the code below:
This is what you have:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
}
}
private Boolean exit = false;
#Override
private void super.onBackPressed() {
// ...
}
This is what you need:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
}
private Boolean exit = false;
#Override
public void onBackPressed() {
// ...
}
}
Try to put
super.onBackPressed()
before finish()
Try this.finish() OR
Try super.onBackPressed(); OR
call NavUtils.navigateUpFromSameTask(this); to get back to previous screen/ activity

OnPause not executing code in cordova/phonegap :(((

Its a week yet and I still get problems integrating the cordova into ana ndroid webview!
Before the onPause and onResume were working fine but after integration they dont trigger anymore.
Even though I see this in my console:
07-15 17:01:21.880: D/CordovaActivity(5635): Paused the application!
07-15 17:01:21.880: D/CORDOVA_ACTIVITY(5635): onPause
but the code inside the opPause function isn't executing!! I'm really tired of this.. I tried a week non stop to get it working.
This is my main java file:
package com.Snap.What;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import org.apache.cordova.*;
public class WhatSnap extends CordovaActivity implements CordovaInterface
{
private CordovaWebView cordova_webview;
private String TAG = "CORDOVA_ACTIVITY";
private final ExecutorService threadPool = Executors.newCachedThreadPool();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.cordova_layout);
cordova_webview = (CordovaWebView) findViewById(R.id.cordova_web_view);
// Config.init(this);
cordova_webview.loadUrl("file:///android_asset/www/index.html");
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
cordova_webview.getSettings().setJavaScriptEnabled(true);
cordova_webview.addJavascriptInterface(jsInterface, "JSInterface");
}
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
#JavascriptInterface
public void showLog(){
Log.v("blah", "blah blah");
}
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
#Override
public void onDestroy() {
super.onDestroy();
if (this.cordova_webview != null) {
this.cordova_webview
.loadUrl("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};");
this.cordova_webview.loadUrl("about:blank");
cordova_webview.handleDestroy();
}
}
#Override
public Activity getActivity() {
return this;
}
#Override
public ExecutorService getThreadPool() {
return threadPool;
}
#Override
public Object onMessage(String message, Object obj) {
Log.d(TAG, message);
if (message.equalsIgnoreCase("exit")) {
super.finish();
}
return null;
}
//
//
// #Override
// public void setActivityResultCallback(CordovaPlugin cordovaPlugin) {
// Log.d(TAG, "setActivityResultCallback is unimplemented");
// }
// #Override
// public void startActivityForResult(CordovaPlugin cordovaPlugin,
// Intent intent, int resultCode) {
// Log.d(TAG, "startActivityForResult is unimplemented");
// }
}
I tried also to comment the onPause and onresume from java but than I only get this in console:
07-15 17:01:21.880: D/CordovaActivity(5635): Paused the application!
In my js I have these lines:
document.addEventListener("resume", onResume, false);
document.addEventListener("pause", punish, false);
and the coresponding functions wich WONT EXECUTE!
I really don't know why they're not executing.. Please take a look and you you have any idea pls tell me.
Its an old post, still if some one is following
Change
document.addEventListener("pause", punish, false);
to
document.addEventListener("pause", onPause, false);

Categories

Resources