Your First Android App

Create a project, understand MainActivity, design XML layouts, run the app, and generate your first APK

New Project MainActivity XML Layout APK

Table of Contents

1Creating New Project

Every Android app starts as a project in Android Studio. A project contains modules (usually one app module), source code, resources, and Gradle build files.

Step-by-step: New Project Wizard

1

Open Android Studio → File → New → New Project (or welcome screen New Project).

2

Select template: Empty Activity (recommended for beginners) or Empty Views Activity.

3

Name: e.g., MyFirstApp · Package name: com.example.myfirstapp (unique reverse-domain ID).

4

Language: Kotlin · Minimum SDK: API 24 (Android 7.0) covers ~95%+ devices.

5

Click Finish. Gradle sync runs automatically — wait until it completes.

What gets created?

File / FolderPurpose
app/src/main/java/.../MainActivity.ktEntry-point Activity (your first screen logic)
app/src/main/res/layout/activity_main.xmlUI layout for MainActivity
app/src/main/AndroidManifest.xmlApp metadata, permissions, component declarations
app/build.gradle.ktsModule build config (SDK versions, dependencies)
res/values/strings.xmlString resources (app name, labels)

2Understanding MainActivity

MainActivity is the entry point of your app — the first screen the user sees. It extends AppCompatActivity and connects Kotlin code to the XML layout.

Kotlin — MainActivity.ktpackage com.example.myfirstapp import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Inflate and display the layout XML setContentView(R.layout.activity_main) } }

Key concepts in MainActivity

onCreate()

Called once when the Activity is created. Initialize UI, bind data, set listeners here.

setContentView()

Links the Activity to an XML layout file — tells Android which UI to display.

R.layout.activity_main

Auto-generated resource ID referencing res/layout/activity_main.xml.

savedInstanceState

Bundle holding state if Activity is recreated (e.g., after rotation).

Adding a button click handler

Kotlin — Button click exampleimport android.widget.Button import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btnHello = findViewById<Button>(R.id.btnHello) btnHello.setOnClickListener { Toast.makeText(this, "Hello, Android!", Toast.LENGTH_SHORT).show() } } }

3XML Layout Basics

Android UIs are defined in XML layout files under res/layout/. Each file describes a hierarchy of Views (widgets) inside a root layout container.

activity_main.xml — Hello World layout

XML — res/layout/activity_main.xml<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tvGreeting" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:textSize="24sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btnHello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tap Me" app:layout_constraintTop_toBottomOf="@id/tvGreeting" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="16dp" /> </androidx.constraintlayout.widget.ConstraintLayout>

Common XML attributes

AttributeValuesMeaning
android:layout_widthmatch_parent, wrap_content, 100dpWidth of the view
android:layout_heightmatch_parent, wrap_contentHeight of the view
android:id@+id/viewNameUnique ID to reference in Kotlin code
android:text@string/key or literalText displayed on TextView/Button
android:layout_margin16dpSpace outside the view
android:padding8dpSpace inside the view

Common layout containers

ConstraintLayout

Flexible flat hierarchy — recommended default for complex UIs.

LinearLayout

Arranges children in a single row or column.

FrameLayout

Stacks views on top of each other — simple overlays.

GridLayout

Grid of rows and columns for structured layouts.

Design vs Code view

Use the Design tab in Android Studio to drag-and-drop widgets visually. Switch to Code tab to edit XML directly — both stay in sync.

4Running Your App

You have two options: a physical device or an emulator (virtual device).

Option A: Physical Device

Easier & faster — real hardware, no emulator boot time.

  1. Enable Developer Options: Settings → About Phone → tap Build Number 7 times.
  2. Enable USB Debugging: Developer Options → USB Debugging → ON.
  3. Connect phone via USB cable (accept the debugging prompt on the phone).
  4. In Android Studio, click the green Run button ▶ (or press Shift + F10).
  5. Select your device from the list and wait for install + launch.
