Building an Android app — From scratch to pro! [1]

Basu
17 min readJun 13, 2020

Do you really need to be like this to create a mobile app?

Photo by Max Duzij on Unsplash

Maybe. Or you can simply start a reinforcement learning for you.

Let me tell you how I learnt Android. One fine day when my brother called me up asking if I know how to create a mobile app because he needed a project for his college and he was too much involved in his internship at that time and needed some help. Everyone in the family believes I know many things in computer and technology ( :P ). While I was still in grade 10th at that time, it was true for many things but Android. I couldn’t help but say ‘YES’ to him. The very next moment I got off the phone call, I started the search on StackOverflow for different things about Android like how to add button, how to add dropdown, how to add pages and interact with a server.

So basically, I didn’t start from the base. I converted each step in making an Android app a problem and searched solutions for that problem while encountering several bugs and fixing them.

So, through this article, I hope to spark a curiosity in you for making mobile apps and give you a headstart in this development process.

What you will learn:

  1. Creating UI for the Android [Part 1]
  2. Creating backend of your app [Part 1]
  3. Notification and extra features for your app [Part 2]
  4. Building server-side with REST APIs [Part 2]
  5. Packaging and publishing the app [Part 2]

The article is divide into 2 parts. Link to the second part is available at the end of this article.

Let’s get started.

Prequistics (Link attached with each resource):

Note: You can download and signup up right away or just move along the article.

  1. Android Studio [Download]
  2. Basic Knowledge of Java (Objects, Loops, Conditional Statements etc.), XML, Php [Learn]
  3. Azure Account [Signup]
  4. Firebase Account [Signup]
  5. Google Play Account (If you want to publish your app) [Signup]

Let’s get started:

Downloading and Installing: Download and install Android Studio. Use default settings everywhere asked.

Important links:

The Official Guide to installing Android Studio.

Developer Workflow Basic

Terms:

  1. Activity: Think of it as a page for your android app. Whenever you interact with an app, you are seeing its activity (page). You move to the next page means you are going to the next activity. Every activity has two component. The front end: XML code and the backend: Java code. In simple words, your body is an XML while your brain is Java. In the XML code, you define your UI- the buttons, colours, layout, list. In your Java, you define what happens when you click a button or how to connect to your server.
  2. Fragment: Through this feature, you can add multiple pages inside the same activity. Each page will have its own backend code. For example, let’s say you have an app with two pages (activities). One page displays weather and a button for going to the next page which shows the local time. Now when you click on that button, Android OS will create a new activity with your code. But if you are using Fragment, the activity will remain the same but the fragment (page) will change. What’s the benefit? Each time an activity is created for viewing and interacting, Android has to do a lot of work which might take an only negligible amount of seconds but imagine an app that needs 80 different pages/ activities. What will you do? You will use Fragments. Fragments are like reusable content of Android OS.

After installing successfully, open Android Studio.

Creating a new project: Click “Start a new Android Studio Project”.

Choose Basic Activity. Android will automatically add a basic activity page (XML) and its Java Code. Here is the full explanation of each activity. Please remember this is just a template. You can go on with No Activity, create an XML and Java file, write your code, connect both XML and Java and Voila, you have your own template. :)

Configure your project: The next step is to configure some settings and create your new project, as described below and shown in the figure.

  1. Specify the Name of your project.
  2. Specify the Package name. By default, this package name also becomes your application ID, which you can change later.
  3. Specify the Save location where you want to locally store your project.
  4. Select the Language you want Android Studio to use when creating a sample code for your new project. Keep in mind, you are not limited to using only that language creating the project. I’m using Java.
  5. Select the Minimum API level you want your app to support. When you select a lower API level, your app can rely on fewer modern Android APIs. However, a larger percentage of Android devices are able to run your app. The opposite is true when selecting a higher API level. If you want to see more data to help you decide, click Help me choose.
  6. If you want your project to use AndroidX libraries by default, which are improved replacements of the Android Support libraries, check the box next to Use AndroidX artifacts. To learn more, read the AndroidX overview.
  7. When you’re ready to create your project, click Finish.

Understanding your baby Android Studio IDE:

First, be sure the Project window is open (select View > Tool Windows > Project) and the Android view is selected from the drop-down list at the top of that window. You can then see the following files in the image above:

app > java > com.example.myfirstapp > MainActivity This is the main activity. It’s the entry point for your app. When you build and run your app, the system launches an instance of this Activity and loads its layout.app > res > layout > activity_main.xml This XML file defines the layout for the activity's user interface (UI). It contains a TextView element with the text "Hello, World!"app > manifests > AndroidManifest.xml The manifest file describes the fundamental characteristics of the app and defines each of its components.Gradle Scripts > build.gradle There are two files with this name: one for the project, "Project: My First App," and one for the app module, "Module: app." Each module has its own build.gradle file, but this project currently has just one module. Use each module's build.file to control how the Gradle plugin builds your app.

This is another view of the structure. You can select this view by selecting Project from the dropdown at the top of the Project window. When you select Project view, you can see a lot more files and directories. The most important of which are the following:

module-name/build/ Contains build outputs.libs/ Contains private libraries.src/ Contains all code and resource files for the module in the following subdirectories:androidTest/ Contains code for instrumentation tests that run on an Android device. For more information, see the Android Test documentation.main/ Contains the "main" sourceset files: the Android code and resources shared by all build variants (files for other build variants reside in sibling directories, such as src/debug/ for the debug build type).AndroidManifest.xml Describes the nature of the application and each of its components. For more information, see the AndroidManifest.xml documentation.java/ Contains Java code sources.jni/ Contains native code using the Java Native Interface (JNI). For more information, see the Android NDK documentation.gen/ Contains the Java files generated by Android Studio, such as your R.java file and interfaces created from AIDL files.res/ Contains application resources, such as drawable files (images), layout files, and UI string. See Application Resources for more information.assets/ Contains file that should be compiled into an .apk file as-is. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager . For example, this is a good location for textures and game data.test/ Contains code for local tests that run on your host JVM.build.gradle (module) This defines the module-specific build configurations.build.gradle (project) This defines your build configuration that apply to all modules. This file is integral to the project, so you should maintain them in revision control with all other source code.

Running your app:

  1. Run on a real device:
Set up your device as follows:-Connect your device to your development machine with a USB cable. If you developed on Windows, you might need to install the appropriate USB driver for your device.-Perform the following steps to enable USB debugging in the Developer options window:
1. Open the Settings app.
2. If your device uses Android v8.0 or higher, select System. Otherwise, proceed to the next step.
3. Scroll to the bottom and select About phone.
4. Scroll to the bottom and tap Build number seven times.
5. Return to the previous screen, scroll to the bottom, and tap Developer options.
6. In the Developer options window, scroll down to find and enable USB debugging.
Run the app on your device as follows:1. In Android Studio, select your app from the run/debug configurations drop-down menu in the toolbar.
2. In the toolbar, select the device that you want to run your app on from the target device drop-down menu.
Click Run (The play icon)Android Studio installs your app on your connected device and starts it.

2. Run on an emulator

In Android Studio, create an Android Virtual Device (AVD) that the emulator can use to install and run your app.1. Open the AVD Manager by clicking Tools > AVD Manager.
2. Click Create Virtual Device, at the bottom of the AVD Manager dialog. The Select Hardware page appears.
3. Select a hardware profile, and then click Next. If you don't see the hardware profile you want, you can create or import a hardware profile.
4. Select the system image for a particular API level, and then click Next.
5. Change AVD properties as needed, and then click Finish
Run the app on your device as follows:1. In Android Studio, select your app from the run/debug configurations drop-down menu in the toolbar.
2. In the toolbar, select the device that you want to run your app on from the target device drop-down menu.
Click Run (The play icon)Android Studio installs your app on your connected device and starts it.
  1. Developing XML Files (Frontend):
Design View

Click and open activity_main.xml file. This is the default view when you open an XML file. You can add elements (layout, button, image, text etc) to your activity (front end page) by either drag and drop or by writing XML blocks (manual coding).

  1. Palette: Contains various views and view groups that you can drag into your layout.
  2. Component Tree: Shows the hierarchy of components in your layout.
  3. Toolbar: Click these buttons to configure your layout appearance in the editor and change layout attributes.
  4. Design editor: Edit your layout in Design view, Blueprint view, or both.
  5. Attributes: Controls for the selected view’s attributes.
  6. View mode: View your layout in either Code code mode icon, Design design mode icon, or Split split mode icon modes. Split mode shows both the Code and Design windows at the same time.
  7. Zoom and pan controls: Control the preview size and position within the editor.

When you open an XML layout file, the design editor opens by default, as shown in the figure. To edit the layout XML in the text editor, click the Code

button in the top-right corner of the window. Note that the Palette, Component Tree, and Attributes windows are not available while editing your layout in Code view.

To add elements manually, open the code viewer of the Activity file (XML file). Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.

Tip: You can switch between design and text editors by pressing Alt + Shift + Right/Left arrow (Control + Shift + Right/Left arrow on Mac).

Layouts: A layout defines the structure for a user interface in your app, such as in an activity. All elements in the layout are built using a hierarchy of View and ViewGroup objects. A View usually draws something the user can see and interact with. Whereas a ViewGroup is an invisible container that defines the layout structure for View and other ViewGroup objects, as shown in the figure.

Sample code: Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you’ve defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. For example, here’s an XML layout that uses a vertical LinearLayout (ViewGroup) to hold a TextView (View) and a Button (View):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>

Attributes:

android:layout_width = The Width of the element
android:layout_height = The height of the element
match_parent = fit the size to parent's size
wrap_content = fit as much as needed
Example: If we add an image, we can set its width to match parent so that it covers the width, but for height we can set it to like 200 dp. (Click here for size measurement scale dp, sp and others).
Other link.
REMEMBER: When you start a new xml activity file, it might already contains: <ConstraintLayout>
or
<androidx.constraintlayout.widget.ConstraintLayout>
This is a ViewGroup same as LinearLayout. You can use either one and combination of both. Please refer to official documentation here. ConstraintLayout and LinearLayout

Here is an official link by Android to create layouts.

Now, on your own, try to add a button and some elements to it. Try playing with different attributes with the element. Example here.

RUN YOUR APP and see how is it working.

Attributes of an element
  1. The Declared Attributes section lists attributes specified in the layout file. To add an attribute, click the Add add attribute button button at the top right of the section.
  2. The Layout section contains controls for the width and height of the view. If the view is in a ConstraintLayout, this section also shows constraint bias and lists the constraints that the view uses. For more information on working with ConstraintLayout, see Build a Responsive UI with ConstraintLayout.
  3. The Common Attributes section lists common attributes for the selected view. To see all available attributes, expand the All Attributes section at the bottom of the window.
  4. Click the Search button to search for a specific view attribute.
  5. The icons to the right of each attribute value indicate whether the attribute values are resource references. These indicators are solid solid indicator icon when the value is a resource reference and empty empty indicator icon when the value is hard-coded. These indicators help you recognize hard-coded values at a glance. Clicking indicators in either state opens the Resources dialog window where you can select a resource reference for the corresponding attribute.
  6. A red highlight around an attribute value indicates an error with the value. An error might indicate an invalid entry for a layout-defining attribute, as shown in the red highlight in figure

NOTE: All edits to the XML file and JAVA file are saved automatically. No need for CTRL+S or CMD+S. But be sure to not force shut down your computer because it might sometimes let Android studio to not save the files.

2. Developing Java Files (Backend):

Points to note: 
1. I’m assuming you are aware with Java programming language.
2. All activity's Java file extends AppCompatActivity
3. The onCreate method of AppCompatActivity is called whenever the activity is created.
Activity have different default methods that correspond to different activity lifecycle starts. Example: onCreate() is called whenever activity is created. onStart() is called whenever activity is starting.

Activity lifecycle:

Read about different lifecycle here.

Your activity’s Java file code:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Connect xml layout
}
}

How can you connect your element from XML to Java? Through unique ID.

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/cancel”
android:text=”Cancel”
android:textSize=”16sp”
android:textStyle=”bold”
android:textColor=”@color/white
app:backgroundTint=”@color/blue_grey
android:layout_gravity=”end”
android:layout_toStartOf=”@+id/submit”
android:layout_toLeftOf=”@+id/submit”
android:textAllCaps=”false”/>
Here's android:id="@+id/cancel" set this button an unique ID "cancel". You can refer to this button using this ID. Each XML files must have unique ID for each elements in it. For different XML files, you can have same unique ID in different files. P.S: You can also check other attributes added to this button. For little fun, try to figure out the meaning of the attributes yourself or google it.

Java code:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Connect xml layout
Button myButton = findViewById(R.id.cancel);
}
}
Here findViewById finds the view in XML file by their Unique ID. We always needs to write R.id.XXXX in the findViewById parameter (XXXX is your Unique ID). After this, we can do operation on the button (like setting click listener or setting visibility) using the object "myButton".

