Tuesday, October 15, 2019

Android BaseActivity Tutorial — Reusable Activity Architecture in Android

No comments email this post Edit Post

In large Android applications, developers often repeat the same code across multiple activities.

Examples:

  • Progress dialogs
  • Keyboard handling
  • Activity transitions
  • Internet connection checks
  • Permission handling
  • Font configuration

To avoid duplicate code and improve maintainability, Android applications commonly use:


BaseActivity

What Is BaseActivity?

BaseActivity is a parent activity class that contains:

  • Common reusable functionality
  • Shared UI behavior
  • Global helper methods
  • Application-wide configurations

Other activities extend BaseActivity to inherit common features.


Why Use BaseActivity?

Without BaseActivity:

  • Code duplication increases
  • Maintenance becomes difficult
  • Bug fixing becomes repetitive
  • Project structure becomes messy

BaseActivity centralizes shared functionality.


Common Features Inside BaseActivity

  • Loading dialogs
  • Network state detection
  • Keyboard hiding
  • Permission helpers
  • Activity animations
  • Analytics logging
  • Crash handling
  • Theme handling

Modern Android Recommendation

Older Android tutorials use:


android.support.*

which is deprecated.

Modern Android applications should use:


androidx.*

Modern BaseActivity Example


package com.example.baseapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public abstract class BaseActivity
        extends AppCompatActivity {

    @Override
    protected void onCreate(
            @Nullable Bundle savedInstanceState
    ) {

        super.onCreate(savedInstanceState);
    }

    @Override
    public void startActivity(
            Intent intent
    ) {

        super.startActivity(intent);

        overridePendingTransition(
                android.R.anim.fade_in,
                android.R.anim.fade_out
        );
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();

        overridePendingTransition(
                android.R.anim.fade_in,
                android.R.anim.fade_out
        );
    }

    @Override
    public boolean dispatchTouchEvent(
            MotionEvent event
    ) {

        View view = getCurrentFocus();

        if (view instanceof EditText) {

            int[] coordinates =
                    new int[2];

            view.getLocationOnScreen(
                    coordinates
            );

            float x = event.getRawX()
                    + view.getLeft()
                    - coordinates[0];

            float y = event.getRawY()
                    + view.getTop()
                    - coordinates[1];

            if (
                event.getAction()
                == MotionEvent.ACTION_UP
            ) {

                if (
                    x < view.getLeft()
                    || x > view.getRight()
                    || y < view.getTop()
                    || y > view.getBottom()
                ) {

                    hideKeyboard(view);
                }
            }
        }

        return super.dispatchTouchEvent(
                event
        );
    }

    private void hideKeyboard(
            View view
    ) {

        InputMethodManager manager =
                (InputMethodManager)
                getSystemService(
                        Context.INPUT_METHOD_SERVICE
                );

        if (manager != null) {

            manager.hideSoftInputFromWindow(
                    view.getWindowToken(),
                    0
            );
        }
    }
}

Understanding BaseActivity Features

  • Common transition animation
  • Keyboard auto hide
  • Centralized lifecycle behavior
  • Shared utility methods

How to Use BaseActivity?

Instead of:


extends AppCompatActivity

activities should use:


extends BaseActivity

Example Usage


public class MainActivity
        extends BaseActivity {

}

What Is AppController?

AppController is commonly an:


Application

class used for:

  • Global initialization
  • SDK setup
  • Analytics setup
  • Crash reporting
  • Dependency initialization

Create AppController.java


package com.example.baseapp;

import android.app.Application;

public class AppController
        extends Application {

    private static AppController
            instance;

    @Override
    public void onCreate() {

        super.onCreate();

        instance = this;
    }

    public static AppController
    getInstance() {

        return instance;
    }
}

Add Application Class in Manifest


<application

    android:name=".AppController"

    android:allowBackup="true"

    android:theme="@style/Theme.App">

</application>

Why Use Application Class?

Application class initializes components before activities start.

Useful for:

  • Firebase
  • Crashlytics
  • Retrofit
  • Dependency Injection
  • Logging systems

Modern Android Replacements

Older tutorials commonly use:

  • Fabric Crashlytics
  • Calligraphy fonts
  • Manual permission handlers

Modern Android now recommends:

  • Firebase Crashlytics
  • Material Typography
  • Activity Result APIs
  • Jetpack libraries

Modern Firebase Crashlytics

Instead of:


Fabric.with(this, new Crashlytics());

Modern apps use:


FirebaseCrashlytics

Modern Font Recommendation

Instead of Calligraphy library:

  • Use XML fonts
  • Use Material Typography
  • Use Google Fonts

Modern Permission Handling

Instead of manual permission managers:

Use:


ActivityResultLauncher

Keyboard Handling Explanation

The:


dispatchTouchEvent()

method hides keyboard when user taps outside EditText.

This improves:

  • User experience
  • Form interaction
  • Screen usability

Modern Architecture Recommendation

Modern Android apps usually combine:

  • BaseActivity
  • MVVM Architecture
  • ViewBinding
  • Dependency Injection
  • Navigation Component
  • Jetpack Compose

BaseActivity vs BaseFragment

BaseActivity BaseFragment
Activity-level logic Fragment-level logic
Global UI behavior Reusable fragment behavior
Transitions/navigation Fragment-specific logic

Modern Jetpack Compose Alternative

Jetpack Compose reduces the need for large BaseActivity classes by:

  • Using composables
  • Using state hoisting
  • Using lifecycle-aware components

Common Beginner Mistakes

1. Putting Too Much Logic Inside BaseActivity

Keep BaseActivity lightweight and reusable.


2. Memory Leaks

Avoid storing Activity references globally.


