Android back button not working properly - java

When i push the back button on the phone it opens the pause activity as intended but it also goes to the previous activity(i can see this because pause activity style is Theme.AppCompat.Dialog. What i want is just open the pause activity but in the backround to be the current activity not the previous one.The code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_2);
//...
}
//...
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(timer_2.this, timer_2_pause.class));
finish();
}

In case you wish to kill previous activity use this:
#Override
public void onBackPressed()
{
startActivity(new Intent(timer_2.this, timer_2_pause.class));
finish();
}
If you want to keep that activity in back stack use this:
#Override
public void onBackPressed()
{
startActivity(new Intent(timer_2.this, timer_2_pause.class));
}

Try this:
#Override
public void onBackPressed() {
Intent i=new Intent(timer_2.this,timer_2_pause.class);
startActivity(i);
finish();
super.onBackPressed();
}

Its because you are calling finish() to close the current activity.
Remove finish() and it wont close the current activity.

You should use onBackPress() like this :
#Override
public void onBackPressed()
{
// super.onBackPressed();
// finish();
startActivity(new Intent(timer_2.this, timer_2_pause.class));
}

Use this just...
#Override
public void onBackPressed()
{
//super.onBackPressed(); dont use this..
finish();
startActivity(new Intent(timer_2.this, timer_2_pause.class));
}

Related

Update attachBaseContext in MainActivity.java from a fragment

How can I update attachBaseContext in MainActivity from a fragment? E.g.
MyFragment.java
String chosenLanguage = "en";
public void updateLanguage(String chosenLanguage) {
//...Update MyContextWrapper.wrap(newBase, chosenLanguage) here
}
MainActivity.java (Following succesfully calls a java class and changes app language)
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(MyContextWrapper.wrap(newBase,"en"));
}
You need to restart activity to run 'attachBaseContext' again.
In your fragment run:
Intent intent= new Intent(getContext(), MainActivity.class);
startActivity(intent);

Android Studio back button activity

I've been trying to find out the back navigation button to lead to another activity.
Every time when I pressed the back button, it goes to the previous activity which is not what I want. I would like to set the back button that goes to another activity I want, instead of previous one.
For example, I have Activity 1, 2 and 3. I was in Activity 2 and just moved to Activity 3. But when I press the back button, it goes automatically to the previous activity which is Activity 2. I want to make it to Activity 1 and not Activity 2. Can anyone suggest me a solution please?
You can make the button to go to a specific activity, instead of having the default behavior that you described.
It can be something like this:
#Override
public void onClick(View v) {
Intent intent = new Intent(Activity2.this, Activity3.class);
intent.putExtra("variable", information); //this is optional, but can be useful if you need to send a specific info to the next activity
startActivity(intent);
}
Activity 2 is parliamonar, and Activity 3 is federalparliamentary. I replaced parliamonar with Activity 1, but it still didn't solve the problem.
public class federalparliamentary extends AppCompatActivity {
Button federal;
private Object parliamonar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_federalparliamentary);
federal = findViewById(R.id.back160);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), parliamonar.class);
startActivity(reserve);
}
});
federal = findViewById(R.id.next164);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), sar.class);
startActivity(reserve);
}
});
}
public void onClick(View V) {
Intent back = new Intent((Context) parliamonar, federalparliamentary.class);
startActivity(back);
}
}
public class federalparliamentary extends AppCompatActivity {
Button federal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_federalparliamentary);
federal = findViewById(R.id.back160);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), parliamonar.class);
startActivity(reserve);
}
});
federal = findViewById(R.id.next164);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), sar.class);
startActivity(reserve);
}
});
}
public void Onclick(View v) {
Intent intent = new Intent(federalparliamentary.this, politicalsystem.class);
startActivity(intent);
}
}
Activity 1 is "politicalsystem".
I added with #Override method, but it says that I have to remove the method, so I added outside, then it says that I have to extract interface, so clicked on it, then it gave me a bunch of list. So I chose onClick(v:View ):void, but it still didn't solve the issue. I tried in another way without #Override, but nothing changed when I tested my app. I also tried inside onCreate method which did not modified the navigation as I desired.

