0

我正在尝试创建一个计数器并在您离开应用程序时尝试保存当前值,所以我尝试使用 onSaveInstanceStateonRestoreInstanceState它似乎不起作用

代码如下

package com.example.taekwondobuddy.util;

import android.app.Activity;

import android.os.Bundle;
import android.view.View;
 import android.widget.Button;
import android.widget.TextView;

public class Counter extends Activity {

int counter;
Button add;
Button sub;
TextView display;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.counter);

    counter = 0;
    add = (Button) findViewById(R.id.button1);
    sub = (Button) findViewById(R.id.button2);
    display = (TextView) findViewById(R.id.tvDisplay);
    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            counter++;
            display.setText("Counter: " + counter);
        }
    });
    sub.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            counter--;
            display.setText("Counter: " + counter);
        }
    });
}

public void onSaveInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);


      savedInstanceState.putInt("counter", counter);


    }

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);


  counter = savedInstanceState.getInt("counter");

   }



  }

这是我第一次过度使用savedInstanceState,所以我想知道语法是否正确,我是否以正确的方式使用它?如果是这样,我的代码有什么问题?帮助和提示表示赞赏

4

2 回答 2

2

You need to swap the order in the methods as the parents' implementation methods will return from the methods and your code won't run. Also, you need to check if the parameter is not null in onRestoreInstanceState.

public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt("counter", counter);
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        counter = savedInstanceState.getInt("counter");
    }
    super.onRestoreInstanceState(savedInstanceState);
}

You also said

I'm trying to make a counter and trying to save the current value when you leave the application

Saving instance state only works when the application is in memory (though leaving the application doesn't remove it). If it's killed, the state will be lost.

于 2013-11-10T07:42:24.030 回答
2

您不需要 onRestoreInstanceState()。这在 onCreate() 之后很长时间被调用,并且对于需要 onCreate() 中的数据的应用程序通常毫无价值。您想在 onCreate() 中检索保存的状态,该状态也通过 Bundle 传递。

在 onCreate() 中:

counter = 0;
if (savedInstanceState != null) {
    counter = savedInstanceState.getInt("counter", 0);
}
于 2013-11-10T07:50:11.850 回答