3. Tight Coupling

Do not place feature-specific code inside BaseActivity.


Best Practices

  • Keep BaseActivity generic
  • Use helper methods carefully
  • Avoid unnecessary inheritance
  • Use lifecycle-aware components
  • Combine with MVVM architecture

FAQ

Why use BaseActivity?

BaseActivity reduces duplicate code across multiple activities.


Is BaseActivity mandatory?

No. It is an architectural choice.


Should all activities extend BaseActivity?

Only if they share common reusable functionality.


Conclusion

BaseActivity is a powerful architectural pattern for organizing reusable Android application behavior.

It helps improve maintainability, reduce duplicate code, and centralize common functionality across activities.

Modern Android applications should combine BaseActivity, AndroidX, MVVM architecture, lifecycle-aware components, and scalable project structure for production-grade development.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

How to Build a News App in Android Using NewsAPI, ListView, and WebView

No comments email this post Edit Post

News applications are one of the most common real-world Android projects for learning:

  • REST APIs
  • JSON parsing
  • ListView and RecyclerView
  • Image loading
  • Networking
  • WebView integration

In this tutorial, we will build a simple Android News App using:

  • NewsAPI
  • Java
  • ListView
  • Picasso Image Library
  • JSON Parsing
  • WebView

What We Will Build

In this Android News App:

  • Fetch latest news articles
  • Display news headlines
  • Load news images
  • Open full article inside WebView
  • Check internet connectivity
  • Parse JSON response

Important Modern Android Note

This tutorial modernizes an older Android project structure.

Modern Android applications should preferably use:

  • RecyclerView instead of ListView
  • Retrofit instead of AsyncTask
  • Coroutines instead of AsyncTask
  • Glide or Coil instead of older Picasso versions
  • MVVM Architecture
  • Jetpack Compose

However, this tutorial is still excellent for beginners learning Android networking fundamentals.


Step 1 — Create NewsAPI Account

Create a free API key from:

https://newsapi.org/

You will receive an API key required for fetching news articles.


Step 2 — Create Android Project

Open Android Studio and create:


Empty Activity

using:

  • Java
  • Minimum SDK 21+

Step 3 — Add Dependency

Inside:


build.gradle

Add:


implementation 'com.squareup.picasso:picasso:2.8'

Why Picasso?

Picasso simplifies:

  • Image downloading
  • Caching
  • Async image loading
  • Memory optimization

Step 4 — Add Internet Permission

Open:


AndroidManifest.xml

Add:


<uses-permission
    android:name=
    "android.permission.INTERNET"/>

<uses-permission
    android:name=
    "android.permission.ACCESS_NETWORK_STATE"/>

Modernized AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>

<manifest
    xmlns:android=
    "http://schemas.android.com/apk/res/android">

    <uses-permission
        android:name=
        "android.permission.INTERNET"/>

    <uses-permission
        android:name=
        "android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:supportsRtl="true"
        android:theme="@style/Theme.NewsApp">

        <activity
            android:name=".DetailsActivity"/>

        <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>

Step 5 — Create activity_main.xml

Create:


res/layout/activity_main.xml

<RelativeLayout
    xmlns:android=
    "http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listNews"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:divider="#EEEEEE"

        android:dividerHeight="1dp"/>

    <ProgressBar
        android:id="@+id/loader"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"/>

</RelativeLayout>

Step 6 — Create News List Item Layout

Create:


res/layout/list_row.xml

This layout contains:

  • News Image
  • Title
  • Description
  • Author
  • Publish Time

Modern Android applications should prefer:


ConstraintLayout

instead of deeply nested LinearLayouts for better performance.


Step 7 — Create activity_details.xml

This screen loads the full news article inside a WebView.


<RelativeLayout
    xmlns:android=
    "http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webView"

        android:layout_width="match_parent"

        android:layout_height="match_parent"/>

    <ProgressBar
        android:id="@+id/loader"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"/>

</RelativeLayout>

Step 8 — Create Network Utility Class

Create:


Function.java

This class handles:

  • Internet checking
  • HTTP requests
  • API response handling

Modern Networking Recommendation

This project uses:


HttpURLConnection

Modern Android apps should instead use:

  • Retrofit
  • OkHttp
  • Coroutines
  • Flow

Step 9 — Create MainActivity.java

MainActivity handles:

  • Fetching news articles
  • Parsing JSON
  • Populating ListView
  • Opening article details

Important Modernization

The original tutorial uses:


AsyncTask

AsyncTask is deprecated in modern Android development.

Recommended alternatives:

  • Coroutines
  • Executors
  • WorkManager

Example NewsAPI Request


https://newsapi.org/v2/top-headlines
?country=us
&apiKey=YOUR_API_KEY

Step 10 — Create Adapter Class

Create:


ListNewsAdapter.java

The adapter binds:

  • News title
  • Description
  • Image
  • Author
  • Publish date

to ListView items.


Step 11 — Create DetailsActivity.java

DetailsActivity loads article URLs inside WebView.

Features:

  • Zoom support
  • Progress loading
  • Web page rendering

How This News App Works

  1. User opens app
  2. App checks internet connection
  3. NewsAPI request is executed
  4. JSON response is parsed
  5. Articles displayed in ListView
  6. User clicks article
  7. WebView opens full article

JSON Parsing Example

NewsAPI returns:


{
  "articles":[
    {
      "title":"News Title",
      "description":"News Description",
      "url":"https://...",
      "urlToImage":"https://..."
    }
  ]
}

Why WebView Is Used?

WebView allows:

  • Displaying full web pages
  • Opening articles inside app
  • Better user retention

Modern Android Architecture Recommendation

