Last active
March 21, 2017 18:27
-
-
Save kmerrell42/4a25009433e28e6e62e76f19da44cb65 to your computer and use it in GitHub Desktop.
Android InstanceState and createIntent() examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MovieDetailActivity extends AppCompatActivity { | |
private static final String EXTRA_INSTANCE_STATE = "extra:instanceState"; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_movie_detail); | |
InstanceState is = InstanceState.from(getIntent().getExtras()); | |
displayMovieDetail(is.id, is.rank); | |
} | |
private void displayMovieDetail(String id, int rank) { | |
... | |
} | |
public static Intent createIntent(Context context, String id, int rank) { | |
Intent intent = new Intent(context, MovieDetailActivity.class); | |
intent.putExtras(new InstanceState(id, rank).toBundle(new Bundle())); | |
return intent; | |
} | |
private static class InstanceState implements Serializable { | |
private final String id; | |
private final int rank; | |
private InstanceState(String id, int rank) { | |
this.id = id; | |
this.rank = rank; | |
} | |
Bundle toBundle(Bundle bundle) { | |
bundle.putSerializable(EXTRA_INSTANCE_STATE, this); | |
return bundle; | |
} | |
private static InstanceState from(Bundle bundle) { | |
return (InstanceState) bundle.getSerializable(EXTRA_INSTANCE_STATE); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment