React-Native Realm 基础用法总结_reactnative realm-程序员宅基地

技术标签: 【React-Native2点滴知识 】  

一、环境配置 
1、创建一个ReactNative项目(RealmDemo)

react-native init RealmDemo
 
 
  
  • 1

2、切换目录

cd RealmDemo
 
 
  
  • 1

3、添加realm依赖库

npm install --save realm
 
 
  
  • 1

4、关联realm库

rnpm link realm
 
 
  
  • 1

注意: 
如果关联失败,出现如下错误:

rnpm-link info Linking realm android dependency
rnpm-link info Android module realm has been successfully linked
rnpm-link info Linking realm ios dependency
rnpm-link info iOS module realm has been successfully linked
rnpm-link ERR! It seems something went wrong while linking. Error: spawn UNKNOWN
Please file an issue here: https://github.com/rnpm/rnpm/issues
 
 
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

则需要在 MainApplication 中添加

new RealmReactPackage()
 
 
  
  • 1

不然会在运行时报错:

android Missing Realm constructor - please ensure RealmReact framework is included
 
 
  
  • 1

还需要注意的是,添加过程中有可能出现很多奇怪的现象,有可能链接不上,也可能链接上了没有自动添加代码,需要手动处理:

settings.gradle中是否存在下面的代码,如不存在手动添加
 
 
  
  • 1
include ':realm'
project(':realm').projectDir = new File(rootProject.projectDir, '../node_modules/realm/android')

 
 
  
  • 1
  • 2
  • 3
app->build.gradle中是否存在如下代码
 
 
  
  • 1
dependencies {
    compile project(':realm')//是否存在,不存在手动添加
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
}
 
 
  
  • 1
  • 2
  • 3
  • 4
  • 5

5、运行项目即可

react-native run-android
 
 
  
  • 1

目前为止,Realm库就算配置成功了

二、Realm具体操作 
作为一个数据库,最基本的增删改查是必须的, 
1、建表 
primaryKey属性,该属性的类型可以为string和int类型。声明主键之后,在更新和设置值的时候该值必须保持唯一。一旦一个使用主键的对象被添加到Realm之后,该主键值就无法被修改啦。

   const CarSchema = {
            name: 'Car',
            primaryKey: 'id',
            properties: {
                id: 'int',
                car_type: 'string',
                car_name: 'string',
                driver_name: 'string',
                 phone: {type: 'string', default: '10086'},//添加默认值的写法
            }
        };
  //初始化Realm
  let realm = new Realm({schema: [CarSchema]});
 
 
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2、写数据 
2.1 增

  realm.write(()=> {
                            realm.create('Car', {id: 1, car_type: 'QQ', car_name: 'SB001', driver_name: '张三'});
                            realm.create('Car', {id: 2, car_type: '宝马', car_name: 'SB002', driver_name: '李四'});
                            realm.create('Car', {id: 3, car_type: '奔驰', car_name: 'SB003', driver_name: '王五'});
                        })
 
 
  
  • 1
  • 2
  • 3
  • 4
  • 5

2.2 删

 realm.write(()=> {
                            let cars = realm.objects('Car');
                            let car = cars.filtered('id==3');
                            realm.delete(car);
                        });
 
 
  
  • 1
  • 2
  • 3
  • 4
  • 5

2.3 改

//更新id = 1的数据
                        realm.write(()=> {
                            realm.create('Car', {id: 2, driver_name: 'feiyang'}, true)
                            ToastAndroid.show("修改完成...", ToastAndroid.SHORT);
                        });
 
 
  
  • 1
  • 2
  • 3
  • 4
  • 5

2.4 查

根据id=2 进行查询数据

  let cars = realm.objects('Car');
                        let car = cars.filtered('id==2');
                        if (car) {
                            ToastAndroid.show('Car的数据为,'
                                + '编号=' + car[0].id
                                + 'car_type=' + car[0].car_type
                                + 'car_name=' + car[0].car_name
                                + 'driver_name=' + car[0].driver_name, ToastAndroid.SHORT);
                        }
 
 
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

查询所有

 let cars = realm.objects('Car');
                        ToastAndroid.show('Car的数据为,'+cars.length, ToastAndroid.SHORT);
 
 
  
  • 1
  • 2

下边是完整代码

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';


import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    TouchableHighlight,
    ToastAndroid,

} from 'react-native';

const Realm = require('realm');

class CustomButton extends Component {
    
    render() {
        return (
            <TouchableHighlight
                style={styles.button}
                underlayColor="#a5a5a5"
                onPress={
   this.props.onPress}>

                <Text style={styles.buttonText}>{
   this.props.text}</Text>
            </TouchableHighlight>
        );
    }
}

class Test extends Component {
    

    render() {
        const CarSchema = {
            name: 'Car',
            primaryKey: 'id',
            properties: {
                id: 'int',
                car_type: 'string',
                car_name: 'string',
                driver_name: 'string',
            }
        };

        //初始化Realm
        let realm = new Realm({
   schema: [CarSchema]});
        return (
            <View style={
   {
   marginTop: 20}}>
                <Text style={styles.welcome}>
                    Realm基础使用实例-增删改查
                </Text>
                <CustomButton
                    text="表新增"
                    onPress={
   ()=>
                        realm.write(()=> {
                            realm.create('Car', {id: 1, car_type: 'QQ', car_name: 'SB001', driver_name: '张三'});
                            realm.create('Car', {id: 2, car_type: '宝马', car_name: 'SB002', driver_name: '李四'});
                            realm.create('Car', {id: 3, car_type: '奔驰', car_name: 'SB003', driver_name: '王五'});
                            realm.create('Car', {id: 4, car_type: '劳斯莱斯', car_name: 'SB004', driver_name: '张六'});
                            realm.create('Car', {id: 5, car_type: '比亚迪', car_name: 'SB005', driver_name: '理七'});
                            ToastAndroid.show('添加数据完成', ToastAndroid.SHORT);
                        })
                    }/>

                <CustomButton
                    text="表修改"
                    onPress={
    ()=> {
                        //更新id = 1的数据
                        realm.write(()=> {
                            realm.create('Car', {id: 2, driver_name: 'feiyang'}, true)
                            ToastAndroid.show("修改完成...", ToastAndroid.SHORT);
                        });
                    }}
                />

                <CustomButton
                    text="表数据删除-删除id=3的数据"
                    onPress={
    ()=> {
                        realm.write(()=> {
                            let cars = realm.objects('Car');
                            let car = cars.filtered('id==3');
                            realm.delete(car);
                        });
                    }}
                />

                <CustomButton
                    text="查询所有数据"
                    onPress={
    ()=> {
                        let cars = realm.objects('Car');
                        ToastAndroid.show('Car的数据为,'+cars.length, ToastAndroid.SHORT);
                    }}
                />
                <CustomButton
                    text="根据id=2 进行查询数据"
                    onPress={
   ()=> {
                        let cars = realm.objects('Car');
                        let car = cars.filtered('id==2');
                        if (car) {
                            ToastAndroid.show('Car的数据为,'
                                + '编号=' + car[0].id
                                + 'car_type=' + car[0].car_type
                                + 'car_name=' + car[0].car_name
                                + 'driver_name=' + car[0].driver_name, ToastAndroid.SHORT);
                        }
                    }}
                />
            </View>
        )
    }


}


const styles = StyleSheet.create({
    welcom: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    button: {
        margin: 3,
        backgroundColor: 'white',
        padding: 10,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#cdcdcd'
    },
});
AppRegistry.registerComponent('RealmDemo', () => Test);

 
 
  
  • 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

三、总结 
本文主要是Realm数据库基本的增删改查。 
在此感谢http://www.lcode.org/react-native/

git地址: 
https://git.oschina.net/feiyangwei/ReactNativeRealmDemo.git

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_17775997/article/details/72675429

智能推荐

机器学习模型评分总结(sklearn)_model.score-程序员宅基地

文章浏览阅读1.5w次,点赞10次,收藏129次。文章目录目录模型评估评价指标1.分类评价指标acc、recall、F1、混淆矩阵、分类综合报告1.准确率方式一:accuracy_score方式二:metrics2.召回率3.F1分数4.混淆矩阵5.分类报告6.kappa scoreROC1.ROC计算2.ROC曲线3.具体实例2.回归评价指标3.聚类评价指标1.Adjusted Rand index 调整兰德系数2.Mutual Informa..._model.score

Apache虚拟主机配置mod_jk_apache mod_jk 虚拟-程序员宅基地

文章浏览阅读344次。因工作需要,在Apache上使用,重新学习配置mod_jk1. 分别安装Apache和Tomcat:2. 编辑httpd-vhosts.conf: LoadModule jk_module modules/mod_jk.so #加载mod_jk模块 JkWorkersFile conf/workers.properties #添加worker信息 JkLogFil_apache mod_jk 虚拟

Android ConstraintLayout2.0 过度动画MotionLayout MotionScene3_android onoffsetchanged-程序员宅基地

文章浏览阅读335次。待老夫kotlin大成,扩展:MotionLayout 与 CoordinatorLayout,DrawerLayout,ViewPager 的 交互众所周知,MotionLayout 的 动画是有完成度的 即Progress ,他在0-1之间变化,一.CoordinatorLayout 与AppBarLayout 交互时,其实就是监听 offsetliner 这个 偏移量的变化 同样..._android onoffsetchanged

【转】多核处理器的工作原理及优缺点_多核处理器怎么工作-程序员宅基地

文章浏览阅读8.3k次,点赞3次,收藏19次。【转】多核处理器的工作原理及优缺点《处理器关于多核概念与区别 多核处理器工作原理及优缺点》原文传送门  摘要:目前关于处理器的单核、双核和多核已经得到了普遍的运用,今天我们主要说说关于多核处理器的一些相关概念,它的工作与那里以及优缺点而展开的分析。1、多核处理器  多核处理器是指在一枚处理器中集成两个或多个完整的计算引擎(内核),此时处理器能支持系统总线上的多个处理器,由总..._多核处理器怎么工作

个人小结---eclipse/myeclipse配置lombok_eclispe每次运行个新项目都需要重新配置lombok吗-程序员宅基地

文章浏览阅读306次。1. eclipse配置lombok 拷贝lombok.jar到eclipse.ini同级文件夹下,编辑eclipse.ini文件,添加: -javaagent:lombok.jar2. myeclipse配置lombok myeclipse像eclipse配置后,定义对象后,直接访问方法,可能会出现飘红的报错。 如果出现报错,可按照以下方式解决。 ..._eclispe每次运行个新项目都需要重新配置lombok吗

【最新实用版】Python批量将pdf文本提取并存储到txt文件中_python批量读取文字并批量保存-程序员宅基地

文章浏览阅读1.2w次,点赞31次,收藏126次。#注意:笔者在2021/11/11当天调试过这个代码是可用的,由于pdfminer版本的更新,网络上大多数的语法没有更新,我也是找了好久的文章才修正了我的代码,仅供学习参考。1、把pdf文件移动到本代码文件的同一个目录下,笔者是在pycharm里面运行的项目,下图中的x1文件夹存储了我需要转换成文本文件的所有pdf文件。然后要在此目录下创建一个存放转换后的txt文件的文件夹,如图中的txt文件夹。2、编写代码 (1)导入所需库# coding:utf-8import ..._python批量读取文字并批量保存

随便推点

Scala:访问修饰符、运算符和循环_scala ===运算符-程序员宅基地

文章浏览阅读1.4k次。http://blog.csdn.net/pipisorry/article/details/52902234Scala 访问修饰符Scala 访问修饰符基本和Java的一样,分别有:private,protected,public。如果没有指定访问修饰符符,默认情况下,Scala对象的访问级别都是 public。Scala 中的 private 限定符,比 Java 更严格,在嵌套类情况下,外层_scala ===运算符

MySQL导出ER图为图片或PDF_数据库怎么导出er图-程序员宅基地

文章浏览阅读2.6k次,点赞7次,收藏19次。ER图导出为PDF或图片格式_数据库怎么导出er图

oracle触发器修改同一张表,oracle触发器中对同一张表进行更新再查询时,需加自制事务...-程序员宅基地

文章浏览阅读655次。CREATE OR REPLACE TRIGGER Trg_ReimFactBEFORE UPDATEON BP_OrderFOR EACH ROWDECLAREPRAGMA AUTONOMOUS_TRANSACTION;--自制事务fc varchar2(255);BEGINIF ( :NEW.orderstate = 2AND :NEW.TransState = 1 ) THENBEG..._oracle触发器更新同一张表

debounce与throttle区别及其应用场景_throttle和debounce应用在哪些场景-程序员宅基地

文章浏览阅读513次。目录概念debouncethrottle实现debouncethrottle应用场景debouncethrottle场景举例debouncethrottle概念debounce字面理解是“防抖”,何谓“防抖”,就是连续操作结束后再执行,以网页滚动为例,debounce要等到用户停止滚动后才执行,将连续多次执行合并为一次执行。throttle字面理解是“节流”,何谓“节流”,就是确保一段时..._throttle和debounce应用在哪些场景

java操作mongdb【超详细】_java 操作mongodb-程序员宅基地

文章浏览阅读526次。regex() $regex 正则表达式用于模式匹配,基本上是用于文档中的发现字符串 (下面有例子)注意:若未加 @Field("名称") ,则识别mongdb集合中的key名为实体类属性名。也可以对数组进行索引,如果被索引的列是数组时,MongoDB会索引这个数组中的每一个元素。也可以对整个Document进行索引,排序是预定义的按插入BSON数据的先后升序排列。save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。_java 操作mongodb

github push 推送代码失败. 使用ssh rsa key. remote: Support for password authentication was removed._git push remote: support for password authenticati-程序员宅基地

文章浏览阅读1k次。今天push代码到github仓库时出现这个报错TACKCHEN-MB0:tc-image tackchen$ git pushremote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.remote: Please see https://github.blog/2020-12-15-token-authentication_git push remote: support for password authentication was removed on august 1