Production-grade News Apps should use:

  • MVVM Architecture
  • Retrofit
  • Room Database
  • Paging 3
  • RecyclerView
  • Jetpack Compose
  • Offline caching
  • Repository Pattern

Common Beginner Mistakes

1. Exposing API Keys

Never hardcode API keys directly in source code for production applications.


2. Using AsyncTask

AsyncTask is deprecated.

Prefer:

  • Coroutines
  • Executors
  • WorkManager

3. Not Handling Null JSON Values

Some news articles may not contain:

  • Author
  • Image
  • Description

Always handle null values safely.


Picasso vs Glide vs Coil

Library Use Case
Picasso Simple image loading
Glide Large-scale image optimization
Coil Kotlin-first image loading

FAQ

Can this app work offline?

Not currently.

Offline support can be added using:

  • Room Database
  • Caching
  • Paging Library

Why use RecyclerView instead of ListView?

RecyclerView provides:

  • Better performance
  • Animations
  • Flexible layouts
  • View recycling optimization

What is the modern networking solution?

Retrofit with Kotlin Coroutines is the modern Android networking standard.


Conclusion

Building a News App is an excellent Android project for learning networking, JSON parsing, image loading, adapters, and API integration.

This project demonstrates how Android applications communicate with remote APIs and display dynamic content.

Modern Android applications should additionally use MVVM architecture, Retrofit, RecyclerView, and lifecycle-aware components for scalable production-grade implementations.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Monday, October 14, 2019

Top Android Interview Questions and Answers for Freshers and Experienced Developers

No comments email this post Edit Post

Android interviews commonly test both fundamental concepts and real-world development knowledge.

Whether you are a beginner Android developer or an experienced mobile engineer, understanding Android architecture, lifecycle, UI components, services, and application flow is essential.

In this guide, we will cover important Android interview questions with modernized explanations and updated Android development practices.


What Is Android?

Android is an open-source mobile operating system developed by Google.

It provides:

  • Operating System
  • Application Framework
  • Middleware
  • Development SDK
  • System Applications

Android applications run inside isolated application sandboxes for security and stability.


What Are the Advantages of Android?

  • Open-source platform
  • Large developer community
  • Powerful SDK
  • Supports Kotlin and Java
  • Wide device ecosystem
  • Google Play distribution
  • Rich APIs and libraries
  • Strong hardware integration

Describe Android Application Architecture

Android application architecture includes:

  • Activities
  • Fragments
  • Services
  • Broadcast Receivers
  • Content Providers
  • Intents
  • Resources
  • Notifications

What Is an Activity?

An Activity represents a single screen with a user interface.

Examples:

  • Login Screen
  • Home Screen
  • Settings Screen

Activities manage:

  • User interaction
  • Lifecycle events
  • Navigation
  • UI rendering

What Is an APK File?

APK stands for:


Android Package Kit

APK contains:

  • Compiled application code
  • Resources
  • Manifest file
  • Assets
  • DEX files

Android applications are distributed using APK files.


What Are the Activity Lifecycle Methods?

The Android Activity lifecycle consists of:

  1. onCreate()
  2. onStart()
  3. onResume()
  4. onPause()
  5. onStop()
  6. onRestart()
  7. onDestroy()

What Is an Intent?

Intent is a messaging mechanism used for communication between Android components.

Intents are used to:

  • Launch Activities
  • Start Services
  • Send Broadcasts
  • Open external applications

What Is an Explicit Intent?

Explicit Intent directly specifies the target component.


Intent intent =
        new Intent(
                MainActivity.this,
                HomeActivity.class
        );

What Is an Implicit Intent?

Implicit Intent does not specify the target component directly.

Android automatically finds a suitable application.


Intent intent =
        new Intent(
                Intent.ACTION_VIEW
        );

What Is AndroidManifest.xml?

AndroidManifest.xml is the central configuration file of an Android application.

It defines:

  • Activities
  • Permissions
  • Services
  • Broadcast Receivers
  • Application metadata

What Languages Are Used for Android Development?

Modern Android applications are primarily developed using:

  • Kotlin
  • Java

Google officially recommends Kotlin for Android development.


What Are DEX Files?

DEX stands for:


Dalvik Executable

DEX files contain compiled Android bytecode optimized for mobile devices.


What Is ADB?

ADB stands for:


Android Debug Bridge

ADB is a command-line tool used for:

  • Debugging
  • Installing APKs
  • Running shell commands
  • Viewing logs
  • Managing devices

What Is a Service?

A Service is an Android component used for background operations.

Examples:

  • Music playback
  • Location tracking
  • Background synchronization

Difference Between Service and Thread

Service Thread
Android component Concurrency mechanism
Lifecycle-aware Runs parallel tasks
Background functionality Worker execution

What Is a Content Provider?

Content Providers allow secure data sharing between Android applications.

Examples:

  • Contacts
  • Media files
  • Call logs

What Is a Toast Notification?

Toast is a lightweight popup message shown temporarily on screen.


Toast.makeText(
    this,
    "Login Successful",
    Toast.LENGTH_SHORT
).show();

What Is a Fragment?

Fragment is a reusable UI component hosted inside an Activity.

Fragments improve:

  • Modularity
  • Navigation
  • Large-screen support
  • Code reuse

What Is ViewGroup?

ViewGroup is a special View that contains other Views.

Examples:

  • LinearLayout
  • ConstraintLayout
  • FrameLayout
  • RelativeLayout

What Is ANR?

ANR stands for:


Application Not Responding

ANR occurs when the UI thread becomes blocked for too long.


How to Avoid ANR?

  • Avoid heavy work on main thread
  • Use Coroutines
  • Use WorkManager
  • Use background threads
  • Optimize network calls

