Main navigation

Tutorial 1 – How to make a basic Android App.

adsense

Pre-requisites:

1) Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
2) A real time android device (Smartphone or Tablet) configured with Android Studio. .
3) A basic knowledge of Android lifecycle and different classes & functions used in Android Studio.

Description of java file in Android App

In this post we will discuss the java file of our APP which is mainly responsible for all functionalities. XML was just used for layout and providing user interface but that layout won’t going to do anything if we do not include their functionality in java file.

We will also make a basic layout of our Millionaire App. Let’s dive into it.

Creating new project

Please follow following steps:

  1. Open Android Studio and make a new project with name “Millionaire App” and company domain application.example.com (I used my company domain i.e androidtutorialpoint.com. Similarly you can use yours).
  2. Click Next and choose android version Lollipop. Again Click Next and Choose Blank Activity.
  3. Now Following screen will appear. Here select Activity Name as MillionaireActivity. Click Finish.

tutorial_1_1

Now you can see MillionaireApp.java, content_main.xml and strings.xml. If you are not able to see them then click on the left window where these files can easily be located as shown in following figure:

tutorial_1_2

MillionaireApp.java:

package com.androidtutorialpoint.millionaireapp;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MillionaireActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_millionaire);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_millionaire, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Here AppCompatActivity is subclass of Android Activity that provides necessary support for the older versions. So for example, we are making this App on Lollipop version but to make it compatible with older versions like Eclairs, Icecream Sandwitch etc. AppCompatActivity is included.

After this we primarily come across three functions:

1) onCreate(): This function is called when a subclass of Activity is created. Bundle is passed as an argument to save details of the App when an instance get destroyed. (You can get more information about this here: ).
Super method is used to call the parent Constructor. Now to get the user interface we call:

public void setContentView(int layoutResID)

This function will instantiate each widget in the layout file as defined by its attributes. Here we specify which layout to make by passing in the layout resource id.
Note: In our case we are passing layoutResId as R.layout.content_millionaire where content_millionaire is the XML file where layout code is present.
Other attributes in OnCreate() are not used right now. So even if you remove them, they won’t going to hamper functionality.

2) onCreateOptionsMenu(): This is used to create Menu where you should place your items in to menu. So for example you want to create a list of 9-10 items then this function will come handy but in our App it won’t be used. So leave it for now.

3) onOptionsItemSelected(): This function is called whenever a particular item is selected from the above menu defined using onCreateOptionsMenu(). Item in the argument is the menu item selected. Leave it too for now.

I would suggest to go through our post for detailed explanation of Layout and Activity .

Now we will add a question and a four buttons through which you can choose correct option.For each button add an id so that we can define their functionality in Millionaire.java

strings.xml:

    
    <string name="app_name">Millionaire App</string>
    <string name="option_1">option_1</string>
    <string name="option_2">option_2</string>
    <string name="option_3">option_3</string>
    <string name="option_4">option_4</string>
    <string name="action_settings">Settings</string>
....

Make a basic layout of App. Here there will be four buttons and a question.

content_millionaire.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
                      android:layout_width="match_parent"
                      android:layout_height="match_parent"
                      android:gravity="center"
                      android:orientation="vertical">
              <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="24dp"
                android:text="Which is the biggest planet in our Solar System" />
              <LinearLayout 
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content" 
                android:orientation="horizontal">
                <Button
                    android:id="@+id/option_1"
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content" 
                    android:text="@string/option_1" 
                    android:layout_marginRight="50dp" />
                <Button 
                    android:id="@+id/option_2"
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content" 
                    android:text="@string/option_2" />
              </LinearLayout> 
              <LinearLayout 
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content" 
                android:orientation="horizontal"> 
                <Button 
                    android:id="@+id/option_3"
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content" 
                    android:text="@string/option_3" 
                    android:layout_marginRight="50dp"/> 
                <Button 
                    android:id="@+id/option_4"
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content" 
                    android:text="@string/option_4" />
            </LinearLayout>

            <Button
                android:id="@+id/next_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/next_button"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="30dp"/>
           </LinearLayout>

Note: There is + sign in the values for android:id but not for android:text because we are creating ids but only referencing strings.

MillionairActivity.java:

public class MillionaireActivity extends AppCompatActivity { 

        private Button mOption1Button; 
        private Button mOption2Button; 
        private Button mOption3Button; 
        private Button mOption4Button; 

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

Also import class android.widget.Button otherwise it will show error for Button.

Hack: You can also import corresponding file directly by pressing Alt+Enter. Android itself will take care of the file to be imported.

Now we have to make these buttons functional. For that, we will first get reference of these buttons in java file and then set events which will respond to it.

MillionaireActivity.java:

@Override 
        protected void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState); 
            setContentView(R.layout.content_millionaire); 
            mOption1Button = (Button) findViewById(R.id.option_1);            // Reference of the buttons
            mOption1Button.setOnClickListener(new View.OnClickListener() {   // Event is included
                @Override 
                public void onClick(View v) { 
                 // Code will be included here !! 
                } 
            }); 
            mOption2Button = (Button) findViewById(R.id.option_2); 
            mOption2Button.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View v) { 
                    // Code will be included here !! 
                } 
            }); 
            mOption3Button = (Button) findViewById(R.id.option_3); 
            mOption3Button.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View v) { 
                    // Code will be included here !! 
                } 
            }); 
            mOption4Button = (Button) findViewById(R.id.option_4); 
            mOption4Button.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View v) { 
                    // Code will be included here !! 
                } 
            });
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
            setSupportActionBar(toolbar); 
           ...
         }

