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

Realm数据库使用教程(二):增加数据

查询数据

  • 同步操作:findAll查询
 /**
                 * 注意:RealmResults虽然实现了List接口,不过有很多方法是不能用的。
                 * 比如add、addAll、remove、clear等,
                 * 调用后会直接抛异常。
                 * 因为它们都被标记为@Deprecated了。
                 */
                RealmResults menList = mRealm.where(Men.class)
                        .findAll();
                for (int i = 0; i < menList.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            menList.get(i).getName() + "----" + menList.get(i).getAge());
                }
  • 异步操作:findAllAsync查询(isLoaded)
  RealmResults menList1 = mRealm.where(Men.class)
                        .findAllAsync();
                menList1.load();//等到查询完成。这将阻塞该线程,使查询再次同步
                if (menList1 != null && menList1.isLoaded()) {
                    for (int i = 0; i < menList1.size(); i++) {
                        Log.d("huangxiaoguo", "huangixoaguo==>" +
                                menList1.get(i).getName() + "----" + menList1.get(i).getAge());
                    }
                }
  • 异步操作:findAllAsync查询(RealmChangeListener)
menList2 = mRealm.where(Men.class)
                        .findAllAsync();
                menList2.addChangeListener(callback);

    /**
     * 异步操作的监听
     */
    private OrderedRealmCollectionChangeListener> callback = new OrderedRealmCollectionChangeListener>() {
        @Override
        public void onChange(RealmResults collection, OrderedCollectionChangeSet changeSet) {
            if (changeSet == null) {
                //第一次异步返回一个空的变更集。
                for (int i = 0; i < collection.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            collection.get(i).getName() + "----" + collection.get(i).getAge());
                }
            } else {
                //每次RealmResults被更新时都会被调用
            }
        }
    };
  @Override
    protected void onDestroy() {
        super.onDestroy();
        if (menList2 != null) {
            menList2.removeChangeListener(callback);
            menList2.removeAllChangeListeners();
        }
        if (mRealm != null && !mRealm.isClosed()) {
            mRealm.close();
        }
    }
  • findFirst :查询第一条数据
 Men men = mRealm.where(Men.class).findFirst();
                Log.d("huangxiaoguo", "huangixoaguo==>" +
                        men.getName() + "----" + men.getAge());
  • equalTo :根据条件单级查询
   RealmResults menRealmResults = mRealm.where(Men.class)
                        .equalTo("name", "huangxiaoguo1").findAll();
                for (int i = 0; i < menRealmResults.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            menRealmResults.get(i).getName() + "----" + menRealmResults.get(i).getAge());
                }
  • equalTo :根据条件多级查询
 //只能是一对一的表,一对多时,子表查询条件无效
                RealmResults people = mRealm.where(Person.class)
                        .equalTo("city", "杭州")
                        .equalTo("men.age", 20)//这是他的子类Men的属性
                        .findAll();
                for (int i = 0; i < people.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            people.get(i).getMen().getName() + "----" +
                            people.get(i).getMen().getAge());
                }
  • 聚合
    /**
                 * sum():对指定字段求和。
                 average():对指定字段求平均值。
                 min(): 对指定字段求最小值。
                 max() : 对指定字段求最大值。count : 求结果集的记录数量。
                 findAll(): 返回结果集所有字段,返回值为RealmResults队列
                 findAllSorted() : 排序返回结果集所有字段,返回值为RealmResults队列
                 between(), greaterThan(),lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()
                 equalTo() & notEqualTo()
                 contains(), beginsWith() & endsWith()
                 isNull() & isNotNull()
                 isEmpty()& isNotEmpty()
                 */
                RealmResults results = mRealm.where(Men.class).findAll();
                long sum = results.sum("age").longValue();
                long min = results.min("age").longValue();
                long max = results.max("age").longValue();
                double average = results.average("age");
                long matches = results.size();
                Log.d("huangxiaoguo", "sum=" + sum + ",min=" + min + ",max=" + max +
                        ",average=" + average + ",matches=" + matches);
  • or的使用
 RealmResults menList2 = mRealm.where(Men.class)
                        .equalTo("name", "huangxiaoguo0")
                        .or().equalTo("name", "huangxiaoguo2")
                        .findAll();
                for (int i = 0; i < menList2.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList2.get(i).getName() +
                            ",age=" + menList2.get(i).getAge());
                }
  • 排序
   RealmResults menList3 = mRealm.where(Men.class).findAll();
                menList3 = menList3.sort("age"); //根据age,正序排列
                for (int i = 0; i < menList3.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList3.get(i).getName() +
                            ",age=" + menList3.get(i).getAge());
                }
                menList3 = menList3.sort("age", Sort.DESCENDING);//逆序排列
                for (int i = 0; i < menList3.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList3.get(i).getName() +
                            ",age=" + menList3.get(i).getAge());
                }
  • 区间查询
  RealmResults menList4 = mRealm.where(Men.class)
                        .between("age", 0, 30)
                        .findAll();
                for (int i = 0; i < menList4.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList4.get(i).getName() +
                            ",age=" + menList4.get(i).getAge());
                }

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.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import io.realm.OrderedCollectionChangeSet;
import io.realm.OrderedRealmCollectionChangeListener;
import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;
import tsou.com.simple.realmtest.adapter.MyAdapter;
import tsou.com.simple.realmtest.bean.Men;
import tsou.com.simple.realmtest.bean.Person;
import tsou.com.simple.realmtest.utils.UIUtils;