What Is Dalvik Virtual Machine?

Dalvik Virtual Machine (DVM) was Android’s original runtime environment.

Modern Android versions now use:


ART (Android Runtime)

instead of Dalvik.


What Is Android Runtime (ART)?

ART is the modern Android runtime environment.

Benefits:

  • Better performance
  • Improved memory management
  • Faster execution
  • Ahead-of-time compilation

What Is RecyclerView?

RecyclerView is a modern and flexible ViewGroup used for displaying large data collections efficiently.

Benefits:

  • View recycling
  • Better performance
  • Animations support
  • Flexible layouts

What Is MVVM Architecture?

MVVM stands for:

  • Model
  • View
  • ViewModel

MVVM improves:

  • Code separation
  • Lifecycle awareness
  • Testing
  • Maintainability

What Is LiveData?

LiveData is a lifecycle-aware observable data holder class.

It automatically updates UI components when data changes.


What Is ViewModel?

ViewModel stores and manages UI-related data.

It survives configuration changes such as screen rotations.


What Is Room Database?

Room is an abstraction layer over SQLite.

Benefits:

  • Less boilerplate code
  • Compile-time SQL validation
  • Easy database management

What Is Jetpack Compose?

Jetpack Compose is Google’s modern declarative UI toolkit for Android.

It replaces traditional XML-based UI development.


What Is the Difference Between LinearLayout and ConstraintLayout?

LinearLayout ConstraintLayout
Simple row/column layout Flexible positioning system
Nested layouts required Flat hierarchy
Less efficient for complex UI Better performance

What Is the Difference Between Serializable and Parcelable?

Serializable Parcelable
Reflection-based Android optimized
Slower Faster
Easy implementation Better performance

Modern Android Recommendations

Modern Android applications commonly use:

  • Kotlin
  • Jetpack Compose
  • MVVM Architecture
  • Coroutines
  • Hilt Dependency Injection
  • Navigation Component
  • Retrofit
  • Room Database

Common Beginner Mistakes

1. Heavy Work on Main Thread

Always move network and database operations to background threads.


2. Ignoring Lifecycle

Lifecycle-aware components prevent memory leaks and crashes.


3. Using Deprecated APIs

Always prefer AndroidX and modern Jetpack libraries.


Conclusion

Android interviews test both theoretical understanding and practical Android development skills.

Developers should understand Android architecture, lifecycle management, UI systems, threading, networking, and modern Jetpack libraries.

Modern Android development now focuses heavily on Kotlin, Jetpack Compose, MVVM architecture, lifecycle awareness, and scalable application design.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Android Core Building Blocks Explained for Beginners

No comments email this post Edit Post

Android applications are built using several core components that work together to create a complete mobile application.

These building blocks help Android developers manage:

  • User interface
  • Navigation
  • Background tasks
  • Data sharing
  • Application lifecycle

Understanding Android core components is essential for every beginner Android developer.


What Are Android Core Building Blocks?

Android core building blocks are the fundamental components provided by the Android framework.

Each component has:

  • A specific purpose
  • A defined lifecycle
  • System-managed behavior

Examples:

  • Activity
  • Service
  • Broadcast Receiver
  • Fragment
  • Content Provider

Main Android Components

Component Purpose
Activity Represents a screen
View User interface element
Intent Communication between components
Service Background operations
Content Provider Data sharing between apps
Fragment Reusable UI section
AndroidManifest.xml Application configuration

1. Activity

An Activity represents a single screen in an Android application.

Examples:

  • Login screen
  • Home screen
  • Settings screen
  • Profile screen

Activities handle:

  • User interaction
  • UI rendering
  • Lifecycle management
  • Navigation

Example Activity


public class MainActivity
        extends AppCompatActivity {

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(savedInstanceState);

        setContentView(
                R.layout.activity_main
        );
    }
}

2. View

A View is any visible UI component on the screen.

Examples:

  • Button
  • TextView
  • EditText
  • ImageView
  • RecyclerView

Example View


<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me"/>

3. Intent

Intent is a messaging object used to communicate between Android components.

Intents are used to:

  • Launch Activities
  • Start Services
  • Send Broadcasts
  • Open web pages
  • Dial phone calls
  • Share content

Example — Open Website Using Intent


Intent intent =
        new Intent(
                Intent.ACTION_VIEW
        );

intent.setData(
        Uri.parse(
                "https://www.deftskill.com"
        )
);

startActivity(intent);

Types of Intents

Intent Type Description
Explicit Intent Launch specific component
Implicit Intent Request external action

4. Service

A Service is a component used for background operations.

Services can perform:

  • Music playback
  • Background downloads
  • Location tracking
  • Data synchronization

Types of Services

Type Description
Foreground Service User-visible background task
Background Service Hidden background operation
Bound Service Connected to other components

5. Content Provider

Content Providers allow applications to share data securely with other applications.

Examples:

  • Contacts
  • Media files
  • Call logs
  • Shared databases

Why Content Providers Are Important

They provide:

  • Centralized data access
  • Permission-based security
  • Cross-application communication

6. Fragment

Fragments are reusable UI sections hosted inside Activities.

Fragments help create:

  • Responsive layouts
  • Tablet interfaces
  • Reusable screens
  • Dynamic navigation

Example Fragment


public class ExampleFragment
        extends Fragment {

}

Why Modern Apps Use Fragments

Fragments improve:

  • Modularity
  • Navigation flexibility
  • Large-screen support
  • Code reusability

7. AndroidManifest.xml

AndroidManifest.xml is one of the most important files in an Android project.

It contains:

  • Activities
  • Permissions
  • Services
  • Broadcast Receivers
  • Application configuration

