Step 07 - Radio Button

In donateButtonPressed we need to discover which payment method has been selected. Our RadioGroup documentation is here:

This looks like the method we need:

This is a revised version of donateButtonPressed()

  1. public void donateButtonPressed (View view)
  2. {
  3. int amount = amountPicker.getValue();
  4. int radioId = paymentMethod.getCheckedRadioButtonId();
  5. String method = "";
  6. if (radioId == R.id.PayPal)
  7. {
  8. method = "PayPal";
  9. }
  10. else
  11. {
  12. method = "Direct";
  13. }
  14. Log.v("Donate", "Donate Pressed! with amount " + amount + ", method: " + method);
  15. }

Run it now and verify we are getting the correct logs.

We can simplify it somewhat by reducing the if statement to a singlle line:

  1. String method = radioId == R.id.PayPal ? "PayPal" : "Direct";

This is the Java ternary operator:

This is the complete activity class:

  1. package com.example.donation;
  2. import android.os.Bundle;
  3. import android.app.Activity;
  4. import android.content.res.Resources;
  5. import android.util.Log;
  6. import android.view.Menu;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.RadioGroup;
  10. import android.widget.NumberPicker;
  11. import android.widget.ProgressBar;
  12. public class Donate extends Activity
  13. {
  14. private Button donateButton;
  15. private RadioGroup paymentMethod;
  16. private ProgressBar progressBar;
  17. private NumberPicker amountPicker;
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState)
  20. {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.activity_donate);
  23. donateButton = (Button) findViewById(R.id.donateButton);
  24. paymentMethod = (RadioGroup) findViewById(R.id.paymentMethod);
  25. progressBar = (ProgressBar) findViewById(R.id.progressBar);
  26. amountPicker = (NumberPicker) findViewById(R.id.amountPicker);
  27. amountPicker.setMinValue(0);
  28. amountPicker.setMaxValue(1000);
  29. }
  30. @Override
  31. public boolean onCreateOptionsMenu(Menu menu)
  32. {
  33. getMenuInflater().inflate(R.menu.donate, menu);
  34. return true;
  35. }
  36. public void donateButtonPressed (View view)
  37. {
  38. int amount = amountPicker.getValue();
  39. int radioId = paymentMethod.getCheckedRadioButtonId();
  40. String method = radioId == R.id.PayPal ? "PayPal" : "Direct";
  41. Log.v("Donate", "Donate Pressed! with amount " + amount + ", method: " + method);
  42. }
  43. }