Android Studio is the most latest and powerful tool for developing android apps. In this tutorial, I will show you a simple math calculation example to make you understand the structure of android apps. In the Android Development Tutorial – part 1, I showed you how to make your first android project on android studio and what are the things you need to configure before start making your apps. I would ask you to see the previous part and make a new project with the required settings. As in this part I will start making a simple maths calculation app on the project I created in the previous part.
Android Development Tutorial
In our android applications, the UI is made with the help of different elements in XML (XML files are called layouts in android studio). And the back end logic of those UI elements is written in java files. When we create our project, an XML file and a java file is automatically created for us to start with. So, first of all we need to open the default xml file from the project on left side and shown in the image below.
In this XML file, the first thing we see is a “hello world” written by default at the top of our app (in the xml file that was created automatically). The XML we have by default contains the layout (relative layout), and a TextView within that layout as shown in the image below.
Note: You can switch between design and Text (XML) view from the bottom of the main window as shown in the image below.
In our case, we have clicked on Text tab to switch to the XML representation of our UI. If we click on Design tab, we will see the visual representation of this particular XML (called activity). Now we need to set the layout of our app first. So, first remove the whole textview tag (including its attributes) from that relation layout. After removing that textview, we will have an empty activity (having just a relative layout). There are many other layouts as well that we can also use, like a linear layout (which layouts its child elements vertically or horizontally). But for this particular part, we will go with default relative layout. Remember that we can have one layout inside another layout as well.
Now click on the Design tab as shown in the image above (for switching to the design view). In the design view we need to add an edit text element by dragging it from the tools bar and set the its width to 200dp as shown in the image below.
Note: We can also write px with the size, but using dp is more preferred because dp (density pixels) is used to set the size that works perfectly for all the screen sizes.
If you now click on the Text tab from the bottom, you will see that the XML would be changed as an element “edittext” will be added as child of relative layout. You can write XML directly (which is recommended in case of complex layouts) but I have just added it directly by dragging it from tools bar. I can edit the properties of this edit text from the properties explorer on the right side as shown in the image above (where I edited the width). But now I will show you how to edit the properties by switching to the XML (Text) view. Now in the XML, I have added two new height and background attributes to edit text as shown in the image below.
The main attribute here is id (which we write almost for every element we write in XML). Id is used to uniquely identify an element in java file and to layout different elements in relative panel which I am going to show you just. Now copy this whole EditText element and paste it just below this EditText. You need to change and add few more attributes to the second EditText attribute as shown in the image below.
In the above image, I have changed the id name (as id should be unique for all the elements). Layout below shows that this element will be below the editText (which is the id of first EditText). Lastly, set the margin top to 12dp to keep it at distance from the first EditText. These two edit texts are used to let user enter two decimal values only (not alphabets). But these elements will also allow alphabets unless we add a new attribute on both EditText elements. So add an attribute shown below, on both the elements.
android:inputType="number"
After adding the above attribute, both EditText’s will only allow numbers to enter in it. Now if you click on design tab and see the UI, it should look like the image shown below.
Now we need to add four radio buttons for user to select the operator for applying it on values of above two edit texts. I hope that all of know that how to add an element in XML and within relative panel. So there is a RadioButton element in XML that we can use to add radio buttons. We have to make sure that user should select at most one radio button for operation. There is another element called RadioGroup that we use as a parent of all RadioButtons. There are bunch of element’s attributes that we can use for designing, positioning and for many other purposes. You need to explore them yourself in order to understand them in depth. But most of the attributes are self explanatory that we can directly use them inside the elements. Now I have added a RadioGroup just below the two EditTexts but inside the relative panel.
<RadioGroup
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="@+id/editText2"
android:checkedButton="@+id/add"
android:id="@+id/radioGroup"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_marginLeft="20dp"
android:id="@+id/add" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:layout_marginLeft="20dp"
android:id="@+id/sub" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*"
android:layout_marginLeft="20dp"
android:id="@+id/mul" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:layout_marginLeft="20dp"
android:id="@+id/div" />
</RadioGroup>
As we are making a simple maths calculations app, we need to have a text block in order to show the result of operation. For this case we will not use EditText because we don’t want to user to change the result by editing it, but we just want to show the result. So, to do that there is another element called TextView in XML. So, we have to add a TextView just below the RadioGroup and the code you have to use in given below.
<TextView
android:layout_width="200dp"
android:layout_height="50dp"
android:id="@+id/resultText"
android:textSize="20dp"
android:layout_below="@+id/radioGroup"
android:layout_centerHorizontal="true"
android:background="#f5ffb3" />
Now if we see the design view, we should see some thing like this.
So, we are just left with one element that is a button. User must have to press the button in order the get the result of calculation. So, we will add our button just below the TextView and before moving further we have to set the string text for that button. If you go to your Project’s res folder, inside it there is a folder called values that contain strings.xml file. If you open that file, there will be some string tag already written, we have to add a new one for our button as shown in the image below.
Now save this file and come back to previous activity_main.xml file. Add a new button just below the TextView as code given below.
<Button
android:layout_width="120dp"
android:layout_height="40dp"
android:text="@string/ok_button"
android:layout_marginTop="20dp"
android:id="@+id/button"
android:layout_below="@+id/resultText"
android:layout_centerHorizontal="true" />
In the above code, the most important thing to see is text of the button. If you see the design view, a text Done will be written on the button but I have written “@string/ok_button” in double quotes. Here I am referring to the string tag that we just defined in strings.xml file. Using the name of that string tag, I have shown the content what that tag contains. I could write text “Done” directly within quotes but this is the preferred way of adding texts to the elements of xml. The benefit of this is when you have too many elements having same text, we define string text in strings.xml and then get its content to use it in our elements. When ever we have to change the text, we just need to change that tag’s content rather than changing the text of all the elements.
Make sure you save your all files that you have edited. Now we have to write some java code now to make the xml elements work. I assume that you already know basic java concepts that will be helpful to write code in android. So, we have our UI in the default file layout_main.xml that was generated by android studio for us. Android Studio have also generated a file called MainActivity.java by default to write java code. You can find this file from project folder > java > com.mycompany.www.first > MainActivity.java as shown in the image below.
Inside this file, there is a few lines code already written for us to start with. At the top, there is a package name and some import files. After that we have a class called MainActivity that extends AppCompatActivity class to inherit its features. Within this class, there are 2 3 methods by default but the most important for now is onCreate method. We can’t change the name of this method and this method automatically called when our activity is first created (see the activity life cycle HERE). Within this method, we are calling the parent’s onCreate method to save the InstanceState. After that, we have to set the content view of our XML activity_main.xml file that this java code belongs to which XML file as as shown in the image below.
Note: We can have more than one java files of one xml file.
Now we have set the content view of our xml file to MainActivity.java file. We have to get the reference of our UI elements that we added in activity_main.xml. To do that, first we have to declare the variables of the same type as our UI elements. Within the MainActivity class but outside (or above) the onCreate method, write the code given below.
EditText editText1, editText2; RadioButton add,sub,mul,div; TextView tv; Button btn;
We have declared our variables and now we have to get the reference of UI elements in these variables. Within the onCreate method and below the setContentView, add the the code given below.
editText1=(EditText) findViewById(R.id.editText); editText2=(EditText) findViewById(R.id.editText2); add=(RadioButton) findViewById(R.id.add); sub=(RadioButton) findViewById(R.id.sub); mul=(RadioButton) findViewById(R.id.mul); div=(RadioButton) findViewById(R.id.div); tv=(TextView) findViewById(R.id.resultText); btn=(Button) findViewById(R.id.button);
Now that you have got the references of all the elements in java file. Now we can apply different operation on these values. I will do basic math calculations on edit texts bases on which radio button was checked. This is based on a simple conditional logic which I am not going to explain here. People who have basic knowledge of programming would understand it. One thing I want to explain it here is the button event listener that has to be added on button when use will touch it. I am going to show you a complete code including event listener and whole logic of this application. You need to add this code just below the code where we added the reference of XML elements to java variables (or below the above code).
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((!editText1.getText().toString().equals("")) &&
(!editText2.getText().toString().equals("")))
{
int num1 = Integer.parseInt(editText1.getText().toString());
int num2 = Integer.parseInt(editText2.getText().toString());
int result;
if (add.isChecked()) {
result=num1+num2;
tv.setText(String.valueOf(result));
}
if (div.isChecked()) {
result=num1/num2;
tv.setText(String.valueOf(result));
}
if (mul.isChecked()) {
result=num1*num2;
tv.setText(String.valueOf(result));
}
if (sub.isChecked()) {
result=num1-num2;
tv.setText(String.valueOf(result));
}
}
else
{
Toast.makeText(getApplicationContext(),"Input Values should not be empty",Toast.LENGTH_SHORT).show();
}
}
});
In the above code, the line written in else condition, executes when any of the edit text field is empty. And this line will show a pop up message with the text written in double quotes. We have completed our app and now I will show you how to run your application. If you have android phone you can test your application on the phone by plugging it to your PC. Make sure you enable the debugging mode in developers options in the settings of your phone. If you don’t have phone then you can test you application on an android emulator (which is a bit slow). So, to test this app on an emulator, you first need to click on play button at the top tool bar as shown in the image below.
After clicking play button, it will open a new dialog to let you select a phone or an emulator. At the top, the gird shows the available devices for you to select in order to run your app on. The nexus 5 shown in the grid is visible because I have attached my nexus phone with my PC. If you don’t have any running device visible in the grid, then click on Launch emulator below and select the available emulators from the drop down. If you want to create your own emulator (with your our settings), you can click on browse emulator’s button and then click Create new emulator from the new window open. I have selected an emulator to show and clicked OK to show the running app on it as shown below.
So, you can see the app running on the emulator above. I hope that up till now you understand every thing about events, java coding and xml layouts. But I don’t want to end this tutorial here, because there is another very important and basic thing that I want you learn as well. I would like to show to how to add another start up screen (activity) for our app. To do that we must have another XML file same as activity_main.xml. In order to add another new xml file, go to app project > res > layout. Right click on layout > New > layout resource file, it will open a new window as shown in the image below.
Set the name of file as startup (not is upper case), match other values as well and click OK. It will create a new xml file (with name startup.xml) under the layout folder. Now you need to add a button on this activity to move the next activity when user clicks on that button. In order to do that, open the text (xml) view of startup.xml file and change the file same as shown in the image below.
Now we have set our layout as we wanted. Now we need to have the java file for this activity. To do that, go to the app project > java and right click on com.mycompany.www.first > New > java class. It will ask you to enter the class name, give it a name StartUpActivity (without java extension) and click OK. A new java file will be created with a class in it. We need to make that similar to the default MainAcitivity.java file when that was first created. So, change the StartUpActivity java class same as shown in the image below.
You can see in the above image that I have set the content view to startup xml file because this java file belongs to that startup.xml file. Same as in previous java file, we want to get the reference of button element from the xml file and set the on click listener to that button. When the user clicks on that button, second activity should start. To do that, change your StartUpActivity class to the code given below.
Button btn;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.startup);
btn=(Button) findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(StartUpActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
In the above code, Intent is used which is basically used to move from one activity to other activities, communication among different activities, passing parameters to other activities and much more (you can read more on Intents). Another we want to add in this java file is when user navigate to second activity, it should not move back to previous activity again (by pressing device back button). To do that we need to add another builtin method called onPause, just below the onCreate method. The reason is that when an activity resumes on any other activity, previous activity goes on the stack (or paused) but not destroyed. In order to destroy that, we need to do that manually inside its onPause method (read more on activity life cycle). So, add the give code below, just after the onCreate method.
@Override
protected void onPause() {
super.onPause();
finish();
}
So, now we have set up our second startup activity but when we will run our app, this activity will not be shown. The reason is that, we have to tell android engine which activity should it open first. To do that, go to app folder > manifests and open AndroidManifest.xml file in it. This file is used for the settings, permissions etc. of your applications. In this file, you will see an activity tag inside the application tag. This activity element defines the MainActivity only and we have to make a new activity element here for our StartUpActivity. What I will do first is change the already written activity element enabled for StartUpActiviy. To do that, change the name attribute of this activity to one shown below.
android:name=".StartUpActivity"
This activity is registered for our StartUpActivity now, because of the action and category element’s name attributes values inside the intent filters. Now we need to make a new activity for our MainActivity. To do that, just add a new activity element below the previous activity element as given below.
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.mycompany.www.first.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I have set the name of this activity to MainActivity, changed the action name to MainActivity and changed the catagory name to default. Now if I save and run this project, it will show a startup screen with a button on it. And when I will touch that button, it will take me to the actual MainActivity and destroy the startup activity because of the finish method inside onPause method in StartUpActivity.java file. The visual example of our application is shown below.
So, we are done with this basic but important tutorial on android studio. I hope that you have learned how to add elements, setting up layout, add a java code on those elements, setting up listeners, toasts and setting up more than one activities. There are some more important elements that you must know and I would strongly recommend you to read List Controls in Android. If you have any question or facing any problem, just comment below this post. Stay in touch with my blog as I will be posting more on android development using android studio. Thank you 🙂

