Option B: Emulator (Virtual Device)
  1. Click the Device Manager icon (smartphone icon in the toolbar).
  2. Click Create device → select a phone model (e.g., Pixel 6) → Next.
  3. Download a system image (e.g., API 34 – Android 14) → Next.
  4. Name your AVD (Android Virtual Device) → Finish.
  5. Click the green Play button ▶ next to the emulator in Device Manager.
  6. Once the emulator boots, run your app as in Option A.

What happens when you run?

1

Android Studio compiles Kotlin/Java source into DEX bytecode.

2

Gradle builds the APK (Android Package) from code, resources, and manifest.

3

The APK is installed on the selected device or emulator via ADB.

4

MainActivity launches — the system calls onCreate() and your UI appears.

Gradle — Build and install from terminal# Build debug APK and install on connected device ./gradlew installDebug # Launch MainActivity via adb adb shell am start -n com.example.myfirstapp/.MainActivity

Build variants

Debug
Development builds with logging enabled
Release
Optimized, signed builds for distribution
Debugging tip: Open Logcat (bottom panel) to see runtime logs. Filter by your package name and use Log.d("TAG", "message") in Kotlin to print debug output.

5APK Generation

An APK (Android Package) is the installable file format for Android apps. For Play Store publishing, Google prefers AAB (Android App Bundle), but APK is ideal for testing and sideloading.

Generate Debug APK (quick testing)

1

Build → Build Bundle(s) / APK(s) → Build APK(s)

2

Wait for Gradle build to finish. Click locate in the notification.

3

APK path: app/build/outputs/apk/debug/app-debug.apk

Gradle — Command line# Generate debug APK ./gradlew assembleDebug # Generate release APK (requires signing config) ./gradlew assembleRelease # Output location # app/build/outputs/apk/debug/app-debug.apk

Debug vs Release APK

TypeSigned?Optimized?Use case
Debug APKAuto debug keyNoTesting on your device/emulator
Release APKYour release keystoreYes (ProGuard/R8)Distribution, Play Store (AAB preferred)

Install APK on a device

ADB — Sideload APKadb install app/build/outputs/apk/debug/app-debug.apk # Reinstall over existing app adb install -r app-debug.apk

6App Components Introduction

Android apps are built from four fundamental app components. Each serves a distinct role and is declared in AndroidManifest.xml.

Activity Service Broadcast Receiver Content Provider
Activity

One screen with a UI. MainActivity is your first Activity. Users interact with your app through Activities.

Service

Runs in the background without a UI — music playback, file downloads, location tracking.

Broadcast Receiver

Listens for system-wide events — battery low, boot completed, incoming SMS.

Content Provider

Manages shared app data — contacts, media files. Enables data sharing between apps.

AndroidManifest.xml — declaring components

XML — AndroidManifest.xml (excerpt)<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myfirstapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/Theme.MyFirstApp"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Manifest elementMeaning
android.intent.action.MAINThis Activity is an entry point
android.intent.category.LAUNCHERShow app icon in the launcher/home screen
android:exported="true"Other apps/system can launch this Activity

What you learned: You created a project, wrote MainActivity, designed an XML layout, ran the app on a device, generated a debug APK, and met the four core app components. Try the hands-on exercises below, then explore the full project structure in the next lesson.

7Hands-On Exercises

Practice what you've learned with these beginner-friendly challenges. Complete them in order to reinforce core Android concepts.

Exercise 1: Button + Toast

Add a button to your XML layout and show a Toast when clicked.

Exercise 2: Second Activity

Create SecondActivity.kt and navigate via Intent.

Exercise 3: Signed APK

Build a signed APK and install on another phone.

Exercise 4: Explore APK

Rename APK to .zip and inspect its contents.

Exercise 1 — Button click with Toast

Add a Button with android:id="@+id/clickButton" in activity_main.xml, then wire it in MainActivity:

Kotlin — Toast on button clickfindViewById<Button>(R.id.clickButton).setOnClickListener { Toast.makeText(this, "Hello from Kotlin!", Toast.LENGTH_SHORT).show() }

Exercise 2 — Navigate to a second Activity