Example Manifest Declaration


<manifest>

    <application>

        <activity
            android:name=".MainActivity"/>

    </application>

</manifest>

8. Android Virtual Device (AVD)

Android Virtual Device (AVD) is an emulator used for testing Android applications.

AVD helps developers:

  • Test apps without real devices
  • Simulate different screen sizes
  • Test Android versions
  • Debug applications

Modern Android Development Technologies

Modern Android applications commonly use:

  • Kotlin
  • Jetpack Compose
  • MVVM Architecture
  • Coroutines
  • Room Database
  • Retrofit
  • Hilt Dependency Injection
  • Navigation Component

How Android Components Work Together

Typical Android application flow:

  1. Activity displays UI
  2. Views handle interaction
  3. Intent launches another screen
  4. Service performs background work
  5. Fragment manages reusable UI
  6. Content Provider shares data

Common Beginner Mistakes

1. Confusing Activity and Fragment

Activities represent screens, while Fragments are reusable sections inside screens.


2. Forgetting Manifest Declarations

Activities and Services must be declared inside:


AndroidManifest.xml

3. Heavy Work on Main Thread

Background tasks should use:

  • Coroutines
  • WorkManager
  • Services

Modern Android Architecture Recommendations

Modern Android development now prefers:

  • Single Activity Architecture
  • Navigation Component
  • Jetpack Compose
  • MVVM
  • Clean Architecture
  • StateFlow

FAQ

Which Android component displays UI?

Activities and Views are responsible for displaying UI.

Can Fragments exist without Activities?

No. Fragments must be hosted inside Activities.

What is the modern Android language?

Kotlin is the officially recommended language for Android development.


Conclusion

Android core building blocks form the foundation of Android application development.

Understanding these components helps developers build scalable, maintainable, and responsive Android applications.

Modern Android development combines these components with lifecycle-aware architecture, Kotlin, Jetpack libraries, and reactive programming for production-grade mobile applications.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Android Login and Registration API Using PHP, MySQL, and Secure Password Hashing

No comments email this post Edit Post

User authentication is one of the most important features in modern mobile applications.

Most Android applications require:

  • User Registration
  • Login Authentication
  • Password Security
  • Database Storage
  • API Communication

In this tutorial, we will build a secure Login and Registration API using:

  • PHP
  • MySQL
  • Password Hashing
  • JSON APIs
  • Prepared Statements
  • Android backend integration

What We Will Build

In this authentication system:

  • User can register
  • User can login securely
  • Password hashes are stored instead of plain passwords
  • Prepared statements prevent SQL Injection
  • JSON responses are returned
  • MySQL stores user data securely

Technologies Used

  • PHP
  • MySQL
  • phpMyAdmin
  • JSON API
  • Password Hashing
  • Android API Integration

Why Plain Password Storage Is Dangerous

Never store passwords directly inside databases.

Unsafe Example:


password = "123456"

If the database is compromised, all user passwords become exposed.

Modern applications should always use:

  • Password hashing
  • Random salt generation
  • Prepared statements

Step 1 — Create Database

Open:


http://localhost/phpmyadmin/

Create a new database:


androiddeft

Step 2 — Create Member Table

Run the following SQL query:


CREATE TABLE member (

  user_id INT(11) NOT NULL AUTO_INCREMENT,

  username VARCHAR(50) NOT NULL,

  full_name VARCHAR(50) NOT NULL,

  password_hash VARCHAR(256) NOT NULL,

  salt VARCHAR(256) NOT NULL,

  created_date DATETIME
  NOT NULL DEFAULT CURRENT_TIMESTAMP,

  PRIMARY KEY (user_id),

  UNIQUE KEY username (username)

) ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4;

Why utf8mb4 Is Recommended?

Modern MySQL applications should use:


utf8mb4

instead of:


latin1

because it fully supports:

  • Unicode
  • Emoji
  • International text

Project Structure


member/
│
├── db/
│   └── db_connect.php
│
├── functions.php
├── register.php
└── login.php

Step 3 — Create db_connect.php

Create:


db/db_connect.php

<?php

define('DB_USER', 'root');

define('DB_PASSWORD', '');

define('DB_DATABASE', 'androiddeft');

define('DB_SERVER', 'localhost');

$con = mysqli_connect(
    DB_SERVER,
    DB_USER,
    DB_PASSWORD,
    DB_DATABASE
);

if (mysqli_connect_errno()) {

    die(
        "Database Connection Failed: "
        . mysqli_connect_error()
    );
}

?>

Step 4 — Create functions.php

This file handles:

  • User existence check
  • Salt generation
  • Password hashing

<?php

$random_salt_length = 32;

function userExists($username) {

    global $con;

    $query =
        "SELECT username
         FROM member
         WHERE username = ?";

    if ($stmt = $con->prepare($query)) {

        $stmt->bind_param(
            "s",
            $username
        );

        $stmt->execute();

        $stmt->store_result();

        if ($stmt->num_rows == 1) {

            $stmt->close();

            return true;
        }

        $stmt->close();
    }

    return false;
}

function getSalt() {

    global $random_salt_length;

    return bin2hex(
        random_bytes(
            $random_salt_length
        )
    );
}

function concatPasswordWithSalt(
    $password,
    $salt
) {

    return $password . $salt;
}

?>

Why random_bytes() Is Better?

Modern PHP applications should use:


random_bytes()

instead of older:


openssl_random_pseudo_bytes()

because it provides stronger cryptographic randomness.


Step 5 — Create register.php

This API registers new users securely.


<?php

$response = array();

include 'db/db_connect.php';

include 'functions.php';

$inputJSON =
    file_get_contents('php://input');

