关于android:如何在onSaveInstanceState中使用变量

how to use variable in onSaveInstanceState

本问题已经有最佳答案,请猛点这里访问。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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);
}

我想用onSaveInstanceState保存变量resultCode,在恢复活动后再次使用它…

(对不起我的英语水平)


Cyren…1)我没有理由在OnCreate中调用super.onRestoreinstanceState。在方法中进行该调用是有意义的

1
2
public void onRestoreInstanceState(Bundle saved) {
    super.onRestoreInstanceState(saved);

2)声明:

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

是否"隐藏"变量:

1
int resultCode;

早些时候宣布的。所以有两个版本的变量resultcode具有不同的作用域。也许你的意思是编码:

1
2
3
4
5
int resultCode;

stuff here

    resultCode = savedInstanceState.getInt("resultCode");

希望有帮助,日本航空公司