Development of mobile applications for a platform Android always begins with an understanding of the fundamental building blocks. One of these key elements is Activity, which is a separate screen with a user interface. Without the ability to correctly create and configure these components, it is impossible to build even the most primitive application, be it a calculator or a complex social network.

In the development environment Android Studio the process of creating an activity is automated to the limit, but it is important for beginners to understand what happens โ€œunder the hoodโ€ when you press a couple of buttons. You should be aware of the difference between the visual part (.xml) and the logical part (.java or .kt), and how the system ties them together through the manifest.

This guide will walk you through all the steps, from creating a new project to setting up the component lifecycle. We'll break down the nuances that are often missed in superficial tutorials, and give recommendations that will save you hours of debugging in the future.

Preparing the environment and creating a new project

Before you start coding, you need to make sure that your development environment is configured correctly. Run Android Studio and select the option to create a new project. At this stage, the wizard will ask you to choose a template, and this is where the first critical mistake of beginners is made.

For pure learning, it is recommended to choose a template Empty Activity. This option provides the minimum required set of files without overloading the project with unnecessary fragments or navigation components that can be confusing at the start. You can add everything you need yourself as you study.

In the project configuration window, pay special attention to choosing a programming language. Today, the industry is actively migrating to Kotlin, which is the preferred language for Android development. While Java is still supported, new API features are often targeted specifically at Kotlin syntax.

It is also important to specify the minimum SDK version (Minimum SDK). Choosing a version that is too old will limit access to modern APIs, while choosing a version that is too new will reduce the audience of your application. It is usually recommended to choose the version that is used by more than 90% of active devices at the moment.

๐Ÿ“Š What programming language are you planning to use to learn Android?
Java
Kotlin
Dart (Flutter)
C# (Xamarin)
Other

Activity file architecture and life cycle

After generating the project, you will see the main activity class in the file structure window. This is a regular class that inherits from the base class AppCompatActivity. This is where all the logic of the screen will be contained: processing clicks, loading data and interacting with other components.

The key method in this class is onCreate(). It is called by the system once when an activity is created and serves as the entry point for initializing the interface. Inside this method there must be a line setContentView()that associates the class with XML markup.

In addition to onCreate, there are several more lifecycle methods that need to be understood. The system calls them at a certain point in time, allowing you to control the state of the application:

  • ๐ŸŽฌ onStart() โ€”the activity becomes visible to the user, but is not yet interactive.
  • โ–ถ๏ธ onResume() โ€”the activity moves to the foreground and is ready for interaction with the user.
  • โธ๏ธ onPause() โ€”the activity loses focus, but is still partially visible (for example, a dialog box is open on top of it).
  • โน๏ธ onStop() โ€”the activity is completely hidden and is no longer visible to the user.

Correct use of these methods allows you to avoid memory leaks and ensure smooth operation of the application when rotating the screen or switching between tasks. Ignoring the lifecycle is the most common cause of crashes for inexperienced developers.

๐Ÿ’ก

Always call the superclass implementation (super.onCreate) at the very beginning of the onCreate method, otherwise the application will crash at startup.

Working with layouts and interface binding

The visual part of the activity is stored in the resource folder res/layout. A markup file, commonly called activity_main.xmldescribes the layout of buttons, text fields, and images on the screen. Android Studio provides a visual editor Layout Inspector, but professionals prefer to work directly with the XML code.

To display this layout in an activity, the setContentView(R.layout.activity_main)method is used. Here R.layout is an automatically generated class containing links to all resources of your project. If you change the name of the XML file, be sure to update the reference in the code, otherwise you will get a compilation error.

Modern versions of Android development increasingly use the View Binding or Jetpack Composeapproach. View Binding allows you to access interface elements directly through code without using a method findViewById, which makes the code safer and more readable.

โš ๏ธ Attention: Never create new Activity instances manually through the operator new. Activities are managed exclusively by the Android system through context and intents. Trying to create an activity as a normal object will result in unpredictable behavior and application crash.

When working with different screen sizes, it is recommended to create alternative layouts. You can create a folder layout-land for landscape orientation or layout-sw600dp for tablets. The system will automatically select the required markup file depending on the device configuration.

โ˜‘๏ธ Check before launch

Done: 0 / 4

Registration in AndroidManifest.xml

Every activity of your application must be registered in a manifest file. This is a kind of passport of the application, where the system learns about the existence of all its components. If you forget to add an activity entry, the system simply will not be able to launch it, even if the code is written perfectly.

Open the file AndroidManifest.xml in the folder manifests. You will see a tag <application>, inside of which there should be tags <activity>. For the main activity, which is launched first when you click on the icon, it is necessary to have a special intent filter.

