Real time filter functionality is recommended for every dynamic react native application who wish to Filter the custom JSON ListView. So in this tutorial we would going to create a react native application with JSON data ListView and filter that data using PHP script. So let’s get started .
What we are doing in this project ( Project Description – Must Read ) :
We are creating a react native app with 2 activities classes using React Navigation Library. First activity name is MainActivity and Second activity name is SecondActivity. The MainActivity class is used to show only the Name of students from JSON fetching from MySQL database. Now we would add the onPress event on ListView and get the selected ListView item ID. After that using the React Navigation inbuilt method this.props.navigation.navigate we would open the SecondActivity and send the Selected Item ID along with it. Now we would receive the Item ID using this.props.navigation.state.params in SecondActivitySecondActivity and run a real time web call to server using Fetch() method. It would send the Item ID on server and on server we are using the PHP script to Get ID and fetch only given ID record from MySQL database. After successfully fetching the only selected record it would return us in JSON form, which we would receive and show inside Text component.
Contents in this project Apply Filter on JSON ListView Data Using PHP MySQL Android iOS Tutorial :
1. Create a fresh MySQL database on your Local / Online hosting server.
2. Create a table inside your MySQL database named as Student_Info_Table with 5 columns id, name, semester, department, phone_number like i did in below screenshot.
3. After successfully creating the MySQL table insert some records inside it like i did in below screenshot.
4. Create 3 PHP Script files :
DBConfig.php : The DBConfig.php file contains all the server information like Database Host Name, Database name, Database username and Database Password.
CollegeStudentsList.php : This file would fetch all the records from MySQL database and covert them into JSON.
Filter.php : This is used to filter the received ID from react native application and return the only given ID record object of single student.
Code for DBConfig.php file :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
//Define your host here.
$HostName = “localhost”;
//Define your database name here.
$DatabaseName = “id2070055_reactnativedb”;
//Define your database username here.
$HostUser = “id2070055_reactnativedb_user”;
//Define your database password here.
$HostPass = “1234567890”;
?>
|
Code for CollegeStudentsList.php 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
|
<?php
include ‘DBConfig.php’;
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}
// Creating SQL command to fetch all records from Table.
$sql = “SELECT * FROM Student_Info_Table”;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item);
}
} else {
echo “No Results Found.”;
}
echo $json;
$conn->close();
?>
|
Screenshot of JSON after running the CollegeStudentsList.php file on web browser :
Code for Filter.php 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
|
<?php
// Importing DBConfig.php file.
include ‘DBConfig.php’;
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
// Getting the received JSON into $json variable.
$json = file_get_contents(‘php://input’);
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
// Populate ID from JSON $obj array and store into $ID.
$ID = $obj[‘id’];
//Fetching the selected record.
$CheckSQL = “SELECT * FROM Student_Info_Table WHERE id=’$ID'”;
$result = $con->query($CheckSQL);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$Item = $row;
$json = json_encode($Item);
}
}else {
echo “No Results Found.”;
}
echo $json;
$con->close();
?>
|
Now the server side coding part is complete . Next step is to Start the app coding .
5. Start a fresh React Native project. If you don’t know how then read my this tutorial.
6. Download and Install the React Navigation library inside your react native project by opening your project name folder into command prompt / terminal and execute the below command. The React Navigation library is used to add multiple activities in react native project.
1
|
npm install —save react–navigation
|
Screenshot after installing the library :
7. Open your project’s App.js file and import StyleSheet, Text, View, ListView and ActivityIndicator component.
1
2
3
|
import React, { Component } from ‘react’;
import { StyleSheet, Text, View, ListView, ActivityIndicator } from ‘react-native’;
|
8. Import the Stack Navigator module from react navigation library.
1
|
import { StackNavigator } from ‘react-navigation’;
|
9. Create the first class named as MainActivity that extends the component. This would be our First main activity class.
1
2
3
4
|
class MainActivity extends Component {
}
|
10. Create navigationOptions inside MainActivity. The navigationOptions is used to set the activity Title which would show inside the Action Title bar of application.
1
2
3
4
5
6
7
8
|
class MainActivity extends Component {
static navigationOptions =
{
title: ‘MainActivity’,
};
}
|
11. Now create constructor inside MainActivity and inside constructor make a State named as isLoading. This State is used to show and hide the ActivityIndicator component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class MainActivity extends Component {
static navigationOptions =
{
title: ‘MainActivity’,
};
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
}
|
12. Create a function named as OpenSecondActivity() and pass id as argument inside it. This function is used to Open SecondActivity and with it we would also send the selected id to next activity using ListViewClickItemHolder object.
1
2
3
4
5
|
OpenSecondActivity(id) {
this.props.navigation.navigate(‘Second’, { ListViewClickItemHolder: id });
}
|
13. Create componentDidMount() method. This is a pre define inbuilt method, which would call automatically on application starting time. Now define the fetch() web api inside componentDidMount() method. This would parse the complete JSON.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
componentDidMount() {
return fetch(‘https://reactnativecode.000webhostapp.com/CollegeStudentsList.php’)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
|
14. Create a function named as ListViewItemSeparator(). This is used to show a divider line between each ListView item in MainActivity.
1
2
3
4
5
6
7
8
9
10
11
|
ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: “100%”,
backgroundColor: “#000”,
}}
/>
);
}
|
15. Set a IF condition inside render’s block and using the State check and hide the ActivityIndicator after done loading JSON data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
);
}
|
16. Create a ListView component inside render’s return block in MainActivity . We are only showing the Student name from JSON data.
dataSource : Set the JSON ListView data source.
renderSeparator : Call the ListViewItemSeparator() method which would display item separator line.
renderRow : Render the Row data from Data source.
onPress : Call the OpenSecondActivity() function and pass the ID inside it using argument.
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
|
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.OpenSecondActivity.bind(this, rowData.id)}> {rowData.name} </Text>}
/>
</View>
);
}
|
17. Complete Source code for MainActivity class :
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
|
class MainActivity extends Component {
static navigationOptions =
{
title: ‘MainActivity’,
};
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
OpenSecondActivity(id) {
this.props.navigation.navigate(‘Second’, { ListViewClickItemHolder: id });
}
componentDidMount() {
return fetch(‘https://reactnativecode.000webhostapp.com/CollegeStudentsList.php’)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: “100%”,
backgroundColor: “#000”,
}}
/>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.OpenSecondActivity.bind(this, rowData.id)}> {rowData.name} </Text>}
/>
</View>
);
}
}
|
Screenshot of MainActivity :
18. Now create the SecondActivity Class. This would be our Filter record class.
1
2
3
4
|
class SecondActivity extends Component
{
}
|
19. Set activity Title using navigationOptions .
1
2
3
4
|
static navigationOptions =
{
title: ‘SecondActivity’,
};
|
20. Create constructor and make 5 state variables named as IdHolder, NameHolder, SemesterHolder, DepartmentHolder and PhoneNumberHolder.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
constructor(props) {
super(props)
this.state={
IdHolder : ”,
NameHolder : ”,
SemesterHolder : ”,
DepartmentHolder : ”,
PhoneNumberHolder : ”
}
}
|
21. Create componentDidMount() method inside SecondActivity and call the Fetch() Web API. Now receive the sent id using this.props.navigation.state.params.ListViewClickItemHolder and pass it with id object. Now after come the response into responseJson array, we would pop up the records and store into each 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
28
29
30
31
32
33
|
componentDidMount(){
fetch(‘https://reactnativecode.000webhostapp.com/Filter.php’, {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
// Getting the id.
id: this.props.navigation.state.params.ListViewClickItemHolder
})
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
IdHolder : responseJson[0].id,
NameHolder : responseJson[0].name,
SemesterHolder : responseJson[0].semester,
DepartmentHolder : responseJson[0].department,
PhoneNumberHolder : responseJson[0].phone_number
})
}).catch((error) => {
console.error(error);
});
}
|
22. Create 5 Text component inside render’s return block. Each component is used to display a Filtered Record.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
render()
{
return(
<View style = { styles.MainContainer }>
<View style={{flex:1, flexDirection: ‘column’}} >
<Text style={styles.textViewContainer} > {‘id = ‘ + this.state.IdHolder} </Text>
<Text style={styles.textViewContainer} > {‘Name = ‘ + this.state.NameHolder} </Text>
<Text style={styles.textViewContainer} > {‘Department = ‘ + this.state.DepartmentHolder} </Text>
<Text style={styles.textViewContainer} > {‘Semester = ‘ + this.state.SemesterHolder} </Text>
<Text style={styles.textViewContainer} > {‘Phone Number = ‘ + this.state.PhoneNumberHolder} </Text>
</View>
</View>
);
}
|
23. Complete Source code for SecondActivity Class :
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
|
class SecondActivity extends Component
{
static navigationOptions =
{
title: ‘SecondActivity’,
};
constructor(props) {
super(props)
this.state={
IdHolder : ”,
NameHolder : ”,
SemesterHolder : ”,
DepartmentHolder : ”,
PhoneNumberHolder : ”
}
}
componentDidMount(){
fetch(‘https://reactnativecode.000webhostapp.com/Filter.php’, {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
// Getting the id.
id: this.props.navigation.state.params.ListViewClickItemHolder
})
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
IdHolder : responseJson[0].id,
NameHolder : responseJson[0].name,
SemesterHolder : responseJson[0].semester,
DepartmentHolder : responseJson[0].department,
PhoneNumberHolder : responseJson[0].phone_number
})
}).catch((error) => {
console.error(error);
});
}
render()
{
return(
<View style = { styles.MainContainer }>
<View style={{flex:1, flexDirection: ‘column’}} >
<Text style={styles.textViewContainer} > {‘id = ‘ + this.state.IdHolder} </Text>
<Text style={styles.textViewContainer} > {‘Name = ‘ + this.state.NameHolder} </Text>
<Text style={styles.textViewContainer} > {‘Department = ‘ + this.state.DepartmentHolder} </Text>
<Text style={styles.textViewContainer} > {‘Semester = ‘ + this.state.SemesterHolder} </Text>
<Text style={styles.textViewContainer} > {‘Phone Number = ‘ + this.state.PhoneNumberHolder} </Text>
</View>
</View>
);
}
}
|
Screenshot of Second Activity with record :
24. Now create the StackNavigator method which would tell the project about present classes and which class is call first. This step is very important.
1
2
3
4
5
6
|
export default Myproject = StackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
|
25. Create Custom Style sheet for all the Views and Text.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
const styles = StyleSheet.create(
{
MainContainer:
{
justifyContent: ‘center’,
flex:1,
margin: 10
},
rowViewContainer: {
fontSize: 20,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
},
textViewContainer: {
padding:5,
fontSize: 20,
color: ‘#000’,
}
});
|
26. 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
|
import React, { Component } from ‘react’;
import { StyleSheet, Text, View, ListView, ActivityIndicator } from ‘react-native’;
import { StackNavigator } from ‘react-navigation’;
class MainActivity extends Component {
static navigationOptions =
{
title: ‘MainActivity’,
};
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
OpenSecondActivity(id) {
this.props.navigation.navigate(‘Second’, { ListViewClickItemHolder: id });
}
componentDidMount() {
return fetch(‘https://reactnativecode.000webhostapp.com/CollegeStudentsList.php’)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: “100%”,
backgroundColor: “#000”,
}}
/>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.OpenSecondActivity.bind(this, rowData.id)}> {rowData.name} </Text>}
/>
</View>
);
}
}
class SecondActivity extends Component
{
static navigationOptions =
{
title: ‘SecondActivity’,
};
constructor(props) {
super(props)
this.state={
IdHolder : ”,
NameHolder : ”,
SemesterHolder : ”,
DepartmentHolder : ”,
PhoneNumberHolder : ”
}
}
componentDidMount(){
fetch(‘https://reactnativecode.000webhostapp.com/Filter.php’, {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
// Getting the id.
id: this.props.navigation.state.params.ListViewClickItemHolder
})
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
IdHolder : responseJson[0].id,
NameHolder : responseJson[0].name,
SemesterHolder : responseJson[0].semester,
DepartmentHolder : responseJson[0].department,
PhoneNumberHolder : responseJson[0].phone_number
})
}).catch((error) => {
console.error(error);
});
}
render()
{
return(
<View style = { styles.MainContainer }>
<View style={{flex:1, flexDirection: ‘column’}} >
<Text style={styles.textViewContainer} > {‘id = ‘ + this.state.IdHolder} </Text>
<Text style={styles.textViewContainer} > {‘Name = ‘ + this.state.NameHolder} </Text>
<Text style={styles.textViewContainer} > {‘Department = ‘ + this.state.DepartmentHolder} </Text>
<Text style={styles.textViewContainer} > {‘Semester = ‘ + this.state.SemesterHolder} </Text>
<Text style={styles.textViewContainer} > {‘Phone Number = ‘ + this.state.PhoneNumberHolder} </Text>
</View>
</View>
);
}
}
export default Myproject = StackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
const styles = StyleSheet.create(
{
MainContainer:
{
justifyContent: ‘center’,
flex:1,
margin: 10
},
rowViewContainer: {
fontSize: 20,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
},
textViewContainer: {
padding:5,
fontSize: 20,
color: ‘#000’,
}
});
|
Screenshots in android mobile phone application :
Screenshot in iOS mobile application :