Create SecondActivity.kt, add a layout, register it in AndroidManifest.xml, then start it with an Intent:

Kotlin — Intent navigation// In MainActivity — open SecondActivity on button click findViewById<Button>(R.id.clickButton).setOnClickListener { val intent = Intent(this, SecondActivity::class.java) startActivity(intent) }

Exercise 3 — Generate a signed APK

1

Build → Generate Signed App Bundle / APK → choose APK.

2

Create or select a keystore, set alias and passwords.

3

Share the release APK with a friend. On their phone, enable Install from unknown sources (Settings → Security) before installing.

Exercise 4 — Explore the APK internals

  1. Locate your built APK (e.g., app-debug.apk).
  2. Rename the file extension from .apk to .zip.
  3. Unzip it and examine key files inside:
File inside APKWhat it contains
AndroidManifest.xmlBinary-encoded manifest (use aapt dump or Android Studio APK Analyzer to read)
classes.dexCompiled DEX bytecode — your app's Kotlin/Java code
res/Compiled resources (layouts, drawables, strings)
META-INF/Signing certificates and manifest checksums
Pro tip

Use Build → Analyze APK in Android Studio to inspect any APK visually — no manual unzip needed. You'll see DEX files, manifest, and resource breakdown in one view.

First Android App MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic First Android App MCQs

1

Which template creates a minimal starter project?

AEmpty Activity
BGame Activity
CWear OS
DAutomotive
Explanation: Empty Activity provides MainActivity and a basic layout.
2

MainActivity typically extends?

AService
BAppCompatActivity
CApplication
DFragment
Explanation: AppCompatActivity provides backward-compatible Activity features.
3

Which method inflates the UI layout?

AonStart()
BsetContentView()
ConResume()
DfindViewById() only
Explanation: setContentView(R.layout.activity_main) connects Activity to XML layout.
4

Layout files live in which folder?

Ares/layout/
Bsrc/main/java/
Cassets/
Dmanifest/
Explanation: XML layouts are stored under res/layout/.
5

R.layout.activity_main refers to?

AJava class
BLayout resource ID
CGradle script
DManifest entry
Explanation: R is the auto-generated resources class; layout IDs come from XML filenames.
6

Which file declares the app's launcher Activity?

Abuild.gradle
BAndroidManifest.xml
Cproguard-rules.pro
Dstrings.xml
Explanation: Manifest registers components and MAIN/LAUNCHER intent filter.
7

Debug APK is unsigned for?

APlay Store release
BLocal testing only
CProduction rollout
DFirebase only
Explanation: Debug builds use a debug keystore; release needs a signed AAB/APK.
8

Green Run button in Android Studio?

ADeletes project
BBuilds and deploys app to device/emulator
COpens SDK Manager
DFormats code
Explanation: Run compiles, installs, and launches the app on the selected target.
9

applicationId in Gradle is?

APackage name for Play Store / unique app ID
BActivity name
CLayout name
DSDK version
Explanation: applicationId uniquely identifies the app on device and Play Store.
10

onCreate receives?

AIntent only
BBundle savedInstanceState
CView hierarchy
DGradle config
Explanation: savedInstanceState restores state after process death or rotation (if handled).

10 Advanced First Android App MCQs

11

ViewBinding replaces findViewById by?

AGenerating binding classes per layout
BUsing reflection only
CRemoving XML
DReplacing Activities
Explanation: ViewBinding generates type-safe references like ActivityMainBinding.
12

LAUNCHER intent filter means?

AApp appears in app drawer
BBackground service
CContent provider
DSystem app only
Explanation: MAIN action + LAUNCHER category makes the Activity the entry point.
13

Build Variants debug vs release differ in?

ASigning, optimization, debuggable flag
BOnly color theme
CManifest package only
DNothing
Explanation: Release builds are minified, signed with release key, and not debuggable.
14

namespace in build.gradle (AGP 8+)?

AReplaces package in manifest for R class generation
BEmulator name
CSDK path
DADB command
Explanation: namespace defines the Java/Kotlin package for R and BuildConfig.
15

