Space Ghost
Space Ghost

Reputation: 765

Saving data across rotation does not seem to work in my android project

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.

Upvotes: 0

Views: 374

Answers (2)

Melquiades
Melquiades

Reputation: 8598

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.

Upvotes: 1

coder
coder

Reputation: 13248

Try this:

android:configChanges="keyboard|keyboardHidden|orientation"

As stated here

Upvotes: 0

Related Questions