In our previous tutorial’s we had learn about SQLite database and perform data insertion using Text Input component into SQLite. Today we would learn about View All Data From SQLite Database in React Native into FlatList component. If you read our previous tutorial then you’ll know back there we would use only single screen but today we would require 2 screens for our application. First screen for inserting data and second screen for showing all SQLite data into FlatList component. So we are using React Navigation library here to create multiple activity screen structure. It is necessary to install both NavigationContainer and createStackNavigator components in current project in order to use multiple screens.
React Native plugins we’re using in this tutorial:
- React Navigation – NavigationContainer and createStackNavigator to use multiple screens.
- react-native-sqlite-storage – To use SQLite database in react native Android iOS platforms.
Contents in this project View All Data From SQLite Database in React Native FlatList Example:
1. Open our React Navigation 5.x installation guide tutorial and from there follow step 1, 2 and 3 to install both NavigationContainer and createStackNavigator components in your project.
2. Open our previous tutorial about Creating SQLite database and from there follow step 1 and 2 to install the React Native SQLite Storage plugin in your project.
3. After done following both above steps, Next step is to open your project’s main App.js file and import useState, useEffect, SafeAreaView, Text, View, StyleSheet, Alert, TouchableOpacity, TextInput, FlatList, openDatabase, NavigationContainer and createStackNavigator components in your project.
1 2 3 4 5 6 7 8 9 |
import React, { useState, useEffect } from 'react'; import { SafeAreaView, Text, View, StyleSheet, Alert, TouchableOpacity, TextInput, FlatList } from 'react-native'; import { openDatabase } from 'react-native-sqlite-storage'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; |
4. Creating a openDatabase object named as db and here we would make our SQLite database named as SchoolDatabase.db .
1 |
var db = openDatabase({ name: 'SchoolDatabase.db' }); |
5. Creating our first screen component named as HomeScreen with navigation.
Explaination:
- S_Name : This state is used to get Student name from Text Input component.
- setName : Used to change S_Name state value.
- S_Phone : Used to get Student phone number from Text Input component.
- setPhone : To change S_Phone value.
- S_Address : Used to hold the student address from Text Input component.
- setAddress : To change S_Address value.
- useEffect() : We are using useEffect as Component did mount method and here we’re creating Table named as Student_Table in SQLite database. The table has 4 fields named as student_id, student_name , student_phone and student_address.
- insertData() : This function is used to enter data into SQLite database.
- navigateToViewScreen() : Used to navigate to next screen where we would display all the entered records in database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
function HomeScreen({ navigation }) { const [S_Name, setName] = useState(''); const [S_Phone, setPhone] = useState(); const [S_Address, setAddress] = useState(''); useEffect(() => { db.transaction(function (txn) { txn.executeSql( "SELECT name FROM sqlite_master WHERE type='table' AND name='Student_Table'", [], function (tx, res) { console.log('item:', res.rows.length); if (res.rows.length == 0) { txn.executeSql('DROP TABLE IF EXISTS Student_Table', []); txn.executeSql( 'CREATE TABLE IF NOT EXISTS Student_Table(student_id INTEGER PRIMARY KEY AUTOINCREMENT, student_name VARCHAR(30), student_phone INT(15), student_address VARCHAR(255))', [] ); } } ); }) }, []); const insertData = () => { if (S_Name == '' || S_Phone == '' || S_Address == '') { Alert.alert('Please Enter All the Values'); } else { db.transaction(function (tx) { tx.executeSql( 'INSERT INTO Student_Table (student_name, student_phone, student_address) VALUES (?,?,?)', [S_Name, S_Phone, S_Address], (tx, results) => { console.log('Results', results.rowsAffected); if (results.rowsAffected > 0) { Alert.alert('Data Inserted Successfully....'); } else Alert.alert('Failed....'); } ); }); } } navigateToViewScreen = () => { navigation.navigate('ViewAllStudentScreen'); } return ( <SafeAreaView style={{ flex: 1 }}> <View style={styles.mainContainer}> <Text style={{ fontSize: 24, textAlign: 'center', color: '#000' }}> Insert Data Into SQLite Database </Text> <TextInput style={styles.textInputStyle} onChangeText={ (text) => setName(text) } placeholder="Enter Student Name" value={S_Name} /> <TextInput style={styles.textInputStyle} onChangeText={ (text) => setPhone(text) } placeholder="Enter Student Phone Number" keyboardType={'numeric'} value={S_Phone} /> <TextInput style={[styles.textInputStyle, { marginBottom: 20 }]} onChangeText={ (text) => setAddress(text) } placeholder="Enter Student Address" value={S_Address} /> <TouchableOpacity style={styles.touchableOpacity} onPress={insertData}> <Text style={styles.touchableOpacityText}> Click Here To Insert Data Into SQLite Database </Text> </TouchableOpacity> <TouchableOpacity style={[styles.touchableOpacity, { marginTop: 20, backgroundColor: '#33691E' }]} onPress={navigateToViewScreen}> <Text style={styles.touchableOpacityText}> Click Here View All Students List </Text> </TouchableOpacity> </View> </SafeAreaView> ); }; |
6. Creating our Second screen named as ViewAllStudentScreen with navigation. In this functional component we would display all the entered records in SQLite database in FlatList component.
Explaination:
- items : Items state is used to hold all the data we get from SQLite database.
- setItems : Used to update the items State value.
- empty : empty state is used to determine whether the items state is empty or not and according to that display a empty message on screen.
- setEmpty : To update empty state value.
- useEffect() : here we would execute the SELECT * FROM Student_Table query and pop up all the records form SQLite database and enter into items state.
- listViewItemSeparator() : To display a horizontal divider line between each Flat List item.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
function ViewAllStudentScreen({ navigation }) { const [items, setItems] = useState([]); const [empty, setEmpty] = useState([]); useEffect(() => { db.transaction((tx) => { tx.executeSql( 'SELECT * FROM Student_Table', [], (tx, results) => { var temp = []; for (let i = 0; i < results.rows.length; ++i) temp.push(results.rows.item(i)); setItems(temp); if (results.rows.length >= 1) { setEmpty(false); } else { setEmpty(true) } } ); }); }, []); const listViewItemSeparator = () => { return ( <View style={{ height: 1, width: '100%', backgroundColor: '#000' }} /> ); }; const emptyMSG = (status) => { return ( <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ fontSize: 25, textAlign: 'center' }}> No Record Inserted Database is Empty... </Text> </View> ); } return ( <SafeAreaView style={{ flex: 1 }}> <View style={{ flex: 1 }}> {empty ? emptyMSG(empty) : <FlatList data={items} ItemSeparatorComponent={listViewItemSeparator} keyExtractor={(item, index) => index.toString()} renderItem={({ item }) => <View key={item.student_id} style={{ padding: 20 }}> <Text style={styles.itemsStyle}> Id: {item.student_id} </Text> <Text style={styles.itemsStyle}> Name: {item.student_name} </Text> <Text style={styles.itemsStyle}> Phone Number: {item.student_phone} </Text> <Text style={styles.itemsStyle}> Address: {item.student_address} </Text> </View> } /> } </View> </SafeAreaView> ); } |
7. Making createStackNavigator() component object named as stack and now we would make our main export default function named as App(). Here we would make NavigationContainer component and define both screen here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const Stack = createStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="HomeScreen" component={HomeScreen} /> <Stack.Screen name="ViewAllStudentScreen" component={ViewAllStudentScreen} /> </Stack.Navigator> </NavigationContainer> ); } |
8. Creating Style.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
const styles = StyleSheet.create({ mainContainer: { flex: 1, alignItems: 'center', padding: 10, }, touchableOpacity: { backgroundColor: '#0091EA', alignItems: 'center', borderRadius: 8, justifyContent: 'center', alignItems: 'center', width: '100%' }, touchableOpacityText: { color: '#FFFFFF', fontSize: 23, textAlign: 'center', padding: 8 }, textInputStyle: { height: 45, width: '90%', textAlign: 'center', borderWidth: 1, borderColor: '#00B8D4', borderRadius: 7, marginTop: 15, }, itemsStyle: { fontSize: 22, color: '#000' } }); |
9. Complete Source Code for App.js file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
import React, { useState, useEffect } from 'react'; import { SafeAreaView, Text, View, StyleSheet, Alert, TouchableOpacity, TextInput, FlatList } from 'react-native'; import { openDatabase } from 'react-native-sqlite-storage'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; var db = openDatabase({ name: 'SchoolDatabase.db' }); function HomeScreen({ navigation }) { const [S_Name, setName] = useState(''); const [S_Phone, setPhone] = useState(); const [S_Address, setAddress] = useState(''); useEffect(() => { db.transaction(function (txn) { txn.executeSql( "SELECT name FROM sqlite_master WHERE type='table' AND name='Student_Table'", [], function (tx, res) { console.log('item:', res.rows.length); if (res.rows.length == 0) { txn.executeSql('DROP TABLE IF EXISTS Student_Table', []); txn.executeSql( 'CREATE TABLE IF NOT EXISTS Student_Table(student_id INTEGER PRIMARY KEY AUTOINCREMENT, student_name VARCHAR(30), student_phone INT(15), student_address VARCHAR(255))', [] ); } } ); }) }, []); const insertData = () => { if (S_Name == '' || S_Phone == '' || S_Address == '') { Alert.alert('Please Enter All the Values'); } else { db.transaction(function (tx) { tx.executeSql( 'INSERT INTO Student_Table (student_name, student_phone, student_address) VALUES (?,?,?)', [S_Name, S_Phone, S_Address], (tx, results) => { console.log('Results', results.rowsAffected); if (results.rowsAffected > 0) { Alert.alert('Data Inserted Successfully....'); } else Alert.alert('Failed....'); } ); }); } } navigateToViewScreen = () => { navigation.navigate('ViewAllStudentScreen'); } return ( <SafeAreaView style={{ flex: 1 }}> <View style={styles.mainContainer}> <Text style={{ fontSize: 24, textAlign: 'center', color: '#000' }}> Insert Data Into SQLite Database </Text> <TextInput style={styles.textInputStyle} onChangeText={ (text) => setName(text) } placeholder="Enter Student Name" value={S_Name} /> <TextInput style={styles.textInputStyle} onChangeText={ (text) => setPhone(text) } placeholder="Enter Student Phone Number" keyboardType={'numeric'} value={S_Phone} /> <TextInput style={[styles.textInputStyle, { marginBottom: 20 }]} onChangeText={ (text) => setAddress(text) } placeholder="Enter Student Address" value={S_Address} /> <TouchableOpacity style={styles.touchableOpacity} onPress={insertData}> <Text style={styles.touchableOpacityText}> Click Here To Insert Data Into SQLite Database </Text> </TouchableOpacity> <TouchableOpacity style={[styles.touchableOpacity, { marginTop: 20, backgroundColor: '#33691E' }]} onPress={navigateToViewScreen}> <Text style={styles.touchableOpacityText}> Click Here View All Students List </Text> </TouchableOpacity> </View> </SafeAreaView> ); }; function ViewAllStudentScreen({ navigation }) { const [items, setItems] = useState([]); const [empty, setEmpty] = useState([]); useEffect(() => { db.transaction((tx) => { tx.executeSql( 'SELECT * FROM Student_Table', [], (tx, results) => { var temp = []; for (let i = 0; i < results.rows.length; ++i) temp.push(results.rows.item(i)); setItems(temp); if (results.rows.length >= 1) { setEmpty(false); } else { setEmpty(true) } } ); }); }, []); const listViewItemSeparator = () => { return ( <View style={{ height: 1, width: '100%', backgroundColor: '#000' }} /> ); }; const emptyMSG = (status) => { return ( <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}> <Text style={{ fontSize: 25, textAlign: 'center' }}> No Record Inserted Database is Empty... </Text> </View> ); } return ( <SafeAreaView style={{ flex: 1 }}> <View style={{ flex: 1 }}> {empty ? emptyMSG(empty) : <FlatList data={items} ItemSeparatorComponent={listViewItemSeparator} keyExtractor={(item, index) => index.toString()} renderItem={({ item }) => <View key={item.student_id} style={{ padding: 20 }}> <Text style={styles.itemsStyle}> Id: {item.student_id} </Text> <Text style={styles.itemsStyle}> Name: {item.student_name} </Text> <Text style={styles.itemsStyle}> Phone Number: {item.student_phone} </Text> <Text style={styles.itemsStyle}> Address: {item.student_address} </Text> </View> } /> } </View> </SafeAreaView> ); } const Stack = createStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="HomeScreen" component={HomeScreen} /> <Stack.Screen name="ViewAllStudentScreen" component={ViewAllStudentScreen} /> </Stack.Navigator> </NavigationContainer> ); } const styles = StyleSheet.create({ mainContainer: { flex: 1, alignItems: 'center', padding: 10, }, touchableOpacity: { backgroundColor: '#0091EA', alignItems: 'center', borderRadius: 8, justifyContent: 'center', alignItems: 'center', width: '100%' }, touchableOpacityText: { color: '#FFFFFF', fontSize: 23, textAlign: 'center', padding: 8 }, textInputStyle: { height: 45, width: '90%', textAlign: 'center', borderWidth: 1, borderColor: '#00B8D4', borderRadius: 7, marginTop: 15, }, itemsStyle: { fontSize: 22, color: '#000' } }); |
Screenshots:




hii sir,
i need your help. right know i don’t have project in my current company so i thing i wasting my time around 6 month . what can i do ?
Rahul, I think you should learn about Flutter. I have a blog on learning flutter from scratch you can visit it here : https://flutter-examples.com/