简体   繁体   English

跨轮保存数据在我的android项目中似乎不起作用

[英]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. 我接受了Melquiades的回答,因为他帮助我过滤了可能是问题的一切。 It turns out, I was the problem, not android or anything else. 原来,我是问题所在,不是android或其他任何问题。 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(); 我试图保存onPause();之前的变量状态onPause(); , onStop(); onStop(); , onDestroy(); 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 创建此方法后,书告诉我,然后转到onCreate方法并添加

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. 每当销毁并创建活动时, myIntVariable都会重置为0。

What I did to fix this is I went to my manifest file and added android:configChanges="orientation|screenSize" . 为了解决这个问题,我去了清单文件并添加了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(); 编辑:如建议,我添加我的onCreate(); and onResume(); 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. 出于所有目的和目的,变量mIndexCounter是我提到的“ myIntVariable”。

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. 解决方案: 我使用的是一本书,但不幸的是,由于我不熟悉android编程,因此过分依赖于本书中编写的代码。 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. 我的程序显示了一个依赖于int的文本字符串,该int用于从R.java类检索信息。 After launching the app, when the user presses Next, the data changes because the int is incremented and the String on the view changes. 启动应用程序后,当用户按下Next时,数据会更改,因为int会增加,并且视图上的String也会更改。 This data was to be saved due to the nature of android destroying any unsaved data upon orientation change. 由于Android的性质会在方向更改时销毁所有未保存的数据,因此需要保存此数据。 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. 我要做的就是简单地添加保存的数据,即一个int,与我最初显示此字符串/文本的方式相同。 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(): 在onRestoreInstanceState()中还原变量,而不是在onCreate()中:

@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. 注意:由于不能保证调用onSaveInstanceState(),因此应仅将其用于记录活动的瞬时状态(UI的状态),而永远不要使用它来存储持久性数据。 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. 相反,您应该在用户离开活动时使用onPause()来存储持久性数据(例如应保存到数据库的数据)。

Btw, change your onCreate() signature to: 顺便说一句,将您的onCreate()签名更改为:

@Override
protected void onCreate(Bundle savedInstanceState) {

as in the docs. 如在文档中。

Try this: 尝试这个:

android:configChanges="keyboard|keyboardHidden|orientation"

As stated here 如前所述这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM