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 TypeDescriptionUse Case
Shared PreferencesKey-value pairsApp settings, small data
Internal StoragePrivate filesSensitive app data
External StoragePublic/shared filesMedia files
SQLite DatabaseStructured relational dataComplex data
Content ProvidersData sharing across appsContacts, media
Room DatabaseORM over SQLiteModern 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

MethodDescription
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

FeatureInternalExternal
SecurityHighLow
AccessibilityApp onlyAll apps
Storage SizeLimitedLarge

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

OperationMethod
Insertinsert()
Readquery(), rawQuery()
Updateupdate()
Deletedelete()

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

ComponentRole
Content ProviderManages data
Content ResolverAccess data
URIIdentifies 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 TypeDescription
AsyncTaskLoaderBackground thread
CursorLoaderLoad DB data

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

Comparison of Storage Methods

FeatureSharedPrefSQLiteFiles
Data TypeKey-valueStructuredUnstructured
SizeSmallLargeLarge
SpeedFastModerateFast
Use CaseSettingsComplex dataMedia

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

ComponentDescription
NavHostContainer
NavControllerManages navigation
Navigation GraphDefines 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

StateDescription
CreatedObject created
StartedVisible
ResumedActive
DestroyedRemoved

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

ComponentDescription
EntityTable
DAOQueries
DatabaseHolder

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

FeatureData BindingView Binding
Logic in XMLYesNo
PerformanceSlightly slowerFaster
ComplexityHighSimple

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