Having issues exiting app on double press

So I've implemented a double press to exit on my mainactivity which exits fine if I go to settings activity or to game activity. However, if I go mainactivity --> gameactivity --> gameoveractivity and then press back it starts the mainactivity fine but then double pressing just returns to gameoveractivity and I'm not sure why as I call finish when starting mainactivity from gameoveractivity.
mainscreenactivity:
// button listeners
playButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent gameActivityIntent = new Intent(MainScreenActivity.this, GameActivity.class);
startActivity(gameActivityIntent);
overridePendingTransition(R.anim.righttocenter, R.anim.centertoleft);
finish();
}
});
settingsButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent settingsActivityIntent = new Intent(MainScreenActivity.this, SettingsActivity.class);
MainScreenActivity.this.startActivity(settingsActivityIntent);
overridePendingTransition(R.anim.righttocenter, R.anim.centertoleft);
}
});
gameactivity:
// handle hardware back button
#Override
public void onBackPressed() {
Intent mainScreenActivityIntent = new Intent(GameActivity.this, MainScreenActivity.class);
startActivity(mainScreenActivityIntent);
overridePendingTransition(R.anim.lefttocenter, R.anim.centertoright);
finish();
}
logic code to handle going to gameoveractivity:
if (weight.getBounds().intersect(player.getBounds())) {
timer.cancel();
gameTimer.cancel();
player.setTouched(false);
save(score, time);
Intent gameOverIntent = new Intent(this.getContext(), GameOverActivity.class);
this.getContext().startActivity(gameOverIntent);
((Activity) this.getContext()).finish();
}
gameoveractivity:
// handle hardware back button
#Override
public void onBackPressed() {
Intent mainScreenActivityIntent = new Intent(GameOverActivity.this, MainScreenActivity.class);
mainScreenActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
GameOverActivity.this.startActivity(mainScreenActivityIntent);
overridePendingTransition(R.anim.lefttocenter, R.anim.centertoright);
finish();
}
Edit: Managed to fix this by adding this: gameOverIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
in the game logic code after creating the gameoveractivityintent.
Managed to fix this by adding this:
gameOverIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
in the game logic code after creating the gameoveractivityintent.

Press back button to another activity

I try the code below to call another activity while pressing the back button:
#Override
public boolean onKeyUp(int keyCode, KeyEvent msg) {
switch(keyCode) {
case(KeyEvent.KEYCODE_BACK):
Intent intent = new Intent(AActivity.this, BActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window w = NASGroup.group.getLocalActivityManager().startActivity("BActivity", intent);
View view = w.getDecorView();
MyGroup.group.setContentView(view);
return true;
}
return false;
}
But when I press the back button, it get out of the app.
I see the logcat, it does not run the function onKeyUp and doesn't output any message.
The same code in onKeyUp, I try to below code to a button in layout and it works.
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AActivity.this, BActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window w = NASGroup.group.getLocalActivityManager().startActivity("BActivity", intent);
View view = w.getDecorView();
MyGroup.group.setContentView(view);
}
});
How can I modify it?
To handle back press you have to override Onbackpress method.
#Override
public void onBackPressed() {
finish();
Intent intent = new Intent(Myactivity.this, other.class);
startActivity(intent);
}
Try overriding the activity's onBackPressed() method
from the docs : onBackPressed
Try like this...
#Override
public void onBackPressed() {
Intent BackpressedIntent = new Intent();
BackpressedIntent .setClass(getApplicationContext(),TargetActivity.class);
BackpressedIntent .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(BackpressedIntent );
finish();
}
For back button you have to override the OnBackPressed() in your activity as
#Override
public void onBackPressed() {
Intent intent=new Intent(currentclass.this,nextActivity.class);
startActivity(intent);
finish();
}
if you didnt finish the previous activity then no need to use intent and startActivity just call finish(); in the onBackPressed it will finish the current activity and previous activity will started.
If you are within Activity you can use onBackPressed which is a built-in method to handle back key press.

