Storing, Sharing & Retrieving Data in Android Applications & Jetpack Components (Android)


Overview of Data Storage in Android

Android provides multiple ways to store data depending on data size, security, and sharing needs.

Storing, Sharing & Retrieving Data in Android Applications & Jetpack Components (Android)

Types of Data Storage

Storage Type Description Use Case
Shared Preferences Key-value pairs App settings, small data
Internal Storage Private files Sensitive app data
External Storage Public/shared files Media files
SQLite Database Structured relational data Complex data
Content Providers Data sharing across apps Contacts, media
Room Database ORM over SQLite Modern apps

Storage Decision Diagram

Data Size?
|
--------------------------
| |
Small Large
| |
SharedPreferences Structured?
|
---------------------
| |
Yes No
| |
SQLite DB Files Storage

Shared Preferences (App Settings)

Used for storing small amounts of primitive data.

Features

  • Stores data as key-value pairs
  • Private to the application
  • Persistent storage

Example Data

  • Username
  • Theme settings
  • Login status

Code Example

SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

editor.putString("username", "Jay");
editor.putBoolean("isLoggedIn", true);
editor.apply();

Retrieve Data

String user = prefs.getString("username", "default");
boolean status = prefs.getBoolean("isLoggedIn", false);

Shared Preferences Table

Method Description
putString() Store string
putInt() Store integer
getString() Retrieve string
apply() Save asynchronously
commit() Save synchronously

Internal Storage

Features

  • Stored in device memory
  • Private to app
  • Automatically deleted on uninstall

Code Example

FileOutputStream fos = openFileOutput("file.txt", MODE_PRIVATE);
fos.write("Hello Android".getBytes());
fos.close();

External Storage

Features

  • Shared storage (SD card or public folder)
  • Requires permission

Permissions

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

Internal vs External Storage

Feature Internal External
Security High Low
Accessibility App only All apps
Storage Size Limited Large

SQLite Database in Android

SQLite is a lightweight relational database.

Features

  • Embedded DB
  • No server required
  • Supports SQL queries

Database Structure Diagram

Database
|
|-- Table (Students)
|-- id (PK)
|-- name
|-- marks

SQLiteOpenHelper Example

public class DBHelper extends SQLiteOpenHelper {

public DBHelper(Context context) {
super(context, "StudentDB", null, 1);
}

public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE students(id INTEGER PRIMARY KEY, name TEXT, marks INTEGER)");
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS students");
onCreate(db);
}
}

Insert Data

SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();

values.put("name", "Jay");
values.put("marks", 90);

db.insert("students", null, values);

Query Data

Cursor cursor = db.rawQuery("SELECT * FROM students", null);

while(cursor.moveToNext()) {
String name = cursor.getString(1);
}

SQLite Operations

Operation Method
Insert insert()
Read query(), rawQuery()
Update update()
Delete delete()

Content Providers

Used to share data between apps.

🔹 Examples

  • Contacts
  • Media files

Architecture Diagram

App A ---> Content Resolver ---> Content Provider ---> Database
App B ---> Content Resolver ---> Content Provider ---> Database

Key Components

Component Role
Content Provider Manages data
Content Resolver Access data
URI Identifies data

Example URI

content://contacts/people

Content Resolver

Acts as a bridge between app and Content Provider.

Example

Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null, null, null, null
);

Loaders (Data Loading)

Used for asynchronous data loading.

Why Loaders?

  • Prevent UI blocking
  • Auto reload data on change
  • Lifecycle-aware

Loader Workflow Diagram

Activity/Fragment
|
LoaderManager
|
Loader
|
Data Source (DB/Provider)

Types of Loaders

Loader Type Description
AsyncTaskLoader Background thread
CursorLoader Load DB data

Example: LoaderManager.getInstance(this).initLoader(1, null, this);

Comparison of Storage Methods

Feature SharedPref SQLite Files
Data Type Key-value Structured Unstructured
Size Small Large Large
Speed Fast Moderate Fast
Use Case Settings Complex data Media

Important Exam Questions

1. Short Questions

  • What is SharedPreferences?
  • Define Content Provider.
  • Difference between internal & external storage.

2. Long Questions

  • Explain SQLite database with example.
  • Describe Content Resolver & its working.
  • Explain Loaders with lifecycle.

3. Practical Questions

  • Write code to store data in SharedPreferences.
  • Insert and retrieve data from SQLite.

Jetpack Components (Android)

Jetpack is a suite of libraries, tools, and architectural guidance to build robust Android apps.

Fragments: A Fragment is a reusable portion of UI in an Activity.

Features

  • Has its own lifecycle
  • Can be reused in multiple activities
  • Supports dynamic UI

Fragment Lifecycle Diagram

onAttach()

onCreate()

onCreateView()

onViewCreated()

onStart()

onResume()

----------------

onPause()

onStop()

onDestroyView()

onDestroy()

Example

public class MyFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_layout, container, false);
}
}

Jetpack Navigation

Handles navigation between fragments using a navigation graph.

Navigation Architecture

Activity
|
NavHostFragment
|
NavController
|
Navigation Graph (XML)

Key Components

Component Description
NavHost Container
NavController Manages navigation
Navigation Graph Defines paths

Example

NavController navController = Navigation.findNavController(this, R.id.nav_host);
navController.navigate(R.id.secondFragment);

Lifecycle

Lifecycle represents states of Activity/Fragment.

Lifecycle States

State Description
Created Object created
Started Visible
Resumed Active
Destroyed Removed

Lifecycle Owner

A class that has a lifecycle.

Examples:

  • Activity
  • Fragment

Interface

public interface LifecycleOwner {
Lifecycle getLifecycle();
}

Lifecycle Observer

Observes lifecycle changes.

Example

public class MyObserver implements LifecycleObserver {

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
// do something
}
}

View Model

Stores UI-related data in a lifecycle-conscious way.

Features

  • Survives configuration changes
  • Separates UI from data

Diagram

Activity/Fragment
|
ViewModel
|
Data

Example

public class MyViewModel extends ViewModel {
String data = "Hello";
}

View Model Provider

Used to create or retrieve ViewModel.

Example

MyViewModel vm = new ViewModelProvider(this).get(MyViewModel.class);

View Model Factory

Used when ViewModel needs parameters.

Example

public class MyFactory implements ViewModelProvider.Factory {
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new MyViewModel("data");
}
}

LiveData

Observable data holder class.

Features
  • Lifecycle-aware
  • Auto updates UI

LiveData Flow

Data Source → LiveData → Observer (UI)

Example

MutableLiveData<String> liveData = new MutableLiveData<>();

liveData.observe(this, data -> {
textView.setText(data);
});

Room API

SQLite abstraction library.

Components

Component Description
Entity Table
DAO Queries
Database Holder

Room Architecture

Entity → DAO → Room DB → App

Example

@Entity
class User {
@PrimaryKey int id;
String name;
}

Data Binding

Binds UI components with data directly.

Advantages

  • Reduces boilerplate code
  • Improves performance

Example

<TextView android:text="@{user.name}" />

View Binding

Generates binding class for layouts.

Example

ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());

binding.textView.setText("Hello");

Data Binding vs View Binding

Feature Data Binding View Binding
Logic in XML Yes No
Performance Slightly slower Faster
Complexity High Simple

MVVM Architecture

Model-View-ViewModel pattern.

MVVM Diagram

View (Activity/Fragment)
|
ViewModel
|
Model (DB/API)

Flow

  1. View observes LiveData
  2. ViewModel processes data
  3. Model provides data

Advantage

  • Separation of concerns
  • Testable code
  • Lifecycle aware

Combined Architecture Diagram

View (UI)
|
LiveData
|
ViewModel
|
Repository
|
Room / API

Important Exam Question

Short Questions

  • What is ViewModel?
  • Define LiveData.
  • Difference between Data Binding and View Binding.

Long Questions

  • Explain MVVM architecture with diagram.
  • Describe Room Database components.
  • Explain Navigation component.

Practical Questions

  • Write code for LiveData observer.
  • Implement ViewModel with Factory.

Final Summary

  • Fragment → UI component
  • Navigation → screen movement
  • ViewModel → data holder
  • LiveData → observable data
  • Room → database
  • MVVM → architecture pattern
  • SharedPreferences → small settings