Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introduction to Android Programming in Android Studio 3.0

DZone's Guide to

Introduction to Android Programming in Android Studio 3.0

This basic guide to the concepts and steps of mobile application development in Android Studio 3.0 will help you get started.

· Mobile Zone
Free Resource

Basic Concepts

  • Activity: An activity is a single, standalone module of application functionality that usually correlates directly to a single user interface screen and its corresponding functionality.
  • Intent: The mechanism by which one activity is able to launch another and implement the flow through the activities that make up an application.
  • View: items in a user interface such as the Button, CheckBox, RadioBox and so on, are subclasses of the Android View class. Views are also called widgets or components.
  • Layout is a container view that is designed for controlling how child views are positioned on the screen. Some layouts are LinearLayout, TableLayout, RelativeLayout, GridLayout, CoordinatorLayout, ConstraintLayout, FrameLayout, etc. By default, Android Studio 3.0 will support the ConstraintLayOut.
  • Resources: contain resources such as the strings, images, fonts, and colors that appear in the user interface together with the XML representation of the user interface layouts. All of the text in a user interface is contained in resource files (default is strings.xml). This can be valuable when translating a user interface to a different spoken language.

How to Create an Android Application

Create a New Project

  • Open Android Studio 3.0
  • Choose File > New > New Project
  • Enter Application name: My_First_Android_App

Image title

  • Click Next and fill out the options, as in the following screenshot:

Image title

  • Click Next and choose Empty Activity.

Image title

  • Click Next, accept the default options, and Finish.
  • By default, a Hello World message will occur on the main screen, as in the following screenshot:

Image title

This interface is the activity_main.xml file in the Design mode. We can switch to the Text mode by selecting the Text tab:

Image title

You can run the application by clicking Run ‘app’ (or Shift + F10) on the Toolbar.

Image title

 The result looks like this:

Image title

  • Close the app. Navigate back to the Design mode of the activity_main.xml file.

Using Standard Controls

Android Studio contains many standard controls, such as Button, TextView, CheckBox, RadioButton, Plain Text, and so on. To use them, we just drag and drop them. All standard controls are contained in the Palette menu:

Image title

  • In the Palette menu, select and drag the Button control to be centered underneath the Hello World message:

Image title

Image title

  • Make sure the Button is still selected.
  • In the Attributes window (on the right-hand side), scroll down to find the text attribute of the button.
  • Change the content from Button to Next Page.

Image title

  • Run the application.

Image title

  • The button will be displayed in the upper left corner because we have not set up the constraint for the button.
  • Close the app and navigate back to activity_main.xml in Design mode and look inside the Component Tree window. The red exclamation mark will be shown by the button in the Component Tree window, and the below message is displayed when moving the cursor to it:

Image title

To solve this problem, we click the white circles that appear around the button:

Image title

And create connections to the margins of the main page:

Image title

  • Now, let's look back to the button in the Component Tree again; a yellow triangle symbol will be there. If we move the cursor to this symbol, a warning message will occur:

Image title

  • To solve this warning, we find and open the values folder and choose the strings.xml file:

Image title

  • In the strings.xml file, we enter the following code:

Image title

  • Navigate back activity_main.xml file in the Design mode, choose the button and enter @string/nextpage in text attribute of the button as the following screenshot

Image title

Create the Second Activity

Beside main activity, we can create other activities easily. The following steps will illustrate how to create the second activity:

  • Right-click app, choose New > Activity > Empty Activity

Image title

  • Change this activity’s name to SecondActivity and click the Finish button.
  • In the Design mode of the second activity (activity_second.xml file), drag TextView from the Palette menu and drop it at the center of the second activity (and keep in mind that we must set up the constraint for this TextView):

Image title

  • In the strings.xml file, we add the following code:

Image title

  • Navigate back to activity_second.xml in Design mode. In the text attribute in the Attributes window, typing @string/next_text, as in the following screenshot:

Image title

  • In Id attribute, change content from textview2 to text2.

Write Java Code

When we create a new application, we can work with two files: XML file, which contains the XML code that creates the layout of the application, and Java file, which contains the Java code that creates functions for components of the application. In our application, these files are MainActivity.java, activity_main.xml (for the main activity), SecondActivity.java, and activity_second.xml (for the second activity).

By default, Android Studio will generate some code automatically, as follows:

Image title

Event Handling

The Android framework maintains an event queue, into which events are placed as they occur. In order to be able to handle the event that has been passed, the view must have in place an event listener, and in order to be able to respond to an event of a particular type, a view must register the appropriate event listener and implement the corresponding callback method. For example, if a button is to respond to a click event, it must both register the View.onClickListener event listener and implement the responding onClick callback method. The following steps will illustrate how to work with the click event of our button:

  • Select the MainActivity.java tab.
  • Add the following lines of code at the end of the onCreate method:
protected void onCreate(Bundle savedInstanceState) {

 super.onCreate(savedInstanceState);

 setContentView(R.layout.activity_main);

 // create the button object

 Button button = (Button) findViewById(R.id.button);

 //register the View.onClickListener

 button.setOnClickListener(new View.OnClickListener() {

   // implement onClick callback method

   public void onClick(View v) {

    // some code                                         

   }

  }

 );

}
  • You must add the import statements:
import android.view.View;

import android.widget.Button;

import android.widget.TextView;

Call Another Activity by Using the Intent

So far, we have created two activities; assume that we want to move on to the second activity from the main activity by clicking the Next Page button. To do this, we can use the intent object and startActivity() method as follows:

Intent intent = new Intent(this, SecondActivity.class);

startActivity(intent);

The complete code for the Next Page button:

