Java Programming for Android Developers For Dummies
Book image
Explore Book Buy On Amazon
You can make meaningful use of Java's logical operators in your Android app. In the code below, the app gets two pieces of information from the user. The app gets a person's age, and gets a check or no-check, indicating a movie's special showing status.

package com.allmycode.a06_01;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;

import android.view.View;

import android.widget.CheckBox;

import android.widget.EditText;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

EditText ageEditText;

CheckBox specialShowingCheckBox;

TextView outputTextView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ageEditText = (EditText) findViewById(R.id.ageEditText);

specialShowingCheckBox =

(CheckBox) findViewById(R.id.specialShowingCheckBox);

outputTextView = (TextView) findViewById(R.id.outputTextView);

}

public void onButtonClick(View view) {

<strong>int age = Integer.parseInt(ageEditText.getText().toString());</strong>

<strong>boolean isSpecialShowing = specialShowingCheckBox.isChecked();</strong>

boolean chargeDiscountPrice = (age < 18 || 65 <= age) && !isSpecialShowing;

outputTextView.setText(Boolean.toString(chargeDiscountPrice));

}

}

There's more to the app than the code. To create this app, you have to design the layout with its text fields, its check box, and its button. You also have to set the button's onClick property to "onButtonClick".

Every check box has an isChecked method and the isSpecialShowing variable gets its value from a call to the isChecked method. Here, the user hasn't selected the check box. So, when Android executes the code, the expression specialShowingCheckBox.isChecked() has the value false.

java-programming-for-android-developers-2e-discounted-movie-price
Getting a discounted movie ticket.

But, in this image, the user has selected the check box. So, when Android executes the code, the expression specialShowingCheckBox.isChecked() has the value true.

java-programming-for-android-developers-2e-full-movie-price
Paying the full price for a movie ticket.

To make the code work, you have to associate the variable names ageEditText, specialShowingCheckBox, and outputTextView with the correct thingamajigs on the device's screen. The findViewById statements help you do that.

About This Article

This article is from the book:

About the book author:

Barry Burd, PhD, is a professor in the Department of Mathematics and Computer Science at Drew University in Madison, New Jersey. He has lectured at conferences in the United States, Europe, Australia, and Asia. He hosts podcasts and videos about software and other technology topics. He is the author of many articles and books, including Java For Dummies.

This article can be found in the category: