Skip to main content

How to Build an Offline Mobile App with React Native, Expo, and SQLite


In this article, we will discuss how to create an expense tracker mobile app using React Native, Expo, and a smartphone's local SQLite database. SQLite is similar to MySQL but is designed for mobile and embedded applications. Every smartphone has a local SQLite database that apps can use. However, locating these databases on your device can be tricky because they are stored within the app's sandbox, and each app has its own sandboxed storage.

In this guide, we will focus on an offline expense tracker that stores your expense data in a local SQLite database. For this example, we have named the database my.db. The app stores information such as the expense ID, day, date, expense amount, and any optional comments related to the expense.

Within the my.db database, we have created two tables: users and todos. The users table stores the id, day, date, and expense amount, while the todos table stores the comments. The two tables are linked using a foreign key, allowing the app to display comments associated with specific expenses, if any have been added.


Code for Creating a Database


import * as SQLite from 'expo-sqlite';

const db = SQLite.openDatabase('mydb.db'); 

export const initDB = () => {
  db.transaction(tx => {
    // Enable foreign key constraints
    tx.executeSql('PRAGMA foreign_keys = ON;');

    // Users table
    tx.executeSql(
      `CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        day TEXT,
        date TEXT,
        amount REAL
      );`
    );

    // Todos table (linked to users)
    tx.executeSql(
      `CREATE TABLE IF NOT EXISTS todos (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER,
        title TEXT,
        description TEXT,
        FOREIGN KEY(user_id) REFERENCES users(id)
      );`
    );
  });
};

export default db;

See how to render the SQLite data

import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, Button } from 'react-native';
import * as SQLite from "expo-sqlite";

let db;
(async () => {
  db = await SQLite.openDatabaseAsync("mydb.db");
})();

const getUsersWithTodos = async (callback) => {
  if (!db) return;

  const users = await db.getAllAsync(`SELECT * FROM users;`);
  const todos = await db.getAllAsync(`SELECT * FROM todos;`);

  const usersWithTodos = users.map(user => ({
    ...user,
    todos: todos.filter(t => t.user_id === user.id),
  }));

  const totalAmount = users.reduce((sum, u) => sum + (u.amount || 0), 0);

  callback({ data: usersWithTodos, totalAmount });
};

const currencySymbols = {
  USD: '$',
  GBP: '£',
  EUR: '€',
  JPY: '¥',
  INR: '₹',
};

const UserList = ({ refreshFlag, currency }) => {
  const [usersData, setUsersData] = useState({ data: [], totalAmount: 0 });

  useEffect(() => {
    getUsersWithTodos(setUsersData);
  }, [refreshFlag]);

  const formatCurrency = (amount) =>
    `${currencySymbols[currency] || ''}${amount.toFixed(2)}`;

  const deleteUser = async (id) => {
    if (!db) return;

    await db.runAsync(`DELETE FROM users WHERE id = ?;`, [id]);
    await db.runAsync(`DELETE FROM todos WHERE user_id = ?;`, [id]);

    getUsersWithTodos(setUsersData);
  };

  return (
    
      Expenses
      
        Total Amount: {formatCurrency(usersData.totalAmount)}
      

      {usersData.data.map(user => (
        
          ID: {user.id}
          Day: {user.day}
          Date: {user.date}
          Amount: {formatCurrency(user.amount)}
          {user.todos.length > 0 ? (
            user.todos.map((t, idx) => (
              Comment: {t.title} - {t.description}
            ))
          ) : (
            No Comment
          )}
          
      ))}
    
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: '#fff' },
  title: { fontSize: 22, fontWeight: 'bold', marginBottom: 8 },
  total: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 12,
    color: '#1e3a8a',
  },
  item: {
    backgroundColor: '#f3f4f6',
    padding: 12,
    borderRadius: 8,
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#d1d5db',
  },
});

export default UserList;
export { getUsersWithTodos, db };
 

How to Render Data from a Local SQLite Database

To retrieve and render data from the local SQLite database (mydb.db), we use simple SQL queries. For example:


const users = await db.getAllAsync(`SELECT * FROM users;`);
const todos = await db.getAllAsync(`SELECT * FROM todos;`);
    

These commands execute SQL SELECT statements to fetch all records from the users and todos tables, respectively.


Visit Github

Further Reading

  1.     

People are good at skipping over material they already know!

View Related Topics to







Contact Us

Name

Email *

Message *

Popular Posts

Online Simulator for ASK, FSK, and PSK

Try our new Digital Signal Processing Simulator!   Start Simulator for binary ASK Modulation Message Bits (e.g. 1,0,1,0) Carrier Frequency (Hz) Sampling Frequency (Hz) Run Simulation Simulator for binary FSK Modulation Input Bits (e.g. 1,0,1,0) Freq for '1' (Hz) Freq for '0' (Hz) Sampling Rate (Hz) Visualize FSK Signal Simulator for BPSK Modulation ...

Constellation Diagrams of ASK, PSK, and FSK

📘 Overview of Energy per Bit (Eb / N0) 🧮 Online Simulator for constellation diagrams of ASK, FSK, and PSK 🧮 Theory behind Constellation Diagrams of ASK, FSK, and PSK 🧮 MATLAB Codes for Constellation Diagrams of ASK, FSK, and PSK 📚 Further Reading 📂 Other Topics on Constellation Diagrams of ASK, PSK, and FSK ... 🧮 Simulator for constellation diagrams of m-ary PSK 🧮 Simulator for constellation diagrams of m-ary QAM BASK (Binary ASK) Modulation: Transmits one of two signals: 0 or -√Eb, where Eb​ is the energy per bit. These signals represent binary 0 and 1.    BFSK (Binary FSK) Modulation: Transmits one of two signals: +√Eb​ ( On the y-axis, the phase shift of 90 degrees with respect to the x-axis, which is also termed phase offset ) or √Eb (on x-axis), where Eb​ is the energy per bit. These signals represent binary 0 and 1.  BPSK (Binary PSK) Modulation: Transmits one of two signals...

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...

📘 Overview of BER and SNR 🧮 Online Simulator for BER calculation of m-ary QAM and m-ary PSK 🧮 MATLAB Code for BER calculation of M-ary QAM, M-ary PSK, QPSK, BPSK, ... 📚 Further Reading 📂 View Other Topics on M-ary QAM, M-ary PSK, QPSK ... 🧮 Online Simulator for Constellation Diagram of m-ary QAM 🧮 Online Simulator for Constellation Diagram of m-ary PSK 🧮 MATLAB Code for BER calculation of ASK, FSK, and PSK 🧮 MATLAB Code for BER calculation of Alamouti Scheme 🧮 Different approaches to calculate BER vs SNR What is Bit Error Rate (BER)? The abbreviation BER stands for Bit Error Rate, which indicates how many corrupted bits are received (after the demodulation process) compared to the total number of bits sent in a communication process. BER = (number of bits received in error) / (total number of tran...

Q-function in BER vs SNR Calculation

Q-function in BER vs. SNR Calculation In the context of Bit Error Rate (BER) and Signal-to-Noise Ratio (SNR) calculations, the Q-function plays a significant role, especially in digital communications and signal processing . What is the Q-function? The Q-function is a mathematical function that represents the tail probability of the standard normal distribution. Specifically, it is defined as: Q(x) = (1 / sqrt(2Ī€)) ∫ₓ∞ e^(-t² / 2) dt In simpler terms, the Q-function gives the probability that a standard normal random variable exceeds a value x . This is closely related to the complementary cumulative distribution function of the normal distribution. The Role of the Q-function in BER vs. SNR The Q-function is widely used in the calculation of the Bit Error Rate (BER) in communication systems, particularly in systems like Binary Phase Shift Ke...

Channel Impulse Response (CIR)

📘 Overview & Theory 📘 How CIR Affects the Signal 🧮 Online Channel Impulse Response Simulator 🧮 MATLAB Codes 📚 Further Reading What is the Channel Impulse Response (CIR)? The Channel Impulse Response (CIR) is a concept primarily used in the field of telecommunications and signal processing. It provides information about how a communication channel responds to an impulse signal. It describes the behavior of a communication channel in response to an impulse signal. In signal processing, an impulse signal has zero amplitude at all other times and amplitude ∞ at time 0 for the signal. Using a Dirac Delta function, we can approximate this. Fig: Dirac Delta Function The result of this calculation is that all frequencies are responded to equally by δ(t) . This is crucial since we never know which frequenci...

Gaussian minimum shift keying (GMSK)

📘 Overview & Theory 🧮 Simulator for GMSK 🧮 MSK and GMSK: Understanding the Relationship 🧮 MATLAB Code for GMSK 📚 Simulation Results for GMSK 📚 Q & A and Summary 📚 Further Reading Dive into the fascinating world of GMSK modulation, where continuous phase modulation and spectral efficiency come together for robust communication systems! Core Process of GMSK Modulation Phase Accumulation (Integration of Filtered Signal) After applying Gaussian filtering to the Non-Return-to-Zero (NRZ) signal, we integrate the smoothed NRZ signal over time to produce a continuous phase signal: θ(t) = ∫ 0 t m filtered (Ī„) dĪ„ This integration is crucial for avoiding abrupt phase transitions, ensuring smooth and continuous phase changes. Phase Modulation The next step involves using the phase signal to modulate a...

LDPC Encoding and Decoding Techniques

📘 Overview & Theory 🧮 LDPC Encoding Techniques 🧮 LDPC Decoding Techniques 📚 Further Reading 'LDPC' is the abbreviation for 'low density parity check'. LDPC code H matrix contains very few amount of 1's and mostly zeroes. LDPC codes are error correcting code. Using LDPC codes, channel capacities that are close to the theoretical Shannon limit can be achieved.  Low density parity check (LDPC) codes are linear error-correcting block code suitable for error correction in a large block sizes transmitted via very noisy channel. Applications requiring highly reliable information transport over bandwidth restrictions in the presence of noise are increasingly using LDPC codes. 1. LDPC Encoding Technique The proper form of H matrix is derived from the given matrix by doing multiple row operations as shown above. In the above, H is parity check matrix and G is generator matrix. If you consider matrix H as [-P' | I] then matrix G will b...

MATLAB code for Pulse Code Modulation (PCM) and Demodulation

📘 Overview & Theory 🧮 Quantization in Pulse Code Modulation (PCM) 🧮 MATLAB Code for Pulse Code Modulation (PCM) 🧮 MATLAB Code for Pulse Amplitude Modulation and Demodulation of Digital data 🧮 Other Pulse Modulation Techniques (e.g., PWM, PPM, DM, and PCM) 📚 Further Reading MATLAB Code for Pulse Code Modulation clc; close all; clear all; fm=input('Enter the message frequency (in Hz): '); fs=input('Enter the sampling frequency (in Hz): '); L=input('Enter the number of the quantization levels: '); n = log2(L); t=0:1/fs:1; % fs nuber of samples have tobe selected s=8*sin(2*pi*fm*t); subplot(3,1,1); t=0:1/(length(s)-1):1; plot(t,s); title('Analog Signal'); ylabel('Amplitude--->'); xlabel('Time--->'); subplot(3,1,2); stem(t,s);grid on; title('Sampled Sinal'); ylabel('Amplitude--->'); xlabel('Time--->'); % Quantization Process vmax=8; vmin=-vmax; %to quanti...