The answers here are not mistaken, but they are incomplete, in my opinion. The best way to do this with validations is to make sure that additional data is taken from the previous action, as well as the saved InstanceState, which is the Bundle data received when the Activity started, and can be returned to onCreate if you need to activate the activity (for example, changing the orientation), so that you do not lose this preliminary information. If there was no data, savedInstanceState is NULL.
Sending data -
Intent intent = new Intent(context, MyActivity.class); intent.putExtra("name", "Daenerys Targaryen"); intent.putExtra("number", "69"); startActivity(intent);
Data Acquisition -
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.myactivity); int no; String na; if(savedInstanceState == null){ Bundle extras = getIntent().getExtras(); if(extras != null){ no = Integer.parseInt(extras.getString("number")); na = extras.getString("name"); } }else{ no = (int) savedInstanceState.getSerializable("number"); na = (String) savedInstanceState.getSerializable("name"); }
source share