Now, how to control the button? Let’s show a Toast message when the user clicks the button by adding a click listener on the button.

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Connect xml layout
Button myButton = findViewById(R.id.cancel);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "This is my first android app.", Toast.LENGTH_SHORT).show();
}
});
}
}
RUN YOUR APP and see how is it working.Here we set a click listener on our button so that whenever our button is clicked, the code inside the onClick() function will be executed. Inside onClick(), we used the Toast class to show Toast message. Toast.LENGTH_SHORT = The duration of the toast. You can set it to your number.getApplicationContext() = You will be using this thing all over your app. See below for short summary.

Context (According to Android): Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc. The Context in Android is actually the context of what we are talking about and where we are currently present.

Few important points about the context:

  1. It is the context of the current state of the application.
  2. It can be used to get information regarding the activity and application.
  3. It can be used to get access to resources, databases, and shared preferences, and etc.
  4. Both the Activity and Application classes extend the Context class.

Here’s a good article about Context. There are different way to get context — getApplicationContext(), this, MainActivity.this.

Moving from one activity to another. Now, let’s try to make another activity and we will go to the second activity and then come back to the main activity.

Click “layout” on your project structure. Right click-> New-> Activity-> Basic Activity. Fill out the details as you did at the beginning. Let’s say your second activity’s name is ‘SecondActivity’.

Now, in your MainActivity. java file, add this code:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Connect xml layout
Button myButton = findViewById(R.id.cancel);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
}
}
Intent: An intent is an abstract description of an operation to be performed. It can be used with Context#startActivity(Intent) to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and Context.startService(Intent) or Context.bindService(Intent, ServiceConnection, int) to communicate with a background Service.startActivity(): A method of Android to start another activity.RUN YOUR APP and see how is it working. You should now be able to move between activity.

Now, try to create multiple activities and move between them. Add images, button, set background colour and more.

BONUS:

  1. Different functions in AppCompactActvity (Some are called by the Android system, some you call)
1.
@Override

public boolean onSupportNavigateUp() {

}
This function is called whenever the activity's back button (situated on top left) is clicked (not the phone's back button). If you can't see the back button in your activity, add this code to your onCreate() after setContentView().
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
After, this you can see the back button on your activity.
2.
@Override
public void onBackPressed(){
super.onBackPressed();
}
This function is called whenever the phone's back button is called.
3.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
YOU CALL this function whenever you need to add a menu in your app. The popup menu.
4.
@Override
public boolean onOptionsItemSelected(MenuItem item) {

}
This function is called if you have a menu and an item is clicked. Again, each item is identified by an Unique ID.
5.
finish()
YOU CALL this function whenever you want to close your activity programatically.

2. Some classes to read about

RecyclerView: If your app needs to display a scrolling list of elements based on large data sets (or data that frequently changes), you should use RecyclerView as described on this page.CardView: An easy way for you show information inside cards that have a consistent look across the platformNotification: A notification is a message that Android displays outside your app's UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.Menu: Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, you should use the Menu APIs to present user actions and other options in your activities.WebView: If you want to deliver a web application (or just a web page) as a part of a client application, you can do it using WebView.SharedPreferences:  A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them.Room: Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

3. Some how-to tutorial and recommended reading

Style and Theme: Styles and themes on Android allow you to separate the details of your app design from the UI structure and behavior, similar to stylesheets in web design.Material Design: Material design is a comprehensive guide for visual, motion, and interaction design across platforms and devices.Fragments:  You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.Principal of navigation: The following principles set a baseline for a consistent and intuitive user experience across appsTabLayout: Swipe views allow you to navigate between sibling screens, such as tabs, with a horizontal finger gesture, or swipe

4. Some websites to learn Android programming

1. Android Developers
2.
Simplified Coding
3.
Android Hive
4.
Tutorials Point
5.
Udemy
6.
Coursera
7.
Udacity
8.
hackr.io

5. A good Spotify playlist to listen to while you code

1. Good Vibes
2.
Beast Mode
3.
Gaming Unleashed
4.
Adrenaline Rush
This one is mine: Nirvana

Endnote: Remember, when you are creating an activity, you might see an option “Launcher Activity”, when selected, the activity will become the default launcher activity that is, it will be this activity which will be launched when you open the app. If you have multiple activities selected as launcher activity, you might get an error saying default activity not selected. You can edit this in Manifest.

I tried to make this article as simple as I can and I hope you are now expanding your Android knowledge on your own and digging new stuff.

Link to part 2: Building an Android app — From scratch to pro! [2]

Thank you for taking out the time to read this article. Please feel free to connect with me anytime if you need any help in Android development.

Cheers!

Basu

--

--