Set Up a Default Activity for an Android Application in Android Studio
Learning Android Application Development from scratch can be tricky sometimes for a newbie like myself. I am assuming that you are equipped with a complete Android Studio setup and have a fair idea about Android Activity and Markup language.
Let us create a Android Project with Empty Activity and follow the process. On completion, we are presented with two files:
1. MainActivity.java (Red box in Fig 1)
2. activity_main.xml (Green box in Fig 1)
Just for curiosity, we delete both the files from the project folder, and now the project is broken.
Through this post, we’ll try to fix what’s broken and set up a new default activity without starting from scratch.
Before we go into the actual process of setting up the default activity, let’s look at how we can create an activity. It can either be created from the File tab section (purple box on the top left of Fig 1) or Project Manager window (blue box, i.e., the leftmost window of Fig 1). Given below are the two ways to create a new activity:
- Go to File tab > New > Activity > Empty Activity
- Right Click on App module > New > Activity > Empty Activity
We will work with Empty Activity(named New Main Activity) in this post.
Once an Activity is selected, a new window will pop up, asking us to Configure the Activity we have chosen previously. Fill up the details as required and do check the check-boxes saying Generate a Layout File and Launcher Activity (Fig 3).
If everything is done correctly, the app will build successfully & run without any errors. We can go back to building our cool application. (Fig 4)
Otherwise, if the check-boxes are left unchecked (Fig 5), the new activity will be generated. But it won’t run because Default Activity is not set (Fig 6).
We will first create a layout file and then update the Android Manifest file to fix this issue.
Step 1: Create a layout file
To create a layout file go to File > New > XML > Layout XML File (Fig 7.1)
In the layout configuration window, the Root Tag field can be filled as Linear Layout, Relative Layout, etc. (Root Tag can also be changed later)
Step 2: Configure Android Manifest file
To open the Android Manifest file go to the Project Manager window (brown box in Fig 1) and follow the file hierarchy (Fig 8):
App > manifests > AndroidManifest.xml
In the XML file you will see activity tag (Fig 9):
<activity android:name= ”.NewMainActivity”></activity>
If there is no code within the activity tag that means that particular activity (.NewMainActivity in our case) is not set as Default Activity.
Add the following markup code within the activity tag to make it a Default Activity (Fig 10):
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
Now, build the application and run it. It will run successfully (Fig 11).