如何在onSaveInstanceState中使用变量

时间:2011-01-15 18:11:36

标签: android

我刚刚开始在android上学习编程,我在onSaveInstanceState使用变量时遇到了问题。这是我的代码:

int resultCode;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if (savedInstanceState != null) {
        super.onRestoreInstanceState(savedInstanceState);

        int resultCode = savedInstanceState.getInt("resultCode");
    } 

    Button btnOpenWithResult = (Button) findViewById(R.id.btnOpenWithResult);
    btnOpenWithResult.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent myIntent = new Intent(flashlight.this, ThirdActivity.class);
            startActivityForResult(myIntent, 1);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (resultCode) {
    case 1:   
         /** option 1  */            
        break;
    case 2:
         /** option 2 */
        break;
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt("resultCode", resultCode);
    super.onSaveInstanceState(savedInstanceState);
}

我想使用resultCode保存变量onSaveInstanceState,并在重新开始活动后再次使用它...

(对不起我的英语水平)

1 个答案:

答案 0 :(得分:5)

Cyren ... 1)我认为没有理由在onCreate中调用super.onRestoreInstanceState。在方法

中进行调用是有意义的
public void onRestoreInstanceState(Bundle saved) {
    super.onRestoreInstanceState(saved);

2)声明:

   int resultCode = savedInstanceState.getInt("resultCode");

正在“隐藏”变量:

int resultCode;

先前宣布。因此,有两个版本的变量resultCode具有不同的范围。也许你的意思是代码:

int resultCode;

stuff here

    resultCode = savedInstanceState.getInt("resultCode");

希望有所帮助, JAL