When I'm leaving my app, my counter gets reset.
I know that I need to use the onPause and onResume functions. However, I don't know how to write it in the code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button b1 = findViewById(R.id.b1);
eggcounter = 100;
final ImageButton ImgButton = findViewById(R.id.eggBtn);
ImgButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
eggcounter = eggcounter - 1;
updateEgg();
if (eggcounter < 80) {
ImgButton.setImageResource(R.drawable.egg_2);
if (eggcounter <60){
ImgButton.setImageResource(R.drawable.egg_3);
if (eggcounter <40) {
ImgButton.setImageResource(R.drawable.egg_4);
If you want to save your application state, you can use Shared Preferences. Example :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// You can call to onResume() or on Pause() in onCreate();
onResume();
onPause();
}
#Override
public void onResume() {
super.onResume();
// After receiving this call you will usually receive a following call
// to onStop() and return to your activity 's onResume()
}
#Override
public void onPause() {
super.onPause();
// When you receive a call, your activity is going into the background
// (to onPause) but your activity can be killed to reclaim resources
// (if there are not enough resources to start the new activity)
}
so if you want to save your instance application state, you can save to Shared Preferences, SQLite and so on. Call it in onPause() or onStop() and reclaim this data in onResume()
Related
I have a CountDownTimer in one activity that I need to cancel in a different activity. The problem I'm having is that the CountDownTimer is not getting cancelled even when I make a call to the endTestTimer() method in another activity. Here is the code for the CountDownTimer:
private long testMillisLeft, questionMillisLeft;
private static CountDownTimer testTimer;
private void startTestTimer()
{
long startTime = DataHolder.getTestTime()*1000; //getTestTime() is the seconds
testTimer = new CountDownTimer(startTime, 1000) {
#Override
public void onTick(long millisUntilFinished) {
testMillisLeft = millisUntilFinished;
updateTestTimeLeft();
}
#Override
public void onFinish() {
Intent intent = new Intent(MainActivity4.this, MainActivity5.class);
startActivity(intent);
}
}.start();
}
public static void endTestTimer()
{
if(testTimer != null)
{
testTimer.cancel();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
testTimeLeft = (TextView) findViewById(R.id.testTimerTextView);
mathProblem = (TextView) findViewById(R.id.mathProblemTextView);
testTimer = null;
startTestTimer();
}
And here is how I am trying to cancel the same timer in another activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity4.endTestTimer();
}
A comment on this related post says that the static CountDownTimer creates memory leak. If that's the case, how can I call the endTestTimer() method in another activity and have it cancel the timer? Alternatively, how can I access the testTimer CountDownTimer directly and call .cancel() on it in another activity if it can't be static?
Looking into Android lifecycles led me to this post and this post, both of which I found very helpful. To my understanding, when the user hits the back button, the onDestroy() method is called for the currently-displayed activity, and then the onCreate() method is called for the activity to be displayed. So, to cancel the timers on MainActivity4 (the current activity in my case), I added this code to its class file:
#Override
protected void onDestroy() {
testTimer.cancel();
questionTimer.cancel();
super.onDestroy();
}
Now, when the user backs out of MainActivity4 (regardless of what other activity that takes them to) and onDestroy() is called automatically, both timers are cancelled and then MainActivity4 is destroyed. This seems to work fine for me, but I'm not sure if there are any downsides to doing it this way, so please let me know if there are.
enter image description hereGood day, I want to save the value of the toggle buttons when the app exits and put them back when the user starts the app again. I've tried using onSaveInstanceState but it just doesn't work. Any help would be appreciated. Thank you.
edit: I also tried using preferences.
edit: I also tried using preferences.
edit: I also tried using preferences.
edit: I also tried using preferences.
edit: I also tried using preferences.
edit: I also tried using preferences.
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("white", white.isChecked());
savedInstanceState.putBoolean("yellow", yellow.isChecked());
savedInstanceState.putBoolean("orange", orange.isChecked());
savedInstanceState.putBoolean("red", red.isChecked());
savedInstanceState.putBoolean("blue", blue.isChecked());
savedInstanceState.putInt("whiteI", whiteI.getVisibility());
savedInstanceState.putInt("yellowI", yellowI.getVisibility());
savedInstanceState.putInt("orangeI", orangeI.getVisibility());
savedInstanceState.putInt("redI", redI.getVisibility());
savedInstanceState.putInt("blueI", blueI.getVisibility());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
white.setChecked(savedInstanceState.getBoolean("white"));
yellow.setChecked(savedInstanceState.getBoolean("yellow"));
orange.setChecked(savedInstanceState.getBoolean("orange"));
red.setChecked(savedInstanceState.getBoolean("red"));
blue.setChecked(savedInstanceState.getBoolean("blue"));
whiteI.setVisibility(savedInstanceState.getInt("whiteI"));
yellowI.setVisibility(savedInstanceState.getInt("yellowI"));
orangeI.setVisibility(savedInstanceState.getInt("orangeI"));
redI.setVisibility(savedInstanceState.getInt("redI"));
blueI.setVisibility(savedInstanceState.getInt("blueI"));
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor editPreferences = preferences.edit();
editPreferences.putBoolean("white", white.isChecked());
editPreferences.putBoolean("yellow", yellow.isChecked());
editPreferences.putBoolean("orange", orange.isChecked());
editPreferences.putBoolean("red", red.isChecked());
editPreferences.putBoolean("blue", blue.isChecked());
editPreferences.putInt("whiteI", whiteI.getVisibility());
editPreferences.putInt("yellowI", yellowI.getVisibility());
editPreferences.putInt("orangeI", orangeI.getVisibility());
editPreferences.putInt("redI", redI.getVisibility());
editPreferences.putInt("blueI", blueI.getVisibility());
editPreferences.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main);
background = findViewById(R.id.imageViewBg);
yellow = findViewById(R.id.tgBtnAlarm);
orange = findViewById(R.id.tgBtnAlert);
red = findViewById(R.id.tgBtnCritical);
blue = findViewById(R.id.tgBtnRecession);
white = findViewById(R.id.tgBtnNormal);
yellowI = findViewById(R.id.imageViewYellow);
redI = findViewById(R.id.imageViewRed);
blueI = findViewById(R.id.imageViewBlue);
orangeI = findViewById(R.id.imageViewOrange);
whiteI = findViewById(R.id.imageViewWhite);
btnExit = findViewById(R.id.btnExit);
preferences = getSharedPreferences("pref",MODE_PRIVATE);
white.setChecked(preferences.getBoolean("white"));
yellow.setChecked(preferences.getBoolean("yellow"));
orange.setChecked(preferences.getBoolean("orange"));
red.setChecked(preferences.getBoolean("red"));
blue.setChecked(preferences.getBoolean("blue"));
whiteI.setVisibility(preferences.getInt("whiteI"));
yellowI.setVisibility(preferences.getInt("yellowI"));
orangeI.setVisibility(preferences.getInt("orangeI"));
redI.setVisibility(preferences.getInt("redI"));
blueI.setVisibility(preferences.getInt("blueI"));
glide();
allow();
volume();
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
Try using SharedPreferences
SharedPreferences savePreferences = getSharedPreferences("pref",MODE_PRIVATE);
SharedPreferences.Editor editPreferences = savePreferences.edit();
editPreferences.putBoolean("white", white.isChecked());
editPreferences.putBoolean("yellow", yellow.isChecked());
editPreferences.putBoolean("orange", orange.isChecked());
editPreferences.putBoolean("red", red.isChecked());
editPreferences.putBoolean("blue", blue.isChecked());
editPreferences.putInt("whiteI", whiteI.getVisibility());
editPreferences.putInt("yellowI", yellowI.getVisibility());
editPreferences.putInt("orangeI", orangeI.getVisibility());
editPreferences.putInt("redI", redI.getVisibility());
editPreferences.putInt("blueI", blueI.getVisibility());
editPreferences.commit();
To retrive data
white.setChecked(savePreferences.getBoolean("white"));
yellow.setChecked(savePreferences.getBoolean("yellow"));
orange.setChecked(savePreferences.getBoolean("orange"));
red.setChecked(savePreferences.getBoolean("red"));
blue.setChecked(savePreferences.getBoolean("blue"));
whiteI.setVisibility(savePreferences.getInt("whiteI"));
yellowI.setVisibility(savePreferences.getInt("yellowI"));
orangeI.setVisibility(savePreferences.getInt("orangeI"));
redI.setVisibility(savePreferences.getInt("redI"));
blueI.setVisibility(savePreferences.getInt("blueI"));
I'm trying to make app like soundboard. Now I have small problem with playing the same sound after reset after playing 1st time.
final MediaPlayer SoundOne = MediaPlayer.create(this, R.raw.somesound);
final Button play_SoundOne = (Button) this.findViewById(R.id.play_SoundOne);
play_SoundOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SoundOne.start();
}
});
SoundOne.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
SoundOne.reset();
}
});
Can I get help how can I prepare that sound to play again after reset (I do reset to make space in memory for next sounds) but SoundOne.prepare() doesn't work if I put that before .start(). Any advice?
Based on the documentation:
It is a programming error to invoke methods such as getCurrentPosition(), getDuration(), getVideoHeight(), getVideoWidth(), setAudioAttributes(AudioAttributes), setLooping(boolean), setVolume(float, float), pause(), start(), stop(), seekTo(long, int), prepare() or prepareAsync() in the Idle state for both cases. If any of these methods is called right after a MediaPlayer object is constructed, the user supplied callback method OnErrorListener.onError() won't be called by the internal player engine and the object state remains unchanged; but if these methods are called right after reset(), the user supplied callback method OnErrorListener.onError() will be invoked by the internal player engine and the object will be transfered to the Error state.
You cannot immediately start() or prepare after reset(). Based on the documentation for reset:
Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
The solution would be
Initialize the MediaPlayer again -> set the Data Source -> call prepare.
Alternatively you can avoid performing reset onCompletion. Instead, release the MediaPlayer onStop()
You can update your as follows:
MediaPlayer soundOne = null;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
play_SoundOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
soundOne.start();
}
});
}
#Override
protected void onStart() {
super.onStart();
if(soundOne == null){
soundOne = MediaPlayer.create(this, R.raw.somesound);
soundOne.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Don't reset
}
});
}
}
#Override
protected void onStop() {
super.onStop();
soundOne.release();
soundOne = null;
}
I have a CharSequence which displays a sequence of text after each imageview click however the CharSequence seems to restart if the orientation is changed mid sequence.
Does anyone know how this can be resolved?
On an orientation change the activity is restarted, and the inCreate() is called again. You have to take that in consideration.
A small example of how to store and retrieve a value:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
isStarted = savedInstanceState.getBoolean("isStarted");
}
}
#Override
protected void onResume() {
isStarted = true;
super.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isStarted", isStarted);
super.onSaveInstanceState(outState);
}
For more information and methods: Saving Android Activity state using Save Instance State
using android:configChanges="orientation|keyboardHidden|screenSize"> resolved the issue
so i get the main idea of how to use
protected void onSaveInstanceState (Bundle outState)
http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)
also from Saving Android Activity state using Save Instance State
but my problem is what if this was the first time the application is being created? then nothing would have been stored in the bundle before....and if so then when i try to call something out from the bundle that hasn't been saved before what do i get?null?
for example
i have this in my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String [] b=savedInstanceState.getStringArray("MyArray");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
String [] a={"haha"};
savedInstanceState.putStringArray("MyArray", a);
}
in the FIRST time the application is ever opened what would the value of b be?
and after the application has been used once what would the value of b be?
Many thanks!
in your onCreate()
add a condition
if(savedInstanceState==null){
//meaning no data has been saved yet or this is your first time to run the activity. Most likely you initialize data here.
}else{
String [] b=savedInstanceState.getStringArray("MyArray");
}
by the way to retrieve data that was saved in your onSaveInstanceState you will override this
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
}
You have to check for null always in the onCreate() or in onRestoreInstanceState() like below:
String [] b = new String[arraysize];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
b = savedInstanceState.getStringArray("MyArray");
// Do here for resetting your values which means state before the changes occured.
}
else{
default..
}
Here you do general things.
}