Why avoid heavy work in onCreate?

ASlows first frame / ANR risk
BBreaks Gradle
CInvalidates manifest
DDisables ViewBinding
Explanation: Long onCreate blocks main thread; defer I/O to background coroutines.
16

AAB vs APK for Play Store?

AAAB required; Google generates optimized APKs
BAPK only forever
CAAB is debug format
DSame file type
Explanation: Android App Bundle enables split APKs by density, ABI, and language.
17

tools:context in layout XML?

ADesign-time preview hint for Android Studio
BRuntime security
CProGuard rule
DADB filter
Explanation: tools:context helps the layout editor pick theme and Activity context.
18

Default language for new Google projects?

AKotlin
BJava only
CC++
DPython
Explanation: Google recommends Kotlin for new Android projects since 2019.
19

If R.id.button is unresolved?

ASync Gradle / fix resource errors
BDelete manifest
CDisable emulator
DChange JDK to 8
Explanation: R is regenerated when resources compile; errors in XML block R generation.
20

Process death and Activity recreation?

ASystem may kill app; Activity restarts with optional saved state
BApp always continues
COnly on iOS
DGradle prevents it
Explanation: Low memory kills processes; restore UI state via savedInstanceState or ViewModel.
Click an option to select, then check answers.

First Android App Interview Q&A

15 topic-focused questions for interviews and revision.

1Walk through creating your first Android project.easy
Answer: Open Android Studio → New Project → Empty Activity → set name, package, language Kotlin, minimum SDK → Finish → wait for Gradle sync → Run on emulator or device.
2Explain the role of MainActivity.easy
Answer: MainActivity is the entry-point screen; it hosts the UI, handles lifecycle callbacks, and responds to user interaction for the first visible screen.
3What is the relationship between Activity and layout XML?easy
Answer: Activity code calls setContentView with a layout resource; XML defines the View hierarchy; Activity logic wires events and updates Views.
4What does AndroidManifest.xml contain for a simple app?medium
Answer: Package/namespace, application tag, Activity declarations, permissions, and intent filters including MAIN/LAUNCHER for the starter Activity.
5How is an APK generated from Android Studio?medium
Answer: Build → Build Bundle(s)/APK(s) → Build APK(s); Gradle assembles dex, resources, and manifest into a signed debug or release APK.
6Difference between package name and applicationId.medium
Answer: Historically the same; applicationId is the unique Play Store identifier and can differ from code namespace in advanced scenarios (product flavors).
7What happens when you click Run?easy
Answer: Gradle compiles Kotlin/Java and resources, packages APK, adb installs on target, Android launches launcher Activity, Logcat shows runtime logs.
8Why use AppCompatActivity instead of raw Activity?medium
Answer: AppCompat provides Material themes, backward-compatible widgets, and consistent behavior across API levels.
9How do you change the app name shown on the home screen?easy
Answer: Set android:label on the application or launcher Activity in the manifest, typically referencing @string/app_name in strings.xml.
10What is Logcat used for during first app runs?easy
Answer: Logcat displays system and app logs — exceptions, println, Log.d — essential for debugging crashes and startup issues.
11Explain debug vs release build for beginners.medium
Answer: Debug: fast builds, debug keystore, debuggable, no shrinking. Release: optimized, ProGuard/R8 optional, signed with release key for distribution.
12What are the four components mentioned when extending a first app?medium
Answer: Activities (UI), Services (background), Broadcast Receivers (system events), Content Providers (shared data) — declared in the manifest.
13How would you add a second screen?medium
Answer: Create New Activity + layout, register in manifest, start it with an explicit Intent from MainActivity (e.g., button click).
14Common first-build errors and fixes?hard
Answer: SDK not found → local.properties; Gradle sync → JDK 17; missing SDK platform → SDK Manager; red XML → fix layout errors.
15What should a Hello World app demonstrate?easy
Answer: Successful project creation, layout inflation, launcher registration, deployment to emulator/device, and basic understanding of Activity + resources.