Mitch
Mitch

Reputation: 1069

Use onBackPressed to save a file

I want to allow users to save a list of favourite items from a list, so I display the full list using a Listview with checkboxes, and the user will check or uncheck items in the list.

When the user presses the back button, I want to be able to save the checked items out to a separate file on the SD card.

I'm using the following method in my Activity:

@Override
  public void onBackPressed() {
  // TODO Auto-generated method stub

  }

However, the list that I create within my OnCreate method is not available within the onBackPressed method - ie it's out of scope.

If I try and pass the list into the onBackPressed method as follows:

@Override
  public void onBackPressed(ArrayList<HashMap<String, Object>> checked_list) {
  // TODO Auto-generated method stub

  }

Then I get the error:

"The method onBackPressed(ArrayList>) of type SetFavourites must override or implement a supertype method" and Eclipse prompts to remove the @Override.

But when I do this, then the onBackPressed method never gets called.

How can I pass variables into the onBackPressed method so that I can perform actions on data within my Activity before exiting?

Thanks

Upvotes: 1

Views: 524

Answers (2)

Squonk
Squonk

Reputation: 48871

You can't use @Override to override a non-existent method. In other words onBackPressed(ArrayList<...> foo) is not an existing method of the Activity class.

To access your list declare it as an instance member of your Activity...

public class MyActivity extends Activity {

    ArrayList<HashMap<String, Object>> checked_list;

    // onCreate(...) here

    // onBackPressed() here

}

Upvotes: 1

Sam
Sam

Reputation: 86948

You can define a variable in the class' scope, ie outside onCreate().

class Example {
    int mVisible = 0;

    void onCreate() {
        int notVisible = mVisible;
    }

    void onBackPressed() {
        mVisible = 10;
    }
}

Upvotes: 1

Related Questions