public class QueryActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ListView mListview;
    private List titles = new ArrayList<>();
    private Realm mRealm;
    private RealmResults menList2;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (menList2 != null) {
            menList2.removeChangeListener(callback);
            menList2.removeAllChangeListeners();
        }
        if (mRealm != null && !mRealm.isClosed()) {
            mRealm.close();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        mRealm = UIUtils.getRealmInstance();
        initData();
        initView();
        initListener();
    }

    private void initData() {
        titles.add("同步操作:findAll查询");
        titles.add("异步操作:findAllAsync查询(isLoaded)");
        titles.add("异步操作:findAllAsync查询(RealmChangeListener)");
        titles.add("findFirst :查询第一条数据");
        titles.add("equalTo :根据条件单级查询");
        titles.add("equalTo :根据条件多级查询");
        titles.add("聚合");
        titles.add("or的使用");
        titles.add("排序");
        titles.add("区间查询");
    }

    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://同步操作:findAll查询
                /**
                 * 注意:RealmResults虽然实现了List接口,不过有很多方法是不能用的。
                 * 比如add、addAll、remove、clear等,
                 * 调用后会直接抛异常。
                 * 因为它们都被标记为@Deprecated了。
                 */
                RealmResults menList = mRealm.where(Men.class)
                        .findAll();
                for (int i = 0; i < menList.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            menList.get(i).getName() + "----" + menList.get(i).getAge());
                }

                break;
            case 1://异步操作:findAllAsync查询(isLoaded)
                RealmResults menList1 = mRealm.where(Men.class)
                        .findAllAsync();
                menList1.load();//等到查询完成。这将阻塞该线程,使查询再次同步
                if (menList1 != null && menList1.isLoaded()) {
                    for (int i = 0; i < menList1.size(); i++) {
                        Log.d("huangxiaoguo", "huangixoaguo==>" +
                                menList1.get(i).getName() + "----" + menList1.get(i).getAge());
                    }
                }
                break;
            case 2://异步操作:findAllAsync查询(RealmChangeListener)
                menList2 = mRealm.where(Men.class)
                        .findAllAsync();
                menList2.addChangeListener(callback);
                break;
            case 3://findFirst :查询第一条数据
                Men men = mRealm.where(Men.class).findFirst();
                Log.d("huangxiaoguo", "huangixoaguo==>" +
                        men.getName() + "----" + men.getAge());
                break;
            case 4://equalTo ——根据条件单级查询
                RealmResults menRealmResults = mRealm.where(Men.class)
                        .equalTo("name", "huangxiaoguo1").findAll();
                for (int i = 0; i < menRealmResults.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            menRealmResults.get(i).getName() + "----" + menRealmResults.get(i).getAge());
                }
                break;
            case 5://equalTo ——根据条件多级查询
                //只能是一对一的表,一对多时,子表查询条件无效
                RealmResults people = mRealm.where(Person.class)
                        .equalTo("city", "杭州")
                        .equalTo("men.age", 20)//这是他的子类Men的属性
                        .findAll();
                for (int i = 0; i < people.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            people.get(i).getMen().getName() + "----" +
                            people.get(i).getMen().getAge());
                }
                break;
            case 6://聚合
                /**
                 * sum():对指定字段求和。
                 average():对指定字段求平均值。
                 min(): 对指定字段求最小值。
                 max() : 对指定字段求最大值。count : 求结果集的记录数量。
                 findAll(): 返回结果集所有字段,返回值为RealmResults队列
                 findAllSorted() : 排序返回结果集所有字段,返回值为RealmResults队列
                 between(), greaterThan(),lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()
                 equalTo() & notEqualTo()
                 contains(), beginsWith() & endsWith()
                 isNull() & isNotNull()
                 isEmpty()& isNotEmpty()
                 */
                RealmResults results = mRealm.where(Men.class).findAll();
                long sum = results.sum("age").longValue();
                long min = results.min("age").longValue();
                long max = results.max("age").longValue();
                double average = results.average("age");
                long matches = results.size();
                Log.d("huangxiaoguo", "sum=" + sum + ",min=" + min + ",max=" + max +
                        ",average=" + average + ",matches=" + matches);
                break;
            case 7://or的使用
                RealmResults menList2 = mRealm.where(Men.class)
                        .equalTo("name", "huangxiaoguo0")
                        .or().equalTo("name", "huangxiaoguo2")
                        .findAll();
                for (int i = 0; i < menList2.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList2.get(i).getName() +
                            ",age=" + menList2.get(i).getAge());
                }
                break;
            case 8://排序
                RealmResults menList3 = mRealm.where(Men.class).findAll();
                menList3 = menList3.sort("age"); //根据age,正序排列
                for (int i = 0; i < menList3.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList3.get(i).getName() +
                            ",age=" + menList3.get(i).getAge());
                }
                menList3 = menList3.sort("age", Sort.DESCENDING);//逆序排列
                for (int i = 0; i < menList3.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList3.get(i).getName() +
                            ",age=" + menList3.get(i).getAge());
                }

                break;
            case 9:
                RealmResults menList4 = mRealm.where(Men.class)
                        .between("age", 0, 30)
                        .findAll();
                for (int i = 0; i < menList4.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList4.get(i).getName() +
                            ",age=" + menList4.get(i).getAge());
                }
                break;

        }
    }

    /**
     * 异步操作的监听
     */
    private OrderedRealmCollectionChangeListener> callback = new OrderedRealmCollectionChangeListener>() {
        @Override
        public void onChange(RealmResults collection, OrderedCollectionChangeSet changeSet) {
            if (changeSet == null) {
                //第一次异步返回一个空的变更集。
                for (int i = 0; i < collection.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            collection.get(i).getName() + "----" + collection.get(i).getAge());
                }
            } else {
                //每次RealmResults被更新时都会被调用
            }
        }
    };
}

Realm数据库使用教程(四):更新数据

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

你可能感兴趣的:(android-数据库)