findViewById() accepts resource id of a button and return a View Object which later can be drive. Also we have to cast View object to Button before using it in the code.

SetOnClickListener() will wait for button to be pressed and intercept it as soon as clicked. We can override inbuilt method onClick() to include some functionality.
Note: onClick() is called every time a user clicks this button. There are methods too which we can override according to our utility. You can get more info. Here

So finally basic App is almost built. We need to insert some logic in the onClick(). For now we will just print the message whether answer is correct or not. For that we will use Toast.
A toast is a message that informs user something but doesn’t require any input. It will be just popped up on the screen. To create a Toast we will call following function:

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

context is an instance of Activity (Activity is subclass of Context), resId is the resource id of the string to be displayed on screen and duration is the time for which message is to be shown.

MillionaireActivity.java:

 mOption1Button = (Button) findViewById(R.id.option_1); 
            mOption1Button.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View v) { 
                    Toast.makeText(MillionaireActivity.this,   // Add this code
                            R.string.incorrect_toast, 
                            Toast.LENGTH_SHORT).show(); 
                } 
            }); 
            mOption2Button = (Button) findViewById(R.id.option_2); 
            mOption2Button.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View v) { 
                    Toast.makeText(MillionaireActivity.this, 
                            R.string.incorrect_toast, 
                            Toast.LENGTH_SHORT).show(); 
                } 
            }); 
            mOption3Button = (Button) findViewById(R.id.option_3); 
            mOption3Button.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View v) { 
                    Toast.makeText(MillionaireActivity.this, 
                            R.string.correct_toast, 
                            Toast.LENGTH_SHORT).show(); 
                } 
            }); 
            mOption4Button = (Button) findViewById(R.id.option_4); 
            mOption4Button.setOnClickListener(new View.OnClickListener() { 
                @Override 
                public void onClick(View v) { 
                    Toast.makeText(MillionaireActivity.this,    
                            R.string.incorrect_toast, 
                            Toast.LENGTH_SHORT).show(); 
                } 
            }); 

It will show an error for Toast and incorrect_toast (They will marked as RED). Guess why is it?

Before using Toast we have to import android.widget.Toast but you can directly include corresponding widget using Alt+ENTER. Moreover, we have to define separate string ids for incorrect and correct Toast.

strings.xml:

    
    <string name="app_name">Millionaire App</string>
    <string name="option_1">option_1</string>
    <string name="option_2">option_2</string>
    <string name="option_3">option_3</string>
    <string name="option_4">option_4</string>
    <string name="invalid">This is first question. Cannot go back</string>
    <string name="next_button">Next</string>
    <string name="prev_button">Prev</string>
    <string name="correct_toast">Correct!</string>
    <string name="incorrect_toast">Incorrect!</string>
....

So our basic App is ready.There is one work remaining of how to connect and configure Android Device (Smartphone etc.) with Android Studio so that you can run this App on real time device. You can read my post on How to Connect and Configure App on Real Android device

Finally run this app on your Android Device. You will see following screen:

tutorial_1_3

Here a question is displayed and option_3 is correct. If you press wrong option then it will display “incorrect”. Kudos to you.



What’s Next

Now you can learn second part of this tutorial i.e. Android Tutorial 2 .
If you have any queries or suggestions then please comment. Don’t forget to subscribe. Also do Like our Facebook Page or Add us on Twitter

You can download this code here:

Android Tutorial Point Download Now


Reader Interactions

Comments

    • Hi Rita,

      You can see our tutorial on how to connect and configure android App on real time devices. Here: Connect and Configure Android devices.

      If still you are getting any error please let us know. Probably you need to update drivers. We will tell you that method. Before that go through above tutorial and let us know if it resolve your problem. Happy Coding 🙂

  1. hi navneet,
    thank you for the tutorial im not well experienced or pro coder.

    i have a request how should i write the code to this app if i have 15 question database.
    first question is randomly picked from lvl1 question list, 2 nd question rqndomly pîcked from question lvl 2 list 3rd from lvl3 list so on till lvl 15.

    i want to make gets harder questions the more you climb, and ill have around 50-100 questions for each level and one should be picked randomly by the app.

    how to code it to work that way?

  2. Hi!

    A have a problem downloading the code.
    I click on the button, I give my name and e-mail, I receive the email. After clicking the confirming link, I got that the page not found.

    What can be the problem?
    And how can I fix it?

Leave a Reply

Advertisment ad adsense adlogger