Android开发

Realm数据库使用教程(二),android工程师面试题目

本文主要是介绍Realm数据库使用教程(二),android工程师面试题目,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

这里写图片描述

这里写图片描述

  • 同步操作:增加一对一表,Person包含一个Men(以copyToRealm为例)

final Person person1 = new Person();

person1.setCity(“杭州”);

person1.setProject(“android”);

Men men1 = new Men();

men1.setName(“huangxiaoguo”);

men1.setAge(new Random().nextInt(100));

person1.setMen(men1);

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

//如果使用copyToRealmOrUpdate,Person需要主键

realm.copyToRealm(person1);

}

});

这里写图片描述

这里写图片描述

  • 同步操作:增加一对多表,Person包含多个Men(以executeTransaction为例)

MorePerson类在文章最下方提供

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

MorePerson morePerson = realm.createObject(MorePerson.class);

morePerson.setCity(“杭州”);

morePerson.setProject(“开发工程师”);

morePerson.setTime(simpleDateFormat.format(new Date()));

for (int i = 0; i < 3; i++) {

Men men = realm.createObject(Men.class);

men.setName(“huangxiaoguo” + i);

men.setAge(new Random().nextInt(100));

morePerson.getMens().add(men);

}

}

});

注意:在Realm中不能使用android原有的list集合,需要Realm特定的RealmList集合!

这里写图片描述

这里写图片描述

  • 同步操作:增加一对多表,Person包含多个Men(以copyToRealm为例)

final MorePerson morePerson1 = new MorePerson();

morePerson1.setCity(“杭州”);

morePerson1.setProject(“开发工程师”);

morePerson1.setTime(simpleDateFormat.format(new Date()));

RealmList menList = new RealmList<>();

for (int i = 0; i < 3; i++) {

Men men2 = new Men();

men2.setName(“huangxiaoguo” + i);

men2.setAge(new Random().nextInt(100));

menList.add(men2);

}

morePerson1.setMens(menList);

for (int i = 0; i < 3; i++) {

Men men2 = new Men();

men2.setName(“huangxiaoguo” + i);

men2.setAge(new Random().nextInt(100));

morePerson1.getMens().add(men2);

}

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

realm.copyToRealm(morePerson1);

}

});

这里写图片描述

这里写图片描述

  • 同步操作:beginTransaction和commitTransaction方法插入数据(不建议使用)

//注意:在UI和后台线程同时开启创建write的事务,可能会导致ANR错误。

// 为了避免该问题,可以使用executeTransactionAsync来实现。

mRealm.beginTransaction();//开启事务

Student student1 = mRealm.createObject(Student.class);

student1.setName(“事务方式插入数据”);

student1.setNum(new Random().nextInt(100) + 100);

mRealm.commitTransaction();

这里写图片描述

异步操作(建议使用)


  • 异步操作:使用executeTransactionAsync直接插入数据

//该方法会开启一个子线程来执行事务,并且在执行完成后进行结果通知。

realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

Student student2 = realm.createObject(Student.class);

student2.setName(“使用executeTransactionAsync直接插入数据”);

student2.setNum(new Random().nextInt(100) + 200);

}

});

异步操作需要在activity不可见或关闭时取消任务

@Override

protected void onDestroy() {

super.onDestroy();

if (realmAsyncTask != null && !realmAsyncTask.isCancelled()) {

realmAsyncTask.cancel();

}

if (mRealm != null && !mRealm.isClosed()) {

mRealm.close();

}

}

这里写图片描述

  • 异步操作:使用executeTransactionAsync并且进行监听

//注意:如果当Acitivity或Fragment被销毁时,在OnSuccess或OnError中执行UI操作,

// 将导致程序奔溃 。用RealmAsyncTask .cancel();可以取消事务

//在onStop或onDestroy中调用,避免crash

realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

Student student2 = realm.createObject(Student.class);

student2.setName(“使用executeTransactionAsync监听”);

student2.setNum(new Random().nextInt(100) + 300);

}

}, new Realm.Transaction.OnSuccess() {

@Override

public void onSuccess() {

UIUtils.showToast(“添加成功”);

}

}, new Realm.Transaction.OnError() {

@Override

public void one rror(Throwable error) {

UIUtils.showToast(“添加失败”);

}

});

这里写图片描述

将Json字符串转化为对象


  • 将Json字符串转化为对象(使用Json字符串插入数据)

模拟网络数据

{

“reason”: “SUCCESSED!”,

“result”: [

{

“dapandata”: {},

“data”: {

“buyFive”: “113700”,

“buyFivePri”: “8.42”,

“buyFour”: “87200”,

“buyThreePri”: “8.35”,

“buyTwoPri”: “8.36”,

“competitivePri”: “8.37”,

“date”: “2012-12-11”,

“gid”: “sh601009”,

“increase”: “43.99”,

“name”: “南京银行”,

“nowPri”: “8.37”,

“reservePri”: “8.38”,

“sellFive”: “214535”,

“time”: “15:03:06”,

“todayMax”: “8.55”,

“traAmount”: “290889560”,

“traNumber”: “34501453”,

“yestodEndPri”: “8.26”

},

“gopicture”: {

“dayurl”: “http://image.sinajs.cn/newchart/daily/n/sh601009.gif”,

“minurl”: “http://image.sinajs.cn/newchart/min/n/sh601009.gif”,

“monthurl”: “http://image.sinajs.cn/newchart/monthly/n/sh601009.gif”,

“weekurl”: “http://image.sinajs.cn/newchart/weekly/n/sh601009.gif”

}

}

],

“resultcode”: “200”

}

创建数据库Model

package tsou.com.simple.realmtest.bean;

import io.realm.RealmObject;

/**

  • Created by Administrator on 2017/12/18 0018.

  • Realm 解析 JSON 时遵循如下规则:

  • 使用包含空值(null)的 JSON 创建对象:

  • 对于非必须(可为空值的属性),设置其值为 null;

  • 对于必须(不可为空值的属性),抛出异常;

  • 使用包含空值(null)的 JSON 更新对象:

  • 对于非必须(可为空值的属性),设置其值为 null;

  • 对于必须(不可为空值的属性),抛出异常;

  • 使用不包含对应属性的 JSON: * 该属性保持不变

*/

public class Stock extends RealmObject {

/**

  • buyFive : 113700

  • buyFivePri : 8.42

  • buyFour : 87200

  • buyThreePri : 8.35

  • buyTwoPri : 8.36

  • competitivePri : 8.37

  • date : 2012-12-11

  • gid : sh601009

  • increase : 43.99

  • name : 南京银行

  • nowPri : 8.37

  • reservePri : 8.38

  • sellFive : 214535

  • time : 15:03:06

  • todayMax : 8.55

  • traAmount : 290889560

  • traNumber : 34501453

  • yestodEndPri : 8.26

*/

private String buyFi

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

ve;

private String buyFivePri;

private String buyFour;

private String buyThreePri;

private String buyTwoPri;

private String competitivePri;

private String date;

private String gid;

private String increase;

private String name;

private String nowPri;

private String reservePri;

private String sellFive;

private String time;

private String todayMax;

private String traAmount;

private String traNumber;

private String yestodEndPri;

public String getBuyFive() {

return buyFive;

}

public void setBuyFive(String buyFive) {

this.buyFive = buyFive;

}

public String getBuyFivePri() {

return buyFivePri;

}

public void setBuyFivePri(String buyFivePri) {

this.buyFivePri = buyFivePri;

}

public String getBuyFour() {

return buyFour;

}

public void setBuyFour(String buyFour) {

this.buyFour = buyFour;

}

public String getBuyThreePri() {

return buyThreePri;

}

public void setBuyThreePri(String buyThreePri) {

this.buyThreePri = buyThreePri;

}

public String getBuyTwoPri() {

return buyTwoPri;

}

public void setBuyTwoPri(String buyTwoPri) {

this.buyTwoPri = buyTwoPri;

}

public String getCompetitivePri() {

return competitivePri;

}

public void setCompetitivePri(String competitivePri) {

this.competitivePri = competitivePri;

}

public String getDate() {

return date;

}

public void setDate(String date) {

this.date = date;

}

public String getGid() {

return gid;

}

public void setGid(String gid) {

this.gid = gid;

}

public String getIncrease() {

return increase;

}

public void setIncrease(String increase) {

this.increase = increase;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getNowPri() {

return nowPri;

}

public void setNowPri(String nowPri) {

this.nowPri = nowPri;

}

public String getReservePri() {

return reservePri;

}

public void setReservePri(String reservePri) {

this.reservePri = reservePri;

}

public String getSellFive() {

return sellFive;

}

public void setSellFive(String sellFive) {

this.sellFive = sellFive;

}

public String getTime() {

return time;

}

public void setTime(String time) {

this.time = time;

}

public String getTodayMax() {

return todayMax;

}

public void setTodayMax(String todayMax) {

this.todayMax = todayMax;

}

public String getTraAmount() {

return traAmount;

}

public void setTraAmount(String traAmount) {

this.traAmount = traAmount;

}

public String getTraNumber() {

return traNumber;

}

public void setTraNumber(String traNumber) {

this.traNumber = traNumber;

}

public String getYestodEndPri() {

return yestodEndPri;

}

public void setYestodEndPri(String yestodEndPri) {

this.yestodEndPri = yestodEndPri;

}

}

解析并插入数据库

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

String stockJson = UIUtils.getJson(“Stock”);

try {

JSONObject js = new JSONObject(stockJson);

String result = js.optString(“result”);

JSONArray jsonArray = new JSONArray(result);

String resultOne = jsonArray.optString(0);

JSONObject js2 = new JSONObject(resultOne);

String data = js2.optString(“data”);

realm.createObjectFromJson(Stock.class, data);

} catch (JSONException e) {

e.printStackTrace();

}

}

});

这里写图片描述

好了,到这里增添数据的方法基本上都介绍完了,如果数据多的话建议使用异步!其他功能请看下文!

Realm数据库使用教程(三):查询数据

Demo地址:https://gitee.com/huangxiaoguo/Realm


这里提供整个activity代码以供参考:

package tsou.com.simple.realmtest;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ListView;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.Random;

import io.realm.Realm;

import io.realm.RealmAsyncTask;

import io.realm.RealmList;

import tsou.com.simple.realmtest.adapter.MyAdapter;

import tsou.com.simple.realmtest.bean.Men;

import tsou.com.simple.realmtest.bean.MorePerson;

import tsou.com.simple.realmtest.bean.Person;

import tsou.com.simple.realmtest.bean.Stock;

import tsou.com.simple.realmtest.bean.Student;

import tsou.com.simple.realmtest.bean.User;

import tsou.com.simple.realmtest.utils.UIUtils;

public class AddActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

private ListView mListview;

private List titles = new ArrayList<>();

private Realm mRealm;

private SimpleDateFormat simpleDateFormat;

private RealmAsyncTask realmAsyncTask;

@Override

protected void onDestroy() {

super.onDestroy();

if (realmAsyncTask != null && !realmAsyncTask.isCancelled()) {

realmAsyncTask.cancel();

}

if (mRealm != null && !mRealm.isClosed()) {

mRealm.close();

}

}

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_add);

mRealm = UIUtils.getRealmInstance();

simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

initData();

initView();

initListener();

}

private void initData() {

//同步操作**********

//注意:如果在UI线程中插入过多的数据,可能会导致主线程拥塞。

titles.add(“同步操作:使用executeTransaction方法插入数据”);

titles.add(“同步操作:使用copyToRealmOrUpdate方法插入数据”);

titles.add(“同步操作:使用copyToRealm方法插入数据”);

titles.add(“同步操作:增加一对一表,Person包含Men(以executeTransaction为例)”);

titles.add(“同步操作:增加一对一表,Person包含一个Men(以copyToRealm为例)”);

titles.add(“同步操作:增加一对多表,Person包含多个Men(以executeTransaction为例)”);

titles.add(“同步操作:增加一对多表,Person包含多个Men(以copyToRealm为例)”);

titles.add(“同步操作:beginTransaction和commitTransaction方法插入数据”);

//异步操作**********

titles.add(“异步操作:使用executeTransactionAsync直接插入数据”);

titles.add(“异步操作:使用executeTransactionAsync并且进行监听”);

//******将Json字符串转化为对象

titles.add(“将Json字符串转化为对象(使用Json字符串插入数据)”);

}

private void initView() {

mListview = (ListView) findViewById(R.id.listview);

mListview.setAdapter(new MyAdapter(this, titles));

}

private void initListener() {

mListview.setOnItemClickListener(this);

}

@Override

public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

switch (position) {

default:

break;

case 0://同步操作:使用executeTransaction方法插入数据

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

Student student = realm.createObject(Student.class);

student.setName(“使用executeTransaction方法插入数据”);

student.setNum(new Random().nextInt(20));

}

});

break;

case 1://同步操作:使用copyToRealmOrUpdate方法插入数据

/**

  • 当Model中存在主键的时候,推荐使用copyToRealmOrUpdate方法插入数据。

  • 如果对象存在,就更新该对象;反之,它会创建一个新的对象。

*/

final User user = new User();

user.setId(2);

user.setName(“使用copyToRealmOrUpdate方法插入数据”);

user.setAge(new Random().nextInt(20));

user.setSex(“同步”);

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

realm.copyToRealmOrUpdate(user);

}

});

break;

case 2://同步操作:使用copyToRealm方法插入数据

/**

*若该Model没有主键,使用copyToRealm方法,否则将抛出异常。

*/

final Student student = new Student();

student.setName(“使用copyToRealm方法插入数据”);

student.setNum(new Random().nextInt(20));

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

realm.copyToRealm(student);

}

});

break;

case 3://同步操作:增加一对一表,Person包含Men(以executeTransaction为例)

//以executeTransaction为例

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

Person person = realm.createObject(Person.class);

person.setCity(“杭州”);

person.setProject(“android”);

Men men = realm.createObject(Men.class);

men.setName(“huangxiaoguo”);

men.setAge(25);

person.setMen(men);

}

});

break;

case 4://同步操作:增加一对一表,Person包含Men(以copyToRealm为例)

final Person person1 = new Person();

person1.setCity(“杭州”);

person1.setProject(“android”);

Men men1 = new Men();

men1.setName(“huangxiaoguo”);

men1.setAge(new Random().nextInt(100));

person1.setMen(men1);

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

//如果使用copyToRealmOrUpdate,Person需要主键

realm.copyToRealm(person1);

}

});

break;

case 5://同步操作:增加一对多表,Person包含多个Men(以executeTransaction为例)

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

MorePerson morePerson = realm.createObject(MorePerson.class);

morePerson.setCity(“杭州”);

morePerson.setProject(“开发工程师”);

morePerson.setTime(simpleDateFormat.format(new Date()));

for (int i = 0; i < 3; i++) {

Men men = realm.createObject(Men.class);

men.setName(“huangxiaoguo” + i);

men.setAge(new Random().nextInt(100));

morePerson.getMens().add(men);

}

}

});

break;

case 6://同步操作:增加一对多表,Person包含多个Men(以copyToRealm为例)

final MorePerson morePerson1 = new MorePerson();

morePerson1.setCity(“杭州”);

morePerson1.setProject(“开发工程师”);

morePerson1.setTime(simpleDateFormat.format(new Date()));

RealmList menList = new RealmList<>();

for (int i = 0; i < 3; i++) {

Men men2 = new Men();

men2.setName(“huangxiaoguo” + i);

men2.setAge(new Random().nextInt(100));

menList.add(men2);

}

morePerson1.setMens(menList);

for (int i = 0; i < 3; i++) {

Men men2 = new Men();

men2.setName(“huangxiaoguo” + i);

men2.setAge(new Random().nextInt(100));

morePerson1.getMens().add(men2);

}

mRealm.executeTransaction(new Realm.Transaction() {

@Override

public void execute(Realm realm) {

realm.copyToRealm(morePerson1);

}

});

break;

case 7://同步操作:beginTransaction和commitTransaction方法插入数据

//注意:在UI和后台线程同时开启创建write的事务,可能会导致ANR错误。

// 为了避免该问题,可以使用executeTransactionAsync来实现。

mRealm.beginTransaction();//开启事务

这篇关于Realm数据库使用教程(二),android工程师面试题目的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!