protected void onCreate(Bundle savedInstanceState) {

 super.onCreate(savedInstanceState);

 setContentView(R.layout.activity_main);

 // create the button object

 Button button = (Button) findViewById(R.id.button);

 //register the View.onClickListener

 button.setOnClickListener(new View.OnClickListener() {

   // implement onClick callback method

   public void onClick(View v) {

    Intent intent = new Intent(this, SecondActivity.class);

    startActivity(intent);

   }

  }

 );

}

Run the app.

Image title

  • Click the Next Page button.

Image title

  • Close the app.

Display a Message Box

  • Go back the activity_main.xml file in the Design mode. Adding a button to the main activity, change its id attribute from button2 to display and set up the constraint for it, as in the following screenshot:

Image title

  • In strings.xml  file, add the following line of code:

Image title

  • Go back activity_main.xml in Design mode, choose the Display button and in the Attributes window, entering @string/display inside its text attribute:

Image title

  • In MainActivity.java, adding the following lines of code into onCreate method (and underneath lines of code for the Next Page button):

@Override

protected void onCreate(Bundle savedInstanceState) {

 super.onCreate(savedInstanceState);

 setContentView(R.layout.activity_main);

 // code for the Next Page button

 Button button = (Button) findViewById(R.id.button);

 button.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

    Intent intent = new Intent(this, SecondActivity.class);

    startActivity(intent);

   }

  }

 );

 // code for the Display button

 Button display_btn = (Button) findViewById(R.id.display);

 display_btn.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

    display();

   }

  }

 );

}
  • The display() method:
private void display() {

 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

 dlgAlert.setMessage("Hello World! I am Ngoc Minh.");

 dlgAlert.setTitle("My First App");

 dlgAlert.setPositiveButton("OK", null);

 dlgAlert.setCancelable(true);

 dlgAlert.create().show();

}
  • You must add the import statement:
import android.app.AlertDialog;
  • Run the app:

Image title

  • Click the DISPLAY button:

Image title

Get and Set Data From the User Interface

In activity_second.xml in the Design mode, adding one button and EditTexts, as in the following screenshot:

Image title

  • Set the value for the Id attributes of EditTexts and the CALCULATE button, as in the following table:

Default value

New value

editText1

value1

editText2

value2

editText3

result

button

cal_btn

  • In the SecondActivity.java file, adding the following lines of code:
Button cal = (Button) findViewById(R.id.cal_btn);
final EditText val1 = (EditText) findViewById(R.id.value1);
final EditText val2 = (EditText) findViewById(R.id.value2);
final EditText result = (EditText) findViewById(R.id.result);

cal.setOnClickListener(new View.OnClickListener() {

  public void onClick(View v) {

   int num1 = Integer.parseInt(val1.getText().toString());

   int num2 = Integer.parseInt(val2.getText().toString());

   String str = String.valueOf(cal(num1, num2));

   result.setText(str);

  }

 }

);
  • cal() method:
private int cal(int val1, int val2) {

 return val1 + val2;

}
  • Run the app:

Image title

  • Click the NEXT PAGE button:

Image title

 

  • Enter values for the first value and the second value. Click the CALCULATE button:

Image title

  • Close the app.
  • Adding RadioButtons to the second activity. The second activity looks like this:

Image title

We must group RadioButtons together inside a RadioGroup. This ensures that only one RadioButton can be selected at a time.

  • Set the values for Id attributes of RadioButtons, as in the following table:

Default value

New value

radioButton1

add

radioButton2

sub

radioButton3

mul

radioButton4

div


  • Declaring variables and actions is shown as the following lines of code:
final RadioButton rd_add = (RadioButton) findViewById(R.id.add);

final RadioButton rd_sub = (RadioButton) findViewById(R.id.sub);

final RadioButton rd_mul = (RadioButton) findViewById(R.id.mul);

final RadioButton rd_div = (RadioButton) findViewById(R.id.div);

calculate.setOnClickListener(new View.OnClickListener() {

  public void onClick(View v) {

   if (!rd_add.isChecked() && !rd_sub.isChecked() && !rd_mul.isChecked()

    && !rd_div.isChecked())

    displayWarning();

   int num1 = Integer.parseInt(val1.getText().toString());

   int num2 = Integer.parseInt(val2.getText().toString());

   String str = "";

   if (rd_add.isChecked()) {

    str = String.valueOf(cal(num1, num2, 1));
   }

   if (rd_sub.isChecked()) {

    str = String.valueOf(cal(num1, num2, 2));
   }

   if (rd_mul.isChecked()) {

    str = String.valueOf(cal(num1, num2, 3));
   }

   if (rd_div.isChecked()) {

    str = String.valueOf(cal(num1, num2, 4));
   }

   result.setText(str);

  }

 }

);

}

private int cal(int val1, int val2, int ok) {

 int result = 0;

 switch (ok) {

  case 1:

   result = val1 + val2;
   break;

  case 2:

   result = val1 - val2;
   break;

  case 3:

   result = val1 * val2;
   break;

  case 4:

   result = val1 / val2;
   break;

  default:

   result = 0;
   break;

 }

 return result;

}

private void displayWarning() {

 AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

 dlgAlert.setMessage("Please choosing an operator!");

 dlgAlert.setTitle("My First App");

 dlgAlert.setPositiveButton("OK", null);

 dlgAlert.setCancelable(true);

 dlgAlert.create().show();

}
  • Run the app.
  • If you enter the first value and the second value but have not selected an operator yet, a message will occur:

Image title

Select the + operator:

Image title

Conclusion

In this article, I have introduced some basic concepts of how to create an Android application. I hope that this article is useful for beginners who are learning Android programming.

Topics:
android ,android studio ,mobile ,mobile app development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}