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.
}
Related
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"));
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()
PLESAE NOTE: The solution to my problem is in bold text at the bottom. I accepted Melquiades's answer because he helped me filter out everything that could have been the problem. It turns out, I was the problem, not android or anything else. So if you are looking for the answer, read below.
I'm trying to save the state of a variable as it is before onPause(); , onStop(); , onDestroy(); are called.
The book I am using has me override a method called
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX, myIntVaraible);
}
the variables you see in the parameter are declared at the beginning of the class
private static final String KEY_INDEX = "index";
private int myIntVariable;
with this method created, the book tells me to then go the the onCreate method and add
if(savedInstanceState != null){
myIntVariable = savedIntanceState.getInt(KEY_INDEX, 0);
}
But this does not work.
Whenever the activity is destroyed and created, the myIntVariable is reset to 0.
What I did to fix this is I went to my manifest file and
added android:configChanges="orientation|screenSize".
However, I have read that this is not practical and is strongly advised against.
EDIT: As suggested, I am adding my onCreate(); and onResume(); methods..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate()");
setContentView(R.layout.activity_main);
iterateQuestions();
mTrueButton = (Button)findViewById(R.id.trueBt);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
correctPressed = true;
checkForTrue();
}
});
mFalseButton = (Button)findViewById(R.id.falseBt);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
falsePressed = false;
checkForFalse();
}
});
mNextButton = (ImageButton)findViewById(R.id.nextBt);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
try{
mIndexCounter++;
mTextViewQuestion = (TextView)findViewById(R.id.text_question_view);
int QuestionToShow = mQuestionBank[mIndexCounter].getQuestion();
mTextViewQuestion.setText(QuestionToShow);
}
catch(Exception e){
iterateQuestions();
}
}
});
mTextViewQuestion = (TextView)findViewById(R.id.text_question_view);
mTextViewQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
try{
mIndexCounter++;
mTextViewQuestion = (TextView)findViewById(R.id.text_question_view);
int QuestionToShow = mQuestionBank[mIndexCounter].getQuestion();
mTextViewQuestion.setText(QuestionToShow);
}
catch(Exception e){
iterateQuestions();
}
}
});
mPrevButton = (ImageButton)findViewById(R.id.prevBtn);
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
try{
mIndexCounter--;
mTextViewQuestion = (TextView)findViewById(R.id.text_question_view);
int QuestionToShow = mQuestionBank[mIndexCounter].getQuestion();
mTextViewQuestion.setText(QuestionToShow);
}catch(Exception e){
iterateQuestionsReverse();
}
}
});
}
and
#Override
public void onResume(){
super.onResume();
Log.d(TAG,"onResume()");
}
For all intents and purposes, the variable mIndexCounter is the "myIntVariable" I mentioned.
SOLUTION: I was using a book and unfortunately, since I am new to android programming, relied too much on the code written in the book. The authors usually add new code in their book as bold, black text. This time, they failed to do that and I had trouble figuring out why my data was not being saved. It turns out that it was saved all along, I just failed to update the view with the saved data whenever it was retrieved. After adding 3 lines of simple code, my mistake was obvious and the goal I had been trying to accomplish, a success.
My program displayed a string of text that was dependant on an int that was used to retrieve information from the R.java class. After launching the app, when the user presses Next, the data changes because the int is incremented and the String on the view changes.
This data was to be saved due to the nature of android destroying any unsaved data upon orientation change.
All I had to do was simply add the saved data, an int, the same way I used to display this string/text in the first place. Instead, I foolishly assumed it would do it automatically because the book did not add this code and I relied on it too much.
This was a great learning experience and if anyone ever comes across something like this, feel free to email me if my answer is not clear.
Instead of in onCreate(), restore your variable in onRestoreInstanceState():
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myIntVariable = savedIntanceState.getInt(KEY_INDEX, 0);
}
The docs also say:
Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.
Btw, change your onCreate() signature to:
#Override
protected void onCreate(Bundle savedInstanceState) {
as in the docs.
Try this:
android:configChanges="keyboard|keyboardHidden|orientation"
As stated here
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
I'm creating a simple app where the user can change the seekbar value. make the default value as 0 and setMax as 5. Every time the app is closed and started back, seekbar value is set to 0. How can I use and set the previous seekbar value which was set before closing the app.
Here's my Activity class >
public class MainActivity extends Activity {
SeekBar s;
TextView v;
public int n;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s=(SeekBar)findViewById(R.id.seekBar1);
v=(TextView)findViewById(R.id.textView1);
next=(Button)findViewById(R.id.button1);
s.setProgress(n);
v.setText(n+" ");
s.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
n = progress;
v.setText(n+" ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
v.setText(n+" ");
}
});
}
}
I Tried using onSaveInstanceState and onRestoreInstanceState but failed to restore back to the previous state.
Please Help
Thanks in Advance.
First of all, onSaveInstance and onRestoreInstance method are triggered only, when a destruction because of orientation change happens, hence you can not use this mechanism with that purpose, in order to store previous values after explicitly destroying the activity, you can use one of the persistance mechanisms that android provides. SharedPreferences or SQLiteDB saving them before destroying the activity, and restoring when the activity is started.
To get the latest value if any you have to add this code in onCreate method:
private SharedPreferences prefs;
private int progress;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
progress = prefs.getInt("myProgress", 0);
}
//And to store it all the time before the activity is destroyed you have to add this code in onPause:
protected void onPause() {
super.onPause();
Editor editPrefs = prefs.edit();
editPrefs.putInt("myProgress", newProgressValue);
editPrefs.commit();
}
Hope this helps.
Regards!
You might want to look at Storage Options in the Developers guide.
Specifically, Shared Preferences seems like a good place to start.
you can try to use SQL database, the database will be availble even after the app is closed and reopened