An example of correct registration of the main activity is as follows:

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

The attribute android:name indicates the full path to the activity class. If you are creating a second, third or tenth activity, you just need to add a new tag <activity> for each of them, but without a block intent-filterif they should not be launched directly from the outside.

Attribute Description Required
android:name Activity class name Yes
android:label Title displayed in the top panel No
android:theme Design style (light/dark theme) No
android:screenOrientation Fixing screen orientation (portrait/landscape) No

Sometimes when refactoring code (renaming packages or classes), Android Studio may forget to update the manifest. Always check this file manually after major changes to the project structure to avoid errors ActivityNotFoundException.

Creating a single screen is only half the battle. Real applications consist of many activities between which the user moves freely. To move from one screen to another, the mechanism Intents (intentions) is used.

Explicit intent is used when you know exactly which activity class you need to go to. This is a standard navigation scenario within your application. The code for the transition looks concise and understandable:

val intent = Intent(this, SecondActivity::class.java)

startActivity(intent)

Often there is a need to transfer data from one screen to another, for example, a user name or product ID. To do this, extrasโ€”key-value pairsโ€”are added to the object. The receiving side retrieves this data in the method Intent extras are added - key-value pairs. The receiving side retrieves this data in the method onCreate or onResume.

Data transfer is carried out as follows:

  • ๐Ÿ“ค Sending: Use the method intent.putExtra("key", value) before starting the activity.
  • ๐Ÿ“ฅ Receiving: Use intent.getStringExtra("key") or similar methods for other data types.
  • ๐Ÿ”™ Return result: To receive a response from the second activity, use startActivityForResult (legacy) or modern Activity Result API.

When passing complex objects, make sure that they implement the interface Serializable or Parcelable. Without this, the system will not be able to correctly serialize the object when moving between processes or when restoring the system state.

What is a Task Stack?

The Task Stack is a data structure in which Android stores the history of open activities. When the Back button is pressed, the system retrieves the activity from the top of the stack and destroys it, returning the user to the previous screen.

Typical errors and debugging

During the learning process, you will inevitably encounter errors. The most common problem is NullPointerException. It often occurs when you try to access a UI element (such as a button) before a method has been called, or if the ID in the code does not match the ID in the XML. setContentView, or if the ID in the code does not match the ID in the XML.

Another common error involves context. Using the wrong context (for example, an activity context where an application context is needed) can lead to memory leaks. The system will keep the activity in memory even after it is closed, which will eventually lead to slowdowns and crashes.

โš ๏ธ Attention: Android interfaces and versions of libraries are constantly updated. Methods described in older textbooks (for example, direct use findViewById without checking for null) may be considered obsolete. Always check Google's official documentation for the latest best practices.

Use the tool Logcat in the bottom bar of Android Studio to find the cause of errors. It displays system logs in real time. Filter logs by your application tag or by error level to quickly find the call stack that led to the crash.

Don't forget about testing on real devices. The emulator is great for a quick check, but it does not always correctly reproduce the behavior of the sensor, working with memory or switching networks, which can hide critical bugs.

๐Ÿ’ก

The main reason for 90% of beginner errors is a lack of understanding of the Activity life cycle and an attempt to work with UI elements at inappropriate times (for example, after onStop).

FAQ: Frequently asked questions about creating an Activity

Is it possible to have multiple Activities in one code file?

Technically, you can declare multiple classes in one file .kt or .java, but this is considered bad practice. Each activity should be in its own separate file for ease of code support and project navigation. In addition, each of them must be separately registered in the manifest.

What is the difference between an Activity and a Fragment?

An Activity is a full-fledged application screen that has its own lifecycle and window. Fragment is a modular part of the interface that lives inside an Activity. Fragments allow you to create flexible interfaces that look different on phones (one fragment per screen) and tablets (multiple fragments on the same screen).

Why is my app crashing with the error "Unable to instantiate activity"?

This error usually means one of three problems: the activity is not registered in AndroidManifest.xml, the activity class is not public (public), or it does not have a public no-argument constructor. Check these three points first.

How to prevent an Activity from closing when the screen is rotated?

By default, when the screen is rotated, the activity is destroyed and recreated to load resources for the new orientation. To save the state, you need to override the method onSaveInstanceState and restore the data to onCreate. Or you can strictly fix the orientation in the manifest with an attribute android:screenOrientation="portrait".

Is it mandatory to use Kotlin, or can you write in Java?

Using Kotlin is not necessary, but it is highly recommended. Google has declared Kotlin a first-class language for Android. Many new libraries and code examples are written only in Kotlin. Java is supported, but new API functions may be less accessible or require more code to implement in Java.