Donation Model & Base Class

In order to keep our application design coherent, we now bring in an Base class and a Donation class to manage our Donations. You can continue with your own version of the app or start with the solution from the previous lab - Donation.2.0

First, create a new package called ‘app.models’ and bring in this class here:

  1. package app.models;
  2. public class Donation
  3. {
  4. public int amount;
  5. public String method;
  6. public Donation (int amount, String method)
  7. {
  8. this.amount = amount;
  9. this.method = method;
  10. }
  11. }

Next, Create a new class called ‘Base’ and add it to the ‘app.activities’ package:

  1. public class Base extends Activity
  2. {
  3. public final int target = 10000;
  4. public int totalDonated = 0;
  5. public static List <Donation> donations = new ArrayList<Donation>();
  6. public boolean newDonation(Donation donation)
  7. {
  8. boolean targetAchieved = totalDonated > target;
  9. if (!targetAchieved)
  10. {
  11. donations.add(donation);
  12. totalDonated += donation.amount;
  13. }
  14. else
  15. {
  16. Toast toast = Toast.makeText(this, "Target Exceeded!", Toast.LENGTH_SHORT);
  17. toast.show();
  18. }
  19. return targetAchieved;
  20. }
  21. @Override
  22. public boolean onCreateOptionsMenu(Menu menu)
  23. {
  24. getMenuInflater().inflate(R.menu.donate, menu);
  25. return true;
  26. }
  27. @Override
  28. public boolean onPrepareOptionsMenu (Menu menu){
  29. super.onPrepareOptionsMenu(menu);
  30. MenuItem report = menu.findItem(R.id.menuReport);
  31. MenuItem donate = menu.findItem(R.id.menuDonate);
  32. if(donations.isEmpty())
  33. report.setEnabled(false);
  34. else
  35. report.setEnabled(true);
  36. if(this instanceof Donate){
  37. donate.setVisible(false);
  38. if(!donations.isEmpty())
  39. report.setVisible(true);
  40. }
  41. else {
  42. report.setVisible(false);
  43. donate.setVisible(true);
  44. }
  45. return true;
  46. }
  47. public void settings(MenuItem item)
  48. {
  49. Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show();
  50. }
  51. public void report(MenuItem item)
  52. {
  53. startActivity (new Intent(this, Report.class));
  54. }
  55. public void donate(MenuItem item)
  56. {
  57. startActivity (new Intent(this, Donate.class));
  58. }
  59. }

Notice our List of Donations in the Base class - we will use this list to display our Donations in the Report.

Your project should now look as follows:

Step 01 - 图1