Skip to content
Luca Guzzon edited this page Apr 7, 2015 · 3 revisions

This annotation will help you to reduce your persistance code. It has two separated behaviours: When it's applied to Views, and when it's not.

Instead of having to override the onSaveInstanceState method, add everything to the Bundle, check if the savedInstanceState was null at the onCreate... you can simplify it by only annotating a variable with @SaveState.

How to use

In order to work propperly, you must ensure that:

  • Your variable can be written to a Bundle object (check Bundle documentation)
  • You must make a call to SwissKnife.restoreState(this, savedInstanceState) in order for the state to be restored.

Keep calm

Don't worry if you manually override the onSaveInstanceState method with some code, it doesn't matter, SwissKnife will append any necessary statements to the already existing code

Example

@SaveInstance
public int myInt

// You can also set a custom tag to your variable
@SaveInstance("MYSTRING")
public String myString

@Override
public void onCreate(Bundle savedInstanceState){
    // Your previous code
    SwissKnife.restoreState(this, savedInstanceState)
}

In case your variable is not one of the types that can be written to a Bundle, the compilation will fail and show which class is giving the error.

Of course, it supports Parcelable objects (also arrays and ArrayLists).

Make sure you check the sample for more examples.

##Views

@SaveInstance can also be used to save the state of views. Though Android usually will do that automatically if the view has an id, you can still use this annotation to force that restoration or use it on views without id.

@SaveInstance
TextView myTextView;

@Override
public void onCreate(Bundle savedInstanceState){
    // Your previous code
    if(savedInstanceState == null) {
         // If the Activity recreates, myTextView will retain the "Hey!" text
         myTextView.setText("Hey!")
    }
    SwissKnife.restoreState(this, savedInstanceState)
}

How is this done? Every view has two methods, onSaveInstanceState() and onRestoreInstanceState(Parcelable) in which they will store their state when called. Usually those methods are called from their containing Activities and Fragments as they are destroyed and recreated when their homonymous methods are called. SwissKnife just forces those calls when needed.