New Preferences not loading when back button is pressed

I have this preferences class (below) that saves two ListPreferences, but if the ListPreferences are changed and the back button is pressed, the changes don't take affect unless the application is restarted. Did I miss something? Have been looking everywhere, but just can't seem to find an answer the fits or works. Please help.
public class Preferences extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
Application Code
public class Quotes extends Activity implements OnClickListener {
ProgressDialog dialog;
private WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String q = SP.getString("appViewType","http://www.google.com");
String c = SP.getString("appRefreshRate","20");
webview = (WebView) findViewById(R.id.scroll);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new QuotesWebView(this));
webview.loadUrl(q);
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
webview.reload();
}
}, 10, Long.parseLong(c),TimeUnit.SECONDS);
findViewById(R.id.refresh).setOnClickListener(this);
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onResume(){
super.onResume();
}
public void onClick(View v){
switch(v.getId()){
case R.id.refresh:
webview.reload();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem about = menu.getItem(0);
about.setIntent(new Intent(this, About.class));
MenuItem preferences = menu.getItem(1);
preferences.setIntent(new Intent(this, Preferences.class));
return true;
}
}
You need to somehow reload your preferences when the preferences activity finishes. I thought Dirol's suggestion of loading them in onResume() instead of onCreate() was excellent; have you tried it? Or am I misunderstanding the problem as well.
In my own case, I launched the preferences activity with startActivityForResult() and then on the activity result callback, I reloaded the preferences.
Code snippets:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Intent intent = new Intent().setClass(this, CalcPreferences.class);
startActivityForResult(intent, MENU_PREFERENCES);
break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onActivityResult(int req, int result, Intent data) {
switch( req ) {
case MENU_PREFERENCES:
SharedPreferences sp =
PreferenceManager.getDefaultSharedPreferences(this);
updatePreferences(sp);
break;
default:
super.onActivityResult(req, result, data);
break;
}
}
#Override
protected void updatePreferences(SharedPreferences sp) {
super.updatePreferences(sp);
keyclick = sp.getBoolean("keyclick", keyclick);
}
Anyway, this is what works for me. I may try moving my updatePreferences() call to onResume() myself to see if that works too.
Try overriding the onBackPressed() method.
If your "Up" button (top left <-) provides the correct result, then you can set the Back button to behave like the Up button.
#Override
public void onBackPressed() {
super.onBackPressed();
NavUtils.navigateUpFromSameTask(this);
}
You load preferences only on onCreate() method. That method called only when a fresh activity starts up. The addPreferencesFromResource inflates the xml file into the preferences, so you only get the info, which is already has been stored in the xml at the moment addPreferencesFromResource was called, not after.
Try to move that method to onResume. But watch for the memory leak. I don't know exactly what the addPreferencesFromResource do, but from the documentation - I would be very suspicious about that method activity.
I had the same problem and solved it as follows:
The main activity class implements OnSharedPreferenceChangeListener:
public class Activity_name extends Activity implements OnSharedPreferenceChangeListener {
...
}
Inside the main activity class the onSharedPreferenceChanged is run whenever a preference entry changes. I simply update all my variables from the preferences as i did in onCreate:
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
<read all preferences as you did in onCreate()>
}
This does the trick and I hope it saves you some time in searching for a solution.
I've had the same problem...
Try to create preference instance and load its data in every class and every activity where you need it.
It worked for me...Hope it helps.
You will need to reload your view or whatever object which uses those preferences, preferably when preference activity closes.
Preference activities do not change nothing but an internal file with your preferences(key=value list). When it is changed, preferenceActivity calls onPreferenceChaged() and nothing more. It doesn't refresh your stuff by itself. You need to reload prefs and to reuse them in onResume() method or equivalent.

Categories