public class FirstActivity extends Activity {
private String userName;
private Uri userPhoto;
private void onOkButtonPressed() {
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(SecondActivity.Key.USER_NAME, userName);
intent.putExtra(SecondActivity.Key.USER_PHOTO, userPhoto);
startActivity(intent);
}
}
public class SecondActivity extends Activity {
public static class Key {
public static final String USER_NAME = "USER_NAME";
public static final String USER_PHOTO = "USER_PHOTO";
}
private String userName;
private Uri userPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.container);
init();
}
private void init() {
Intent intent = getIntent();
userName = intent.getStringExtra(Key.USER_NAME);
userPhoto = intent.getParcelableExtra(Key.USER_PHOTO);
}
}
Or maybe it would be better to make the keys private
inside SecondActivity
and do something like this?
public class SecondActivity extends Activity {
private static class Key {
public static final String USER_NAME = "USER_NAME";
public static final String USER_PHOTO = "USER_PHOTO";
}
public static void start(Context context, String userName, Uri userPhoto) {
Intent intent = prepareIntent(context, userName, userPhoto);
context.startActivity(intent);
}
public static Intent prepareIntent(Context context, String userName, Uri userPhoto) {
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra(Key.USER_NAME, userName);
intent.putExtra(Key.USER_PHOTO, userPhoto);
return intent;
}
// skipped
}
It slightly improves readability:
SecondActivity.start(this, userName, userPhoto);
But on the other hand, it becomes complicated to make changes. Every time when I want add new fields or change existing fields, I should also change the arguments list in the method start()
. And this way is also not suitable in the case when number of the input parameters will increase significantly.