24

I just started learning programming at the android and I have a problem with using variable at onSaveInstanceState. This is my code:

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);
}

I want to save the variable resultCode using onSaveInstanceState and after the resumption of activity once again to use it ...

(sorry for my level of English)

Mykola
  • 3,343
  • 6
  • 23
  • 39
Cyren
  • 249
  • 1
  • 2
  • 3
  • Be more specific, what exactly is your problem? Did you tried to assign value to resultCode. – Kiril Kirilov Jan 15 '11 at 18:32
  • My problem is save state of variable resultCode (switch) to onSaveInstanceState. When I write: savedInstanceState.putInt("resultCode", resultCode); and after that try use: int resultCode = savedInstanceState.getInt("resultCode"); then variable resultCode it's empty – Cyren Jan 15 '11 at 21:02
  • you should explore other options for permanent storage of data in memory. For instance, why not declare the variable as static or even on a static class apart? – Miguel Tomás Feb 26 '21 at 08:54

1 Answers1

6

Cyren... 1) I see no reason to call super.onRestoreInstanceState in onCreate. It WOULD make sense to make that call in the method

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

2) The declaration:

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

is "hiding" the variable:

int resultCode;

declared earlier. So there are two version of the variable resultCode with different scopes. Perhaps you mean to code:

int resultCode;

stuff here

    resultCode = savedInstanceState.getInt("resultCode");

Hope that helps, JAL

JAL
  • 3,319
  • 2
  • 20
  • 17