$input =
    json_decode($inputJSON, true);

if (
    isset($input['username']) &&
    isset($input['password']) &&
    isset($input['full_name'])
) {

    $username =
        trim($input['username']);

    $password =
        trim($input['password']);

    $fullName =
        trim($input['full_name']);

    if (!userExists($username)) {

        $salt = getSalt();

        $passwordHash =
            password_hash(
                concatPasswordWithSalt(
                    $password,
                    $salt
                ),
                PASSWORD_DEFAULT
            );

        $query =
            "INSERT INTO member
            (username, full_name,
             password_hash, salt)

             VALUES (?, ?, ?, ?)";

        if ($stmt = $con->prepare($query)) {

            $stmt->bind_param(
                "ssss",
                $username,
                $fullName,
                $passwordHash,
                $salt
            );

            $stmt->execute();

            $response["status"] = 0;

            $response["message"] =
                "User Registered Successfully";

            $stmt->close();
        }

    } else {

        $response["status"] = 1;

        $response["message"] =
            "Username Already Exists";
    }

} else {

    $response["status"] = 2;

    $response["message"] =
        "Missing Required Parameters";
}

echo json_encode($response);

?>

Step 6 — Create login.php

This API validates login credentials securely.


<?php

$response = array();

include 'db/db_connect.php';

include 'functions.php';

$inputJSON =
    file_get_contents('php://input');

$input =
    json_decode($inputJSON, true);

if (
    isset($input['username']) &&
    isset($input['password'])
) {

    $username =
        trim($input['username']);

    $password =
        trim($input['password']);

    $query =
        "SELECT full_name,
                password_hash,
                salt

         FROM member

         WHERE username = ?";

    if ($stmt = $con->prepare($query)) {

        $stmt->bind_param(
            "s",
            $username
        );

        $stmt->execute();

        $stmt->bind_result(
            $fullName,
            $passwordHashDB,
            $salt
        );

        if ($stmt->fetch()) {

            if (
                password_verify(
                    concatPasswordWithSalt(
                        $password,
                        $salt
                    ),
                    $passwordHashDB
                )
            ) {

                $response["status"] = 0;

                $response["message"] =
                    "Login Successful";

                $response["full_name"] =
                    $fullName;

            } else {

                $response["status"] = 1;

                $response["message"] =
                    "Invalid Credentials";
            }

        } else {

            $response["status"] = 1;

            $response["message"] =
                "Invalid Credentials";
        }

        $stmt->close();
    }

} else {

    $response["status"] = 2;

    $response["message"] =
        "Missing Required Parameters";
}

echo json_encode($response);

?>

How This Authentication System Works

  1. User registers
  2. Password gets salted and hashed
  3. Secure hash stored in MySQL
  4. User logs in
  5. Password is verified using password_verify()
  6. JSON response returned to Android app

Example JSON Request

Register Request


{
  "username":"salil",
  "password":"123456",
  "full_name":"Salil Jha"
}

Success Response


{
  "status":0,
  "message":"Login Successful"
}

Security Improvements Over Old Tutorials

Old Approach Modern Secure Approach
Plain passwords Password hashing
Unsafe SQL queries Prepared statements
Weak salt methods random_bytes()
latin1 charset utf8mb4 charset

Modern Backend Recommendations

Production-grade mobile applications should additionally use:

  • JWT Authentication
  • HTTPS
  • Rate limiting
  • Token refresh system
  • Input validation
  • Password strength rules
  • Email verification
  • Laravel or FastAPI backend

Common Beginner Mistakes

1. Storing Plain Passwords

Always use:


password_hash()

2. Using Raw SQL Queries

Prepared statements prevent SQL Injection attacks.


3. Ignoring HTTPS

Authentication APIs should always run on HTTPS in production.


FAQ

Can Android directly connect to MySQL?

No. Android apps should communicate through secure backend APIs.

Why use password_hash()?

It securely hashes passwords using modern algorithms.

What is the modern authentication method?

JWT Authentication with secure REST APIs is commonly used today.


Conclusion

Building secure login and registration systems is essential for modern Android applications.

Using PHP, MySQL, prepared statements, password hashing, and JSON APIs provides a solid backend authentication foundation.

Modern applications should further integrate JWT authentication, HTTPS security, token-based authorization, and scalable backend architectures for production-grade systems.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Why Kotlin Is the Preferred Language for Modern Android Development

No comments email this post Edit Post

Kotlin has become one of the most important programming languages for Android development.

Google officially announced Kotlin as a first-class language for Android development, and today most modern Android applications are built using Kotlin.

In this tutorial, we will understand:

  • What Kotlin is
  • Why Kotlin is popular
  • Advantages of Kotlin over Java
  • How Kotlin improves Android development

What Is Kotlin?

Kotlin is a statically typed modern programming language developed by JetBrains.

It runs on:

  • Java Virtual Machine (JVM)
  • Android
  • Backend servers
  • Web applications
  • Desktop applications

Kotlin is fully interoperable with Java, meaning developers can use existing Java libraries and frameworks directly inside Kotlin projects.


Why Google Supports Kotlin for Android

Google officially supports Kotlin because it helps developers:

  • Write cleaner code
  • Reduce bugs
  • Improve productivity
  • Build scalable Android applications

Modern Android development now heavily relies on Kotlin-first libraries such as:

  • Jetpack Compose
  • Coroutines
  • Flow
  • KTX Extensions

Major Advantages of Kotlin


1. Concise Code

Kotlin reduces boilerplate code significantly compared to Java.

Example — Button Click Listener in Java:


button.setOnClickListener(
    new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // Action
        }
    }
);

The same implementation in Kotlin:


button.setOnClickListener {

    // Action
}

Kotlin code is shorter, cleaner, and easier to read.


2. Null Safety

One of Kotlin’s biggest advantages is built-in null safety.

In Java, NullPointerException is one of the most common runtime crashes.

Kotlin helps prevent many null-related crashes during compile time.

Example:


var name: String = "Android"

name = null

The above code produces a compilation error because Kotlin does not allow null assignment to non-nullable variables.


3. Full Java Interoperability

Kotlin is 100% interoperable with Java.

Developers can:

  • Use Java libraries in Kotlin
  • Use Kotlin code inside Java projects
  • Migrate projects gradually

4. Improved Readability

Kotlin focuses heavily on developer productivity and readability.

Features like:

  • Type inference
  • Data classes
  • Extension functions
  • Lambda expressions

make Android development more efficient.


5. Coroutines for Asynchronous Programming

Kotlin Coroutines simplify asynchronous programming significantly.

Instead of complicated callback structures, developers can write cleaner asynchronous code.

Example:


lifecycleScope.launch {

    val data = repository.getData()

    updateUI(data)
}

Kotlin vs Java

Java Kotlin
More boilerplate code Concise syntax
NullPointerExceptions common Built-in null safety
Verbose callbacks Coroutines support
Older Android standard Modern Android standard
Longer development time Faster development

Performance of Kotlin

Kotlin applications run efficiently because Kotlin compiles into JVM bytecode similar to Java.

Performance is generally:

  • Comparable to Java
  • Optimized for Android runtime
  • Efficient with inline functions and lambdas

Compilation Time

Kotlin supports incremental compilation.

Although clean builds may sometimes be slower than Java, incremental builds are usually very fast in Android Studio.


Learning Kotlin for Android Development

Kotlin is relatively easy for Java developers because syntax and concepts are familiar.

Recommended learning order:

  1. Variables and data types
  2. Functions
  3. Classes and objects
  4. Null safety
  5. Collections
  6. Lambdas
  7. Coroutines
  8. Android development with Kotlin

Using Kotlin in Android Studio

Modern Android Studio versions provide built-in Kotlin support.

Developers can:

  • Create Kotlin projects directly
  • Convert Java code to Kotlin
  • Use Kotlin templates
  • Access Kotlin-first Jetpack libraries

Common Mistakes Beginners Make

1. Treating Kotlin Like Java

Many beginners write Java-style code in Kotlin instead of using Kotlin features properly.


2. Ignoring Null Safety

Improper use of nullable types defeats Kotlin’s safety advantages.


3. Overusing !! Operator

Using:


!!

forces null values and may still crash applications.


Modern Android Technologies Built Around Kotlin

  • Jetpack Compose
  • Kotlin Coroutines
  • Flow & StateFlow
  • Hilt Dependency Injection
  • Ktor
  • Kotlin Multiplatform

FAQ

Is Kotlin better than Java for Android?

For modern Android development, Kotlin is generally preferred because of cleaner syntax, null safety, and coroutine support.

Can Java developers learn Kotlin easily?

Yes. Kotlin is designed to be easy for Java developers to adopt.

Should beginners learn Java first?

New Android developers can directly start with Kotlin because it is the modern recommended language.


Conclusion

Kotlin has transformed Android development by providing a modern, concise, and safer programming language.

Its interoperability with Java and strong Android ecosystem support make it one of the best choices for building modern Android applications.

Developers who learn Kotlin gain access to modern Android architecture tools, cleaner code practices, and faster development workflows.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

Build a Modern Navigation Drawer App in Android Studio Using Fragments

No comments email this post Edit Post

Navigation Drawer is one of the most commonly used UI patterns in Android applications.

It provides:

  • Easy navigation
  • Modern Material Design UI
  • Fragment switching
  • Organized app structure
  • Better user experience

In this tutorial, we will build a complete Navigation Drawer Android application using:

  • NavigationView
  • DrawerLayout
  • Fragments
  • Toolbar
  • ScrollView
  • TableLayout
  • Spinner
  • HorizontalScrollView

What We Will Build

This project will include:

  • Navigation Drawer menu
  • Fragment navigation
  • Student dashboard UI
  • Time Table screen
  • Exam Schedule screen
  • Attendance screen
  • Social media links
  • Responsive layouts

Important Modern Android Note

The original project uses:


android.support.*

which is deprecated.

Modern Android applications should now use:


androidx.*

along with:


Material Design Components

Step 1 — Create a Navigation Drawer Activity

Open Android Studio and create a new project.

Select:


Navigation Drawer Activity

Android Studio automatically generates:

  • DrawerLayout
  • NavigationView
  • Toolbar
  • Menu resources
  • Navigation structure

Modern Dependencies

Inside:


build.gradle

add:


implementation
'com.google.android.material:material:1.11.0'

implementation
'androidx.navigation:navigation-fragment:2.7.7'

implementation
'androidx.navigation:navigation-ui:2.7.7'

What Is NavigationView?

NavigationView is a Material Design component used inside DrawerLayout to display a side navigation menu.

It supports:

  • Menu items
  • Icons
  • Header layouts
  • Nested menus
  • Material styling

NavigationView Example


<com.google.android.material.navigation.NavigationView

    android:id="@+id/nav_view"

    android:layout_width="wrap_content"

    android:layout_height="match_parent"

    android:layout_gravity="start"

    app:headerLayout="@layout/nav_header_main"

    app:menu="@menu/activity_main_drawer"/>

Understanding Navigation Drawer Menu

Navigation Drawer menus are defined inside:


res/menu/activity_main_drawer.xml

Menu structure:

  • menu → root container
  • group → grouped menu items
  • item → individual menu item
  • submenu → nested menu

