So if you are like me, you prefer to transfer data around in you application using a simple objects that really only contain public or private fields and/or their getters and setters. For lack of a better term I’m going to call these object Data Transfer Objects (DTO) even thought we are not technically passing data between two different computing processes in this example.
My custom DTO is below, so now how do I get this data to a new activity in android?
public class BurndownWorkoutData
{
public String WeightSet;
public int BarWeight;
public int InitialWeight;
public int DecrementAmount;
public int RepIncrement;
private String ErrorMessage;
public String GetErrorMessage()
{
if(ErrorMessage != null) return ErrorMessage;
return "";
}
public void SetErrorMessage(String errorMessage)
{
if(errorMessage != null) {
ErrorMessage = errorMessage;
}
}
}
I’m currently targeting android SDK version 16 and in this version there is no method that allows the passing of an object to a new Intent, at least not directly.
But we can pass an object that implements the Serializable interface. So lets do just that.
The new DTO…
public class BurndownWorkoutData implements Serializable
{
public String WeightSet;
public int BarWeight;
public int InitialWeight;
public int DecrementAmount;
public int RepIncrement;
private String ErrorMessage;
public String GetErrorMessage()
{
if(ErrorMessage != null) return ErrorMessage;
return "";
}
public void SetErrorMessage(String errorMessage)
{
if(errorMessage != null) {
ErrorMessage = errorMessage;
}
}
}
Now when after we have initialized our Intent object, we can pass the object to the putExtra method.
Below we see the putExtra() call passing in two arguments, one is the key that will be used to retrieve the object and the other is the object that implements the Serializable interface.
CalcUtils.BurndownWorkoutData burndownDTO = GetInputData();
Intent burndownActivity = new Intent(this,burndownView.class);
burndownActivity.putExtra("burndowndata",burndownDTO);
startActivity(burndownActivity);
Now lets move to the new Activity to get the object back.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_burndown_view);
CalcUtils.BurndownWorkoutData data = (CalcUtils.BurndownWorkoutData) getIntent().getSerializableExtra("burndowndata");
}
To get the object back we simple call the getIntent().getSerializableExtra() method and pass in the key that we used in the putExtra() method call in the previous step.