Android DevelopmentAndroid Robot Featured

Ever wondered how to pass data between a Fragment and an Activity?  If you’re a beginner, reviewing the developer documentation on the Android Developer site might not be straightforward.  Let’s create a simple Android app that demonstrates how to pass data between a Fragment and an Activity.
We’re going to create a simple bank account app that displays the balance of two accounts and allow the user to update each account balance.  We will be using DialogFragments to update the account balances.  We’ll use the new Layout Editor to design the screens using constraints in Android Studio.

Design

Using Android Studio’s new Constraint Layout system, adding labels and buttons to the designer is very simple.  At times the constraint system doesn’t quite work which indicates that it’s not quite a mature system just yet.  Overall, it was easy to wire up the widgets with the property inspector

Main Layout View

The Main Layout view contains the primary design for the app.  Blueprint mode provides a nice view into the structure of your app.

Layout in Android Studio
Layout in Android Studio

Account 1 Dialog View

The Account1 dialog view contain a TextView and an EditText widget for accepting user input.  Since this is a simple app which focuses on passing data between a Fragment and an Activity, no attempt is made to validate user input.

Account1 Dialog
Account1 Dialog

Account 2 Dialog View

A hint is used in the EditText to provide an example to users of what type values to enter.  The Blueprint view in the designer is really nice when you want to focus on the structure of your app and not all the visual noise.

Account2 Dialog
Account2 Dialog

Development

Account Model

The Account class is a simple Java class that describes the Account model.  The constructor performs basic validation to ensure that the initial account balance cannot be a negative number.

public class Account {

private double balance;

public Account(double initialAccountBalance){

if(initialAccountBalance > 0.0){

this.balance = initialAccountBalance;

}

}

public void credit(double amount){

balance += amount;

}

public double getBalance(){

return balance;

}

}

Main Activity

The MainActivity class wires up the widgets on the main view.  We create two Account objects, set and then assign their initial balance in the onCreate method.  We then display the initial balance on the TextView.  We also create two button click events that trigger a dialog to open.

public class MainActivity extends AppCompatActivity {   Account acc1;   Account acc2;   TextView acc1InitialBal;   TextView acct2InitialBal;   @Override   protected void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.activity_main);       acc1 = new Account(100.00);       acc2 = new Account(0.00);       acc1InitialBal = (TextView) findViewById(R.id.account1BalId);       String acc1Bal = String.format("Account1 balance: $%.2f", acc1.getBalance());       acc1InitialBal.setText(acc1Bal);   }   public void account1DepositBtn(View view){       AccountFragment accountFragment = new AccountFragment();       accountFragment.show(getSupportFragmentManager(), "account_dialog");   } }

Account Fragment

The AccountFragment class gets the Account object from the MainActivity class.  The class then grabs the value entered in the dialog and passes to the credit method of the Account object.

// Pass account1 value to AccountFragment final Account account1 = ((MainActivity)getActivity()).acc1; builder.setView(view) .setTitle(R.string.<i>account1_dialog_title</i>) .setPositiveButton(R.string.<i>save</i>, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText accountValue = (EditText) view.findViewById(R.id.<i>account1ValueId</i>); account1.credit(Double.<i>parseDouble</i>(accountValue.getText().toString())); // Pass account balance back to activity and update the account1 label TextView account1TextView = ((MainActivity)getActivity()).acc1InitialBal; account1TextView.setText(String.<i>format</i>("Account1 balance: $%.02f", account1.getBalance())); } })

Distribute

Here is the app running in the Android emulator.

Account Main View
Account Main View
Account Dialog View
Account Dialog View

If you’re interested in checking out the entire source code for the app, here is the download link.  If you have questions, please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment