As we have discussed in our previous tutorials about Inserting Data into Realm database, Now this tutorial is the next part of inserting data tutorial. Inside this tutorial we would going to perform some amazing functionality and Display all the Already inserted items into Realm Mobile Database inside a Custom ListView. We would render all the items in a group one by one and they would render on the mobile phone screen. So in this tutorial we would going to Show Realm Database Data into ListView in react native Android iOS app Example Tutorial.
What we are doing in this project:
- We are using the React Navigation library in our project in order to use the Activity structure because there are two activities in this project. 1st one is MainActivity and 2nd is ShowDataActivity.
- We have to add the Realm mobile database library in our project in order to use the Realm database.
Activities in present project:
- MainActivity
- ShowDataActivity
Contents in this project Show Realm Database Data into ListView Android iOS React Native App Example Tutorial:
1. We need to install the React Navigation library in our project because we are using multiple activities in our current project. To install the React Navigation library in your project Open your react native project folder path in CMD(Command Prompt) and execute the below command.
1 |
npm install --save react-navigation |
Screenshot of CMD :
Screenshot of CMD after successfully installed library:
2. Now we need to install the Realm library in order to use Realm Mobile Database into our project. To install realm in your project again open your react native’s project folder into CMD(Command Prompt) and execute below command.
1 |
npm install --save realm |
Screenshot of CMD:
Screenshot of CMD after successfully installing this library:
3. After successfully installing the library we need to run react-native link realm command so the newly installed Realm libraries and dependencies would index in our project.
Screenshot of CMD after executing above command:
4. Open your project’s App.js file and import StyleSheet, Platform, View, Image, Text, TextInput, TouchableOpacity, Alert, YellowBox and ListView component in your project.
1 2 3 |
import React, { Component } from 'react'; import { StyleSheet, Platform, View, Image, Text, TextInput, TouchableOpacity, Alert, YellowBox, ListView } from 'react-native'; |
5. Import the Realm in your project and create a global variable name as realm. We would use the realm using this variable.
1 2 3 |
var Realm = require('realm'); let realm ; |
6. Import the StackNavigator module from react navigation library to use multiple activities in your project.
1 |
import { StackNavigator } from 'react-navigation'; |
7. Creating a activity class named as MainActivity in project. Inside this activity we have explaining about Creating Realm database and Creating tables inside it and inserting data from TextInput to realm database. So i have already make a tutorial on this topic. If you want to understand all inserting process is working you can read my this tutorial about Insert Data into Realm database here.
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 |
class MainActivity extends Component{ static navigationOptions = { title: 'MainActivity', }; GoToSecondActivity = () => { this.props.navigation.navigate('Second'); } constructor(){ super(); this.state = { Student_Name : '', Student_Class : '', Student_Subject : '' } realm = new Realm({ schema: [{name: 'Student_Info', properties: { student_id: {type: 'int', default: 0}, student_name: 'string', student_class: 'string', student_subject: 'string' }}] }); } add_Student=()=>{ realm.write(() => { var ID = realm.objects('Student_Info').length + 1; realm.create('Student_Info', { student_id: ID, student_name: this.state.Student_Name, student_class: this.state.Student_Class, student_subject : this.state.Student_Subject }); }); Alert.alert("Student Details Added Successfully.") } render() { return ( <View style={styles.MainContainer}> <TextInput placeholder="Enter Student Name" style = { styles.TextInputStyle } underlineColorAndroid = "transparent" onChangeText = { ( text ) => { this.setState({ Student_Name: text })} } /> <TextInput placeholder="Enter Student Class" style = { styles.TextInputStyle } underlineColorAndroid = "transparent" onChangeText = { ( text ) => { this.setState({ Student_Class: text })} } /> <TextInput placeholder="Enter Student Subject" style = { styles.TextInputStyle } underlineColorAndroid = "transparent" onChangeText = { ( text ) => { this.setState({ Student_Subject: text })} } /> <TouchableOpacity onPress={this.add_Student} activeOpacity={0.7} style={styles.button} > <Text style={styles.TextStyle}> CLICK HERE TO ADD STUDENT DETAILS </Text> </TouchableOpacity> <TouchableOpacity onPress={this.GoToSecondActivity} activeOpacity={0.7} style={styles.button} > <Text style={styles.TextStyle}> SHOW ALL ENTERED DATA INTO LISTVIEW </Text> </TouchableOpacity> </View> ); } } |
Screenshot:
8. Creating another class named as ShowDataActivity in your project. This would be our displaying data class.
1 2 3 4 5 6 7 8 |
class ShowDataActivity extends Component { static navigationOptions = { title: 'ShowDataActivity', }; } |
9. Creating Constructor() in ShowDataActivity class.
YellowBox : Used to hide the componentWillMount() yellow box errors, which is currently coming with every newly build react native project.
mydata : Variable object holds all the data from Realm database.
ds : Creating ListView data source row changed.
dataSource : Creating a State named as dataSource and setting up all the Realm data into dataSource State.
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 |
class ShowDataActivity extends Component { static navigationOptions = { title: 'ShowDataActivity', }; constructor() { super(); YellowBox.ignoreWarnings([ 'Warning: componentWillMount is deprecated', 'Warning: componentWillReceiveProps is deprecated', ]); var mydata = realm.objects('Student_Info'); let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows(mydata), }; } } |
10. Creating a function named as GetClickedItem() inside ShowDataActivity, This function would display the Selected item from ListView.
1 2 3 4 5 |
GetClickedItem (student_name) { Alert.alert(student_name); } |
11. Creating a function named as ListViewItemSeparator(), This function would render a Horizontal line after printing each element of ListView.
1 2 3 4 5 6 7 8 9 10 11 |
ListViewItemSeparator = () => { return ( <View style={{ height: .5, width: "100%", backgroundColor: "#000", }} /> ); } |
12. Create ListView component inside render’s return block in ShowDataActivity and Show Realm Database Data into ListView one by one.
dataSource : Setting up the data source in this prop.
renderSeparator : Calling the item separator function.
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 |
render() { return( <View style = { styles.MainContainer }> <ListView dataSource={this.state.dataSource} renderSeparator= {this.ListViewItemSeparator} renderRow={(rowData) => <View style={{flex:1, flexDirection: 'column'}} > <TouchableOpacity onPress={this.GetClickedItem.bind(this, rowData.student_name)} > <Text style={styles.textViewContainer} >{'id = ' + rowData.student_id}</Text> <Text style={styles.textViewContainer} >{'Name = ' + rowData.student_name}</Text> <Text style={styles.textViewContainer} >{'Class = ' + rowData.student_class}</Text> <Text style={styles.textViewContainer} >{'Subject = ' + rowData.student_subject}</Text> </TouchableOpacity> </View> } /> </View> ); } |
13. Complete Code of ShowDataActivity class 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 |
class ShowDataActivity extends Component { static navigationOptions = { title: 'ShowDataActivity', }; constructor() { super(); YellowBox.ignoreWarnings([ 'Warning: componentWillMount is deprecated', 'Warning: componentWillReceiveProps is deprecated', ]); var mydata = realm.objects('Student_Info'); let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows(mydata), }; } GetClickedItem (student_name) { Alert.alert(student_name); } ListViewItemSeparator = () => { return ( <View style={{ height: .5, width: "100%", backgroundColor: "#000", }} /> ); } render() { return( <View style = { styles.MainContainer }> <ListView dataSource={this.state.dataSource} renderSeparator= {this.ListViewItemSeparator} renderRow={(rowData) => <View style={{flex:1, flexDirection: 'column'}} > <TouchableOpacity onPress={this.GetClickedItem.bind(this, rowData.student_name)} > <Text style={styles.textViewContainer} >{'id = ' + rowData.student_id}</Text> <Text style={styles.textViewContainer} >{'Name = ' + rowData.student_name}</Text> <Text style={styles.textViewContainer} >{'Class = ' + rowData.student_class}</Text> <Text style={styles.textViewContainer} >{'Subject = ' + rowData.student_subject}</Text> </TouchableOpacity> </View> } /> </View> ); } } |
Screenshot:
14. Creating StackNavigator activity navigation structure to implement and control between multiple activities.
1 2 3 4 5 6 |
export default Project = StackNavigator( { First: { screen: MainActivity }, Second: { screen: ShowDataActivity } }); |
15. Creating Styles.
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 |
const styles = StyleSheet.create({ MainContainer :{ flex:1, justifyContent: 'center', paddingTop: (Platform.OS) === 'ios' ? 20 : 0, margin: 10 }, TextInputStyle: { borderWidth: 1, borderColor: '#009688', width: '100%', height: 40, borderRadius: 10, marginBottom: 10, textAlign: 'center', }, button: { width: '100%', height: 40, padding: 10, backgroundColor: '#4CAF50', borderRadius:7, marginTop: 12 }, TextStyle:{ color:'#fff', textAlign:'center', }, textViewContainer: { textAlignVertical:'center', padding:10, fontSize: 20, color: '#000', } }); |
16. 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 |
import React, { Component } from 'react'; import { StyleSheet, Platform, View, Image, Text, TextInput, TouchableOpacity, Alert, YellowBox, ListView } from 'react-native'; var Realm = require('realm'); let realm ; import { StackNavigator } from 'react-navigation'; class MainActivity extends Component{ static navigationOptions = { title: 'MainActivity', }; GoToSecondActivity = () => { this.props.navigation.navigate('Second'); } constructor(){ super(); this.state = { Student_Name : '', Student_Class : '', Student_Subject : '' } realm = new Realm({ schema: [{name: 'Student_Info', properties: { student_id: {type: 'int', default: 0}, student_name: 'string', student_class: 'string', student_subject: 'string' }}] }); } add_Student=()=>{ realm.write(() => { var ID = realm.objects('Student_Info').length + 1; realm.create('Student_Info', { student_id: ID, student_name: this.state.Student_Name, student_class: this.state.Student_Class, student_subject : this.state.Student_Subject }); }); Alert.alert("Student Details Added Successfully.") } render() { return ( <View style={styles.MainContainer}> <TextInput placeholder="Enter Student Name" style = { styles.TextInputStyle } underlineColorAndroid = "transparent" onChangeText = { ( text ) => { this.setState({ Student_Name: text })} } /> <TextInput placeholder="Enter Student Class" style = { styles.TextInputStyle } underlineColorAndroid = "transparent" onChangeText = { ( text ) => { this.setState({ Student_Class: text })} } /> <TextInput placeholder="Enter Student Subject" style = { styles.TextInputStyle } underlineColorAndroid = "transparent" onChangeText = { ( text ) => { this.setState({ Student_Subject: text })} } /> <TouchableOpacity onPress={this.add_Student} activeOpacity={0.7} style={styles.button} > <Text style={styles.TextStyle}> CLICK HERE TO ADD STUDENT DETAILS </Text> </TouchableOpacity> <TouchableOpacity onPress={this.GoToSecondActivity} activeOpacity={0.7} style={styles.button} > <Text style={styles.TextStyle}> SHOW ALL ENTERED DATA INTO LISTVIEW </Text> </TouchableOpacity> </View> ); } } class ShowDataActivity extends Component { static navigationOptions = { title: 'ShowDataActivity', }; constructor() { super(); YellowBox.ignoreWarnings([ 'Warning: componentWillMount is deprecated', 'Warning: componentWillReceiveProps is deprecated', ]); var mydata = realm.objects('Student_Info'); let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows(mydata), }; } GetClickedItem (student_name) { Alert.alert(student_name); } ListViewItemSeparator = () => { return ( <View style={{ height: .5, width: "100%", backgroundColor: "#000", }} /> ); } render() { return( <View style = { styles.MainContainer }> <ListView dataSource={this.state.dataSource} renderSeparator= {this.ListViewItemSeparator} renderRow={(rowData) => <View style={{flex:1, flexDirection: 'column'}} > <TouchableOpacity onPress={this.GetClickedItem.bind(this, rowData.student_name)} > <Text style={styles.textViewContainer} >{'id = ' + rowData.student_id}</Text> <Text style={styles.textViewContainer} >{'Name = ' + rowData.student_name}</Text> <Text style={styles.textViewContainer} >{'Class = ' + rowData.student_class}</Text> <Text style={styles.textViewContainer} >{'Subject = ' + rowData.student_subject}</Text> </TouchableOpacity> </View> } /> </View> ); } } export default Project = StackNavigator( { First: { screen: MainActivity }, Second: { screen: ShowDataActivity } }); const styles = StyleSheet.create({ MainContainer :{ flex:1, justifyContent: 'center', paddingTop: (Platform.OS) === 'ios' ? 20 : 0, margin: 10 }, TextInputStyle: { borderWidth: 1, borderColor: '#009688', width: '100%', height: 40, borderRadius: 10, marginBottom: 10, textAlign: 'center', }, button: { width: '100%', height: 40, padding: 10, backgroundColor: '#4CAF50', borderRadius:7, marginTop: 12 }, TextStyle:{ color:'#fff', textAlign:'center', }, textViewContainer: { textAlignVertical:'center', padding:10, fontSize: 20, color: '#000', } }); |
Screenshots in Android device:
Hi.
Thank you for all tutorials on Realm. Please, continue and maybe after Realm, react native and firebase. 😉
Welcome Revonn 🙂 , And after completing Realm i will start posting tutorials on Firebase 🙂 .
What good news! Thx 😉
Amazing stuff :). Thanx for sharing !
Welcome Irbe 🙂 .
Hi admin, Thanks for the great tutorial on realm database. I’m also new to this one. I have one query. How can access schema object created in one component into another component?
It’s like I have created add_user() in one component on one of my sceen and inserted data into schema. But again in another screen I have to insert the data into same schema. How can I do this ?
Kabeer you need to create the object of first class and call that function from present class, read my this tutorial this would help you : https://reactnativecode.com/call-another-class-function/ .
its great for me sir, thankyou for sharing your knowledge…
Welcome 🙂 .
Hi admin Great Work!!! Can You just add Functionality of Edit and Delete to Same Project.
Yes Harry, i will soon publish a new tutorial on this topic 🙂 .
Sir I need help when I enter employee id to the text input field than I want to display full name and id of employee to the second screen.
Swati currently we do not how how to save image locally in mobile phone but you can store image URL if your image is online. read our this tutorial this would help you https://reactnativecode.com/insert-data-into-realm-local-database/
Hello sir,
I am getting error while installing realm using this command
“npm install –save realm”
C:\Users\Maan\Desktop\Demo>npm install –save realm
> [email protected].0 install C:\Users\Maan\Desktop\Demo\node_modules\realm
> node-pre-gyp install –fallback-to-build
node-pre-gyp ERR! Tried to download(404): https://static.realm.io/node-pre-gyp/2
.13.0/realm-v2.13.0-node-v64-win32-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for [email protected].0 and [email protected]
(node-v64 ABI, unknown) (falling back to source compile with node-gyp)
node-pre-gyp ERR! Tried to download(undefined): https://static.realm.io/node-pre
-gyp/2.13.0/realm-v2.13.0-node-v64-win32-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for [email protected].0 and [email protected]
(node-v64 ABI, unknown) (falling back to source compile with node-gyp)
gyp ERR! configure error
gyp ERR! stack Error: Can’t find Python executable “python”, you can set the PYT
HON env variable.
gyp ERR! stack at PythonFinder.failNoPython (C:\Users\Maan\AppData\Roaming\n
pm\node_modules\npm\node_modules\node-gyp\lib\configure.js:483:19)
gyp ERR! stack at PythonFinder. (C:\Users\Maan\AppData\Roaming\np
m\node_modules\npm\node_modules\node-gyp\lib\configure.js:508:16)
gyp ERR! stack at C:\Users\Maan\AppData\Roaming\npm\node_modules\npm\node_mo
dules\graceful-fs\polyfills.js:284:29
gyp ERR! stack at FSReqWrap.oncomplete (fs.js:158:21)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command “C:\\Program Files\\nodejs\\node.exe” “C:\\Users\\Maan\\AppData
\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js” “co
nfigure” “–fallback-to-build” “–module=C:\\Users\\Maan\\Desktop\\Demo\\node_mo
dules\\realm\\compiled\\node-v64_win32_x64\\realm.node” “–module_name=realm” “-
-module_path=C:\\Users\\Maan\\Desktop\\Demo\\node_modules\\realm\\compiled\\node
-v64_win32_x64”
gyp ERR! cwd C:\Users\Maan\Desktop\Demo\node_modules\realm
gyp ERR! node -v v10.6.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute ‘C:\Program Files\nodejs\node.e
xe C:\Users\Maan\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\
node-gyp.js configure –fallback-to-build –module=C:\Users\Maan\Desktop\Demo\no
de_modules\realm\compiled\node-v64_win32_x64\realm.node –module_name=realm –mo
dule_path=C:\Users\Maan\Desktop\Demo\node_modules\realm\compiled\node-v64_win32_
x64’ (1)
node-pre-gyp ERR! stack at ChildProcess. (C:\Users\Maan\Desktop\D
emo\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
node-pre-gyp ERR! stack at ChildProcess.emit (events.js:182:13)
node-pre-gyp ERR! stack at maybeClose (internal/child_process.js:961:16)
node-pre-gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/chi
ld_process.js:248:5)
node-pre-gyp ERR! System Windows_NT 6.1.7601
node-pre-gyp ERR! command “C:\\Program Files\\nodejs\\node.exe” “C:\\Users\\Maan
\\Desktop\\Demo\\node_modules\\node-pre-gyp\\bin\\node-pre-gyp” “install” “–fal
lback-to-build”
node-pre-gyp ERR! cwd C:\Users\Maan\Desktop\Demo\node_modules\realm
node-pre-gyp ERR! node -v v10.6.0
node-pre-gyp ERR! node-pre-gyp -v v0.6.39
node-pre-gyp ERR! not ok
Failed to execute ‘C:\Program Files\nodejs\node.exe C:\Users\Maan\AppData\Roamin
g\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js configure –fallbac
k-to-build –module=C:\Users\Maan\Desktop\Demo\node_modules\realm\compiled\node-
v64_win32_x64\realm.node –module_name=realm –module_path=C:\Users\Maan\Desktop
\Demo\node_modules\realm\compiled\node-v64_win32_x64’ (1)
npm WARN [email protected] requires a peer of [email protected]^3.17.0 || ^
4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]
1.2.4: wanted {“os”:”darwin”,”arch”:”any”} (current: {“os”:”win32″,”arch”:”x64″}
)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected].0 install:
node-pre-gyp install --fallback-to-build
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected].0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Maan\AppData\Roaming\npm-cache\_logs\2018-07-13T12_54_51_1
36Z-debug.log
Dilip please start the command prompt as Run as Administrator mode and try again.