Science Quiz Android Application - Finale

Now that our layout is completely set, its time to define actions of the True and False buttons. As this is a simple app, with just one question hence, when the user will click on True, we will show a message saying Correct! because Graphite is used to make pencils, its true. And if the user presses the False button then we will show the message Incorrect!

Our ScienceActivity class looks like this by default:

package quiz.studytonight.com.sciencequiz;

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

public class ScienceActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_science);
    }
}

Wiring Button widgets to ScienceActivity Class

We will be defining two private variables of type Button in our ScienceActivity class, and will then hook them up with the widgets defined in the layout xml file. First lets define the two private variables:

public class ScienceActivity extends AppCompatActivity {

    private Button mTrueButton;
    private Button mFalseButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_science);
    }
}

When you will introduce these 2 new variables to your class, Android Studio will give error, saying Cannot resolve symbol 'Button', its because the class Button must be imported in our class to be able to use it. Click on the text Button and press option + return if you are using Macbook, and Alt + Enter if you are a Windows user, to command Android Studio to automatically import the class for you. Memorise this shortcut for future use.


Getting Widget Reference and Setting Listeners

Variable creation was just the start, we now have to assign the Button widget reference to these variables and then set listeners, to listen to click events on this event.

To reference any widget defined in the layout xml, we use findViewById method, its syntax is:

public View findViewById(int id)

This method takes the resource id of the widget(defined as the attribute android:id) as argument and returns a View object.

In ScienceActivity.java class, use the resource ids of the Button widgets to get the View objects, and assign them to your member variables. You will have to cast the returned View object into Button object. Casting the returned View object to the respective widget is always required, whenever you reference any widget defined in the layout xml in the Activity class.

public class ScienceActivity extends AppCompatActivity {

    private Button mTrueButton;
    private Button mFalseButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_science);

        mTrueButton = (Button) findViewById(R.id.true_button);
        mFalseButton = (Button) findViewById(R.id.false_button);
    }
}

Android applications are event driven, hence once an Activity loads up a layout, it will stay in that state until directed by any event to change. These events can be anything, human touch, OS initiated, timer events etc. Object called as listener is attached to a widget to make that widget listen to any event, and the listener implements a listener interface for that event. Android provides listener interfaces for various events. In our case as we have to listen to the "click" event, so we will make our listener implement View.OnClickListener interface.

mTrueButton.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		// Does nothing yet, but soon!
	}
});

Add the aboe code, just below the line where you assign the widget reference to our mTrueButton member variable using findViewById method. And then similarly attach a listener to the mFalseButton as well. The listener above is implemented as Java anonymous inner class.


Displaying Message on click

Now that we have attached listeners to our buttons, we will know when a user click on the True or the False button. We will write the code of displaying the message, inside the respective onClick() methods of the listener interface implementation.

Android provides a very simple way of displaying messages that does not require any input or action, its known as Toast. So we will create Toast displaying Correct! or Incorrect! based on the button press. Following is the method used to create a Toast:

<
public static Toast makeText(Context context, int resId, int duration)

In this, Context will take instance of our Activity(Activity is a subclss of Context). The second parameter is the resource Id of the string message, which will be displayed in the Toast. Hence, we will have to add two more entries into our strings.xml file, one for Correct! and second for Incorrect!. Add the below lines to strings.xml file.

<string name="correct_toast">Correct!</string>
<string name="incorrect_toast">Incorrect!</string>

Now add the code to create Toast inside the onClick() method of both mTrueButton and mFalseButton. We will show you how to do it for one, do it yourself for the other button.

mTrueButton.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		Toast.makeText(ScienceActivity.this,
                           R.string.correct_toast,Toast.LENGTH_SHORT).show();
	}
});

Method show() is used to show the created Toast. For importing the Toast class simply press option + return for Mac and Alt + Enter for Windows to automatically import the required classes.

NOTE: If we use just this to reference the ScienceActivity in makeText method, it will not work, because this here will refer to the View.OnClickListener object, as all this is being done inside the anonymous inner class.


Time to Run our App

You can use Emulator to run the app, but we suggest you to use a real device for running the App. Simply connect your Android Smartphone to your Computer, Android Studio will automatically detect it, and click on the Run button(Green colored Play button).

Ahoy! Your second android app is running, enjoy!