Я создал одну рабочую демонстрацию, просто посмотрите!
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,TouchableOpacity, TextInput,ListView,ActivityIndicator
} from 'react-native';
import Sqlite from './AppComponent/SqliteHelper';
let SQLiteStorage = require('react-native-sqlite-storage')
var TAG = "App : ";
var records = [];
var _this = null;
var db = null;
export default class App extends Component<{}> {
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([]),
selected :0,
itemNo:'',
itemName:'',
records :[],
loading:false,
};
_this = this;
}
componentWillMount(){
console.log(TAG + "-----componentWillMount-----")
Sqlite.initialize();
}
/**
* List item row UI
* @param {*} rowData
*/
listRowItems(rowData) {
console.log(TAG + "-----listRowItems------")
if (rowData != null) {
return <View style={styles.listItemStyle}>
<Text>ItemNo:{rowData.ITEMNO}</Text>
<Text>ItemName:{rowData.ITEMNAME}</Text>
<View style={{marginTop:5,marginBottom:5,backgroundColor:'#000',height:1}}/>
</View>
} else {
console.log(TAG + "rowdata null")
}
}
/**
* UI modification while selecting diff options
* @param {*} value
*/
changeSelection(value){
this.setState({selected:value});
}
/**
* When click on google
*/
goClick(){
console.log(TAG + "------goClick----")
switch(this.state.selected){
case 0:
this.SearchItemWithInsert(this.state.itemNo,this.state.itemName);
break;
case 1:
this.SearchWithUpdate(this.state.itemNo,this.state.itemName)
break;
case 2:
this.SearchWithDelete(this.state.itemNo)
break;
case 3:
this.searchRecord(this.state.itemNo)
break;
case 4:
this.deleteAllRecords();
break;
case 5:
this.getAllItems();
break;
}
}
/**
* update record
* @param {*} ITEMNO
* @param {*} ITEMNAME
*/
updateItemName(ITEMNO, ITEMNAME) {
console.log(TAG + "-----updateItemName------");
_this.startLoading();
var query = "UPDATE Table1 set ITEMNAME='" + ITEMNAME + "' where ITEMNO =" + ITEMNO;
console.log(TAG + "query : " + query);
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
try {
db.transaction((tx) => {
tx.executeSql(query, [], (tx, results) => {
console.log(TAG + "Item updated...");
_this.getAllItems();
}, function (error) {
_this.stopLoading()
console.log(TAG + "Item update error: " + error.message);
});
});
} catch (ex) {
console.log(TAG + "error in updateITEMNAME " + JSON.stringify(ex));
}
}
/**
* before delete search record, if found then delete record
* @param {*} ITEMNO
*/
SearchWithDelete(ITEMNO) {
console.log(TAG + "-----SearchWithDelete------");
if (ITEMNO.length > 0) {
_this.startLoading();
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM Table1 where ITEMNO=' + ITEMNO, [], (tx, results) => {
console.log(TAG + "results :" + JSON.stringify(results))
var len = results.rows.length;
console.log(TAG + "Items found : " + len);
if (len > 0) {
_this.DeletesItem(ITEMNO);
} else {
_this.stopLoading()
alert('Not found')
}
}, function (error) {
_this.stopLoading()
console.log(TAG + "Item delete error: " + error.message);
});
});
} else {
_this.stopLoading()
alert('please enter item no')
}
}
/**
* delete record
* @param {*} ITEMNO
*/
DeletesItem(ITEMNO) {
console.log(TAG + "-----DeletesItem------");
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
db.transaction((txn) => {
txn.executeSql('DELETE FROM Table1 where ITEMNO =' + ITEMNO, [], (txn, resultsN) => {
console.log(TAG + "deleted 1 Item");
_this.getAllItems()
}, function (error) {
_this.stopLoading()
console.log(TAG + "Item delete error: " + error.message);
});
});
}
/**
* search record, if found update it
* @param {*} ITEMNO
* @param {*} ITEMNAME
*/
SearchWithUpdate(ITEMNO, ITEMNAME) {
console.log(TAG + "-----SearchWithUpdate------");
if (ITEMNO.length > 0) {
if (ITEMNAME.length > 0) {
_this.startLoading();
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM Table1 where ITEMNO=' + ITEMNO, [], (tx, results) => {
console.log(TAG + "results :" + JSON.stringify(results))
var len = results.rows.length;
console.log(TAG + "Items found : " + len);
if (len > 0) {
_this.updateItemName(ITEMNO, ITEMNAME);
} else {
_this.stopLoading()
alert('Not found')
}
});
});
} else {
_this.stopLoading()
alert('please enter item name')
}
} else {
_this.stopLoading()
alert('please enter item no')
}
}
/**
* search record, if not found then insert it
* @param {*} ITEMNO
* @param {*} ITEMNAME
*/
SearchItemWithInsert(ITEMNO, ITEMNAME) {
console.log(TAG + "-----SearchItem------");
if (ITEMNO.length > 0) {
if (ITEMNAME.length > 0) {
_this.startLoading();
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM Table1 where ITEMNO=' + ITEMNO, [], (tx, results) => {
console.log(TAG + "results :" + JSON.stringify(results))
var len = results.rows.length;
console.log(TAG + "Items found : " + len);
if (len > 0) {
_this.stopLoading()
alert('already available')
} else {
_this.insertIntoItemTable(ITEMNO, ITEMNAME);
}
}, function (error) {
_this.stopLoading()
console.log(TAG + "Item insert error: " + error.message);
});
});
} else {
_this.stopLoading()
alert('please enter item name')
}
} else {
_this.stopLoading()
alert('please enter item no')
}
}
/**
* Insert function
* @param {*} ITEMNO
* @param {*} ITEMNAME
*/
insertIntoItemTable(ITEMNO, ITEMNAME) {
console.log(TAG + "-------insertIntoItemTable---------")
try {
var query = 'INSERT INTO Table1 ( ITEMNO,ITEMNAME ) VALUES (?,?)';
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
db.transaction((tx) => {
tx.executeSql(query,
[ITEMNO, ITEMNAME],
(tx, results) => {
console.log(TAG + "Item : " + ITEMNAME + ' inserted......');
_this.getAllItems();
}, function (error) {
console.log(TAG + "Item : " + ITEMNAME + ' insertion error: ' + error.message);
});
});
} catch (ex) {
console.log(TAG + "Exception: " + ex);
}
}
startLoading(){
console.log(TAG + '------startLoading-----')
this.setState({loading:true})
}
stopLoading(){
console.log(TAG + '------stopLoading-----')
this.setState({loading:false})
}
/**
* search record
* @param {*} ITEMNO
*/
searchRecord(ITEMNO) {
console.log(TAG + '-----searchRecord-----');
if (ITEMNO.length > 0) {
this.startLoading();
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM Table1 where ITEMNO=' + ITEMNO, [], (tx, results) => {
console.log(TAG + "Query completed");
// Get rows with Web SQL Database spec compliance.
var len = results.rows.length;
console.log(TAG + 'len::::::' + len);
var aryData = [];
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
console.log(TAG + `Record:::::::: ${row.ITEMNO} ${row.ITEMNAME}`);
aryData.push({ ITEMNO: row.ITEMNO, ITEMNAME: row.ITEMNAME });
}
console.log(TAG + 'arydata :: ' + JSON.stringify(aryData));
if (aryData.length == 0) {
_this.stopLoading()
alert('no record found')
} else {
_this.populateList(aryData);
}
});
});
} else {
alert('enter item no')
}
}
/**
* load all items/records from database
*/
getAllItems(){
console.log(TAG + '-----getAllItems-----');
this.startLoading();
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM Table1', [], (tx, results) => {
console.log(TAG + "Query completed");
// Get rows with Web SQL Database spec compliance.
var len = results.rows.length;
console.log(TAG + 'len::::::' + len);
var aryData = [];
for (let i = 0; i < len; i++)
{
let row = results.rows.item(i);
console.log(TAG + `Record:::::::: ${row.ITEMNO} ${row.ITEMNAME}`);
aryData.push({ITEMNO:row.ITEMNO,ITEMNAME:row.ITEMNAME});
}
console.log(TAG + 'arydata :: ' + JSON.stringify(aryData));
if (aryData.length == 0) {
_this.stopLoading()
alert('no record found')
} else {
_this.populateList(aryData);
}
});
});
}
/**
* attach all data fetched from database to listview
* @param {*} aryData
*/
populateList(aryData){
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
var dataSourceTemp = ds.cloneWithRows(aryData);
this.setState({records:aryData,dataSource:dataSourceTemp});
_this.stopLoading()
}
/**
* delete all records
*/
deleteAllRecords(){
console.log(TAG + "-----deleteAllRecords------");
db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
db.transaction((txn) => {
txn.executeSql('DELETE FROM Table1', [], (txn, resultsN) => {
console.log(TAG + "deleted 1 Item");
this.getAllItems();
});
});
}
render() {
return (
(this.state.loading)?<View style={styles.containerholder}>
<View style={styles.containerloading}>
<ActivityIndicator color='grey' size="large" color="#0000ff" />
</View>
</View>
:
<View style={styles.container}>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={()=>this.changeSelection(0)} style={(this.state.selected == 0)?styles.buttonStyleSelected:styles.buttonStyle}>
<Text style={(this.state.selected == 0)?styles.buttonTextSelected:styles.buttonText}>Insert single</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>this.changeSelection(1)} style={(this.state.selected == 1)?styles.buttonStyleSelected:styles.buttonStyle}>
<Text style={(this.state.selected == 1)?styles.buttonTextSelected:styles.buttonText}>Update single</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>this.changeSelection(2)} style={(this.state.selected == 2)?styles.buttonStyleSelected:styles.buttonStyle}>
<Text style={(this.state.selected == 2)?styles.buttonTextSelected:styles.buttonText}>Delete single</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>this.changeSelection(3)} style={(this.state.selected == 3)?styles.buttonStyleSelected:styles.buttonStyle}>
<Text style={(this.state.selected == 3)?styles.buttonTextSelected:styles.buttonText}>search</Text>
</TouchableOpacity>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={()=>this.changeSelection(4)} style={(this.state.selected == 4)?styles.buttonStyleSelected:styles.buttonStyle}>
<Text style={(this.state.selected == 4)?styles.buttonTextSelected:styles.buttonText}>All Delete</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>this.changeSelection(5)} style={(this.state.selected == 5)?styles.buttonStyleSelected:styles.buttonStyle}>
<Text style={(this.state.selected == 5)?styles.buttonTextSelected:styles.buttonText}>Refresh record</Text>
</TouchableOpacity>
</View>
<View style={styles.formStyle}>
{((this.state.selected == 4) || (this.state.selected == 5))?null:
<View>
<Text>Item No</Text>
<TextInput keyboardType = {'numeric'} style = {styles.textInputstyle} onChangeText = {(text) => this.setState({itemNo:text})} value = {this.state.itemNo}/>
</View>
}
{((this.state.selected == 2) || (this.state.selected == 3) || (this.state.selected == 4) || (this.state.selected == 5))?null:
<View style={{marginTop:10}}>
<Text>Item Name</Text>
<TextInput style = {styles.textInputstyle} onChangeText = {(text) => this.setState({itemName:text})} value = {this.state.itemName}/>
</View>
}
<View>
<TouchableOpacity style={styles.goStyle} onPress={()=>this.goClick()}>
<Text style={{color:'#fff'}}>GO</Text>
</TouchableOpacity>
</View>
</View>
<ListView
style={{flex:1}}
dataSource={this.state.dataSource}
renderRow={(rowData) => this.listRowItems(rowData)}
enableEmptySections ={true}/>
</View>
);
}
}
const styles = StyleSheet.create({
containerloading: {
justifyContent: 'center',
height:150,
width:150,
},
containerholder: {
flex: 1,
backgroundColor: 'rgba(255, 255, 255, .4)',
justifyContent: 'center',
alignItems:'center',
},
container: {
flex: 1,
backgroundColor: '#fff',
padding:10,
},
buttonContainer:{
flexDirection:'row',
marginTop:10,
marginBottom:10,
},
buttonStyleSelected:{
padding:5,
backgroundColor:'#00ff',
marginLeft:5,
},
buttonStyle:{
padding:5,
backgroundColor:'gray',
marginLeft:5,
},
buttonText :{
color:'#000',
},
buttonTextSelected :{
color:'#fff',
},
formStyle:{
borderRadius: 4,
borderWidth: 0.5,
borderColor: '#000',
padding:15,
},
textInputstyle:{
height: 40,
width:100,
borderColor: 'gray',
borderWidth: 1 ,
marginTop:10,
},
goStyle:{
padding:5,
backgroundColor:'gray',
width:100,
marginTop:15,
justifyContent: 'center',
alignItems: 'center',
},
listItemStyle:{
padding:10,
}
});