Tuesday, October 22, 2013

Howto - Passing data among Android Activities

Invoking an Activity from an Activity
In our scenario, we have a LoanCalculatorActivity invoking another Activity - AmortizationActivity upon an user event, says a "Amortization" button is clicked. Activity is started by an Intent, so in LoanCalculatorActivity, an instance of Intent is created and started with the startActivity(...) function.




Intent anIntent=new Intent(view.getContext(),AmortizationActivity.class);
startActivity(anIntent);


Passing data from the calling Activity to the called Activity
Data can be put into the Bundle object (can be retrieved through getExtras()) of an Intent directly through the putExtra(,). The is a string. The is the data value of the key-value pair put into the Bundle. Android API supports mainly the primitive datatypes and their array for . You can also uses String, Parcelable, Bundle and Serializable as . Say we want to pass a String value, the code becomes ...




Intent anIntent=new Intent(view.getContext(),AmortizationActivity.class);
anIntent.putExtras("amortization", "amortization value");
startActivity(anIntent);


On the called Activity (i.e. AmortizationActivity), the data is retrieved by



Bundle aBundle=getIntent().getExtras();
String aString=aBundle.getString("amortization");

Passing Object in Activities
Passing primitive data are inflexible and against the principle of OOP, Android API provides two alternatives of passing object - Serializable or Parcelable. Parcelable requires more coding effort but more flexible as you might want to pass object that is not Serializable. However, so far I am quite happy using Serializable as I can simple tag a Class to implement Serializable.




public class LoanCalculator implements Serializable {
private double principal;
private double annualRate;
private int periodsPerYear;
private int year;
...
};


On the calling Activity, an instance of the LoanCalculator is created and populated ...



Intent anIntent=new Intent(view.getContext(),AmortizationActivity.class);
LoanCalculator aCalculator=new LoanCalculator()
// populate aCalculator
anIntent.putExtra("calculator", aCalculator);
anIntent.getExtras()
startActivity(anIntent);
};



Now on the called Activity, the Calculator object (is not the same instance) is deserialized and it's functions can be invoked to calculate the amortization schedule as ...



protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.amortization);
TableLayout aTable=(TableLayout)findViewById(R.id.amortization);
Bundle aBundle=getIntent().getExtras();
if(aBundle!=null){
LoanCalculator amortization=(LoanCalculator)aBundle.getSerializable("calculator");
String[][] amortValues=amortization.computeAmortization();
appendRows(aTable,amortValues);
}
};