Menu Example


<menu xmlns:android=
"http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

        <item
            android:id="@+id/home"
            android:title="Home"/>

        <item
            android:id="@+id/timeTable"
            android:title="Time Table"/>

        <item
            android:id="@+id/examSchedule"
            android:title="Exam Schedule"/>

    </group>

</menu>

What Is Fragment Navigation?

Fragments allow multiple screens inside a single Activity.

Advantages:

  • Reusable UI
  • Better architecture
  • Modular screens
  • Dynamic navigation
  • Improved performance

Handling Navigation Item Clicks

Menu item clicks are handled using:


setNavigationItemSelectedListener()

Modern Fragment Navigation Example


navigationView
.setNavigationItemSelectedListener(item -> {

    Fragment fragment = null;

    int id = item.getItemId();

    if (id == R.id.home) {

        fragment = new HomeFragment();

    } else if (id == R.id.timeTable) {

        fragment = new TimeTableFragment();

    }

    if (fragment != null) {

        getSupportFragmentManager()
            .beginTransaction()
            .replace(
                R.id.content_frame,
                fragment
            )
            .commit();
    }

    drawerLayout.closeDrawers();

    return true;
});

Why Use Fragments?

  • Cleaner architecture
  • Single Activity design
  • Easier maintenance
  • Reusable screens
  • Navigation flexibility

Creating HomeFragment

Example:


public class HomeFragment
        extends Fragment {

    @Override
    public View onCreateView(
            LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState
    ) {

        return inflater.inflate(
                R.layout.home,
                container,
                false
        );
    }
}

Building the Home Dashboard UI

The Home screen can contain:

  • Student details
  • Important information
  • Buttons
  • HorizontalScrollView
  • Announcements
  • Cards

Using LinearLayout

LinearLayout arranges views:

  • Vertically
  • Horizontally

Student Info Layout Example


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:text="Student Name"/>

</LinearLayout>

Using ScrollView

ScrollView allows vertical scrolling for large content.

Important:


ScrollView can have only one direct child.

HorizontalScrollView

HorizontalScrollView enables horizontal scrolling.

Useful for:

  • Category buttons
  • Tabs
  • Quick actions
  • Cards

HorizontalScrollView Example


<HorizontalScrollView>

    <LinearLayout
        android:orientation="horizontal">

        <Button
            android:text="Time Table"/>

        <Button
            android:text="Attendance"/>

    </LinearLayout>

</HorizontalScrollView>

Handling Button Clicks in Fragment


public class HomeFragment
        extends Fragment
        implements View.OnClickListener {
}

Button Click Example


@Override
public void onClick(View v) {

    switch (v.getId()) {

        case R.id.btnTimeTable:

            Fragment fragment =
                    new TimeTableFragment();

            getActivity()
                .getSupportFragmentManager()
                .beginTransaction()
                .replace(
                    R.id.content_frame,
                    fragment
                )
                .commit();

            break;
    }
}

Building TimeTableFragment

Time tables can be created using:

  • TableLayout
  • TableRow
  • TextView

What Is TableLayout?

TableLayout arranges UI in rows and columns.

Useful for:

  • Schedules
  • Reports
  • Attendance tables
  • Timetables

TableLayout Example


<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TableRow>

        <TextView
            android:text="Math"/>

        <TextView
            android:text="10:00 AM"/>

    </TableRow>

</TableLayout>

Building ExamScheduleFragment

Exam schedules can be displayed using:

  • ScrollView
  • LinearLayout
  • TextViews

Building AttendanceFragment

Attendance screen uses:

  • Spinner
  • TextView
  • Dynamic data display

What Is Spinner?

Spinner is a dropdown selection component in Android.


Spinner Example


Spinner spinner =
    view.findViewById(R.id.semSpinner);

Adding Data to Spinner


ArrayAdapter<CharSequence> adapter =
    ArrayAdapter.createFromResource(

        getContext(),

        R.array.semesters,

        android.R.layout
        .simple_spinner_item
);

Modern Android Recommendations

Modern Android applications now commonly use:

  • Jetpack Navigation Component
  • ViewBinding
  • RecyclerView
  • ConstraintLayout
  • Material Design 3
  • MVVM Architecture
  • Jetpack Compose

Why Avoid Older Android Support Libraries?

Older:


android.support.*

libraries are deprecated.

AndroidX provides:

  • Better support
  • Improved performance
  • Modern APIs
  • Future compatibility

Best Practices

1. Use Fragments Properly

Keep fragments modular and reusable.


2. Use RecyclerView Instead of Large ScrollViews

RecyclerView improves performance for large lists.


3. Use ViewBinding

Avoid excessive:


findViewById()

calls in modern Android apps.


4. Use Material Design Components

Material Design improves UI consistency and accessibility.


Common Beginner Mistakes

1. Using Too Many Nested Layouts

Deep layout nesting reduces performance.


2. Forgetting Fragment Back Stack

Use:


addToBackStack()

for proper navigation behavior.


3. Using Deprecated APIs

Always prefer AndroidX libraries.


FAQ

What is Navigation Drawer in Android?

Navigation Drawer is a side menu used for navigating between screens.


Why use Fragments?

Fragments provide modular and reusable UI components.


What is the modern alternative?

Jetpack Navigation Component and Jetpack Compose Navigation are modern recommended approaches.


Conclusion

Navigation Drawer remains one of the most powerful Android UI navigation patterns.

Using Fragments, NavigationView, DrawerLayout, and Material Design components allows developers to build scalable and professional Android applications.

Modern Android applications should combine AndroidX, Material Design 3, responsive layouts, and clean architecture patterns for production-grade development.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.