Android greenDAO数据库开发梳理 : Android ORM for your SQLite database

Android greenDAO数据库开发梳理 : Android ORM for your SQLite database,第1张

概述首先名确一个关键字:Objectelationmapping(ORM):对象/关系映射(ORM)greenDao是什么?为什么会产生这个框架,也就是说greenDao的诞生是为了解决什么需求的?关于 Android 中常用的数据存储方式有sharePreference存储、网络存储、文件存储等,但是对于数据量比较大、结构复杂的数据

首先名确一个关键字:Object/relation mapPing (ORM):对象/关系映射(ORM)

greenDao是什么?为什么会产生这个框架,也就是说greenDao的诞生是为了解决什么需求的?

关于 AndroID 中常用的数据存储方式有sharePreference存储、网络存储、文件存储等,但是对于数据量比较大、结构复杂的数据我们想要存储只能通过数据库进行处理,AndroID 系统中集成了一个轻量级的数据库: sqlite 数据库,但是使用起来比较繁琐和复杂,所以 AndroID 又新推出了Jetpack 组件库:Room 持久性库,Room 持久性库在 sqlite 的基础上提供了一个抽象层,让用户能够在充分利用 sqlite 的强大功能的同时,获享更强健的数据库访问机制。如果不使用这个新的组件库或者说在jetpack组件库之前,我们怎么能更方便快捷的访问 *** 作sqliteDatabase数据库呢?开源ORM 框架———greenDAO框架。

下面我们来看官网对greenDAO的描述:GreenDAO的本质是为存储在关系数据库sqlite中的数据提供一个面向对象的接口。只需定义数据模型,Green DAO将创建Java数据对象(实体)和DAO(数据访问对象)。这将为您节省大量无聊的代码,只需来回移动数据。除此之外,Green DAO还提供一些高级ORM特性类似于会话缓存、急切加载和活动实体。

greenDAO’s Features at a glanceMaximum performance (probably the fastest ORM for AndroID); our benchmarks are open sourced tooEasy to use powerful APIs covering relations and joinsMinimal memory consumptionSmall library size (<100KB) to keep your build times low and to avoID the 65k method limitDatabase encryption: greenDAO supports sqlCipher to keep your user’s data safeStrong community: More than 5.000 GitHub stars show there is a strong and active community

You want to learn more about greenDAO features like active entitIEs, protocol buffers support, or eager loading?  Then have a look at our full feature list.

下面是翻译:

GreenDAO的特点一目了然最大性能(可能是AndroID最快的ORM);我们的基准测试也是开源的。易用覆盖关系和联接的强大API极小内存消耗小的库大小(<100 kb),以保持较低的构建时间,并避免65k方法限制数据库加密*GreenDAO支持sqlCiPHER,以确保用户数据的安全强群落:5.000多名GitHub明星展示了一个强大而活跃的社区

您想了解有关GreenDAO功能的更多信息,如活动实体、协议缓冲区支持或急切加载?那就来看看我们的特征列表.

官网地址如下:https://greenrobot.org/greendao/

GitHub地址:https://github.com/greenrobot/greenDAO

下面给出使用实例:

首先创建一个项目、添加依赖包:

Add the following Gradle configuration to your AndroID project. In your root build.gradle file:

buildscript {    repositorIEs {        jcenter()        mavenCentral() // add repository    }    dependencIEs {        classpath 'com.androID.tools.build:gradle:3.5.3'        classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0' // add plugin    }}

In your app modules app/build.gradle file:

apply plugin: 'com.androID.application'apply plugin: 'org.greenrobot.greendao' // apply plugin dependencIEs {    implementation 'org.greenrobot:greendao:3.3.0' // add library}

Note that this hooks up the greenDAO Gradle plugin to your build process. When you build your project, it generates classes like DaoMaster, DaoSession and DAOs.

下面来看一个示例效果:在EditText中输入文字(比如做课堂笔记Note),点击添加按钮,就会将输入的文字笔记添加到数据库。下面是一个RecyclerVIEw列表,它将数据库中的内容全部读出并展示,点击item条目会删除该条目同时删除数据库中的记录。

对应数据库字段以及数据:

下面按照实际的开发步骤贴出代码:

1.首先我们需要定义一个实体对象(Entity Object),它是我们映射到数据库中的对象,这里你只需要定义实体对象的字段就可以,其他的getter()\setter()方法等编译器会自动生成:

public class Note {    private Long ID;    private String text;    private String comment;    private java.util.Date date;    private NoteType type;}

然后点击AndroID studio-->build-->Make Project按钮后,编译器就会自动创建完整的实体类:

完整的实体类:

package org.greenrobot.greendao.example;import org.greenrobot.greendao.annotation.Convert;import org.greenrobot.greendao.annotation.Entity;import org.greenrobot.greendao.annotation.Generated;import org.greenrobot.greendao.annotation.ID;import org.greenrobot.greendao.annotation.Index;import org.greenrobot.greendao.annotation.NotNull;/** * Entity mapped to table "NOTE". */@Entity(indexes = {    @Index(value = "text, date DESC", unique = true)})public class Note {    @ID    private Long ID;    @NotNull    private String text;    private String comment;    private java.util.Date date;    @Convert(converter = NoteTypeConverter.class, columnType = String.class)    private NoteType type;    @Generated(hash = 1272611929)    public Note() {    }    public Note(Long ID) {        this.ID = ID;    }    @Generated(hash = 1686394253)    public Note(Long ID, @NotNull String text, String comment, java.util.Date date, NoteType type) {        this.ID = ID;        this.text = text;        this.comment = comment;        this.date = date;        this.type = type;    }    public Long getID() {        return ID;    }    public voID setID(Long ID) {        this.ID = ID;    }    @NotNull    public String getText() {        return text;    }    /** Not-null value; ensure this value is available before it is saved to the database. */    public voID setText(@NotNull String text) {        this.text = text;    }    public String getComment() {        return comment;    }    public voID setComment(String comment) {        this.comment = comment;    }    public java.util.Date getDate() {        return date;    }    public voID setDate(java.util.Date date) {        this.date = date;    }    public NoteType getType() {        return type;    }    public voID setType(NoteType type) {        this.type = type;    }}

GreenDao并且会自动生成3个核心类如下:

3个核心类介绍

DaoMaster:

使用 greenDAO 的入口点。DaoMaster 负责管理数据库对象(sqliteDatabase)和 DAO 类(对象),我们可以通过它内部类 OpenHelper 和 DevOpenHelper sqliteOpenHelper 创建不同模式的 sqlite 数据库。

DaoSession :

管理指定模式下的所有 DAO 对象,DaoSession提供了一些通用的持久性方法比如插入、负载、更新、更新和删除实体。

XxxDAO :

每个实体类 greenDAO都会生成一个与之对应DAO对象,如:User实体,则会生成一个一个UserDao类,通过这和UserDao对象调用queryBuilder()进而调用查询条件的方法、增删改查的方法等。

EntitIEs

可持久化对象。通常, 实体对象代表一个数据库行使用标准 Java 属性(如一个POJO 或 JavaBean )。

三个核心类与数据实体对象之间的关系:

DaoMaster.class:

package org.greenrobot.greendao.example;import androID.content.Context;import androID.database.sqlite.sqliteDatabase;import androID.database.sqlite.sqliteDatabase.CursorFactory;import androID.util.Log;import org.greenrobot.greendao.AbstractDaoMaster;import org.greenrobot.greendao.database.StandardDatabase;import org.greenrobot.greendao.database.Database;import org.greenrobot.greendao.database.DatabaSEOpenHelper;import org.greenrobot.greendao.IDentityscope.IDentityScopeType;// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT./** * Master of DAO (schema version 1000): kNows all DAOs. */public class DaoMaster extends AbstractDaoMaster {    public static final int SCHEMA_VERSION = 1000;    /** Creates underlying database table using DAOs. */    public static voID createalltables(Database db, boolean ifNotExists) {        NoteDao.createtable(db, ifNotExists);    }    /** Drops underlying database table using DAOs. */    public static voID dropAlltables(Database db, boolean ifExists) {        NoteDao.droptable(db, ifExists);    }    /**     * WARNING: Drops all table on Upgrade! Use only during development.     * ConvenIEnce method using a {@link DevOpenHelper}.     */    public static DaoSession newDevSession(Context context, String name) {        Database db = new DevOpenHelper(context, name).getWritableDb();        DaoMaster daoMaster = new DaoMaster(db);        return daoMaster.newSession();    }    public DaoMaster(sqliteDatabase db) {        this(new StandardDatabase(db));    }    public DaoMaster(Database db) {        super(db, SCHEMA_VERSION);        registerDaoClass(NoteDao.class);    }    public DaoSession newSession() {        return new DaoSession(db, IDentityScopeType.Session, daoConfigMap);    }    public DaoSession newSession(IDentityScopeType type) {        return new DaoSession(db, type, daoConfigMap);    }    /**     * Calls {@link #createalltables(Database, boolean)} in {@link #onCreate(Database)} -     */    public static abstract class OpenHelper extends DatabaSEOpenHelper {        public OpenHelper(Context context, String name) {            super(context, name, SCHEMA_VERSION);        }        public OpenHelper(Context context, String name, CursorFactory factory) {            super(context, name, factory, SCHEMA_VERSION);        }        @OverrIDe        public voID onCreate(Database db) {            Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);            createalltables(db, false);        }    }    /** WARNING: Drops all table on Upgrade! Use only during development. */    public static class DevOpenHelper extends OpenHelper {        public DevOpenHelper(Context context, String name) {            super(context, name);        }        public DevOpenHelper(Context context, String name, CursorFactory factory) {            super(context, name, factory);        }        @OverrIDe        public voID onUpgrade(Database db, int oldVersion, int newVersion) {            Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropPing all tables");            dropAlltables(db, true);            onCreate(db);        }    }}

DaoSession.class: 

package org.greenrobot.greendao.example;import java.util.Map;import org.greenrobot.greendao.AbstractDao;import org.greenrobot.greendao.AbstractDaoSession;import org.greenrobot.greendao.database.Database;import org.greenrobot.greendao.IDentityscope.IDentityScopeType;import org.greenrobot.greendao.internal.DaoConfig;import org.greenrobot.greendao.example.Note;import org.greenrobot.greendao.example.NoteDao;// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT./** * {@inheritDoc} *  * @see org.greenrobot.greendao.AbstractDaoSession */public class DaoSession extends AbstractDaoSession {    private final DaoConfig noteDaoConfig;    private final NoteDao noteDao;    public DaoSession(Database db, IDentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>            daoConfigMap) {        super(db);        noteDaoConfig = daoConfigMap.get(NoteDao.class).clone();        noteDaoConfig.initIDentityScope(type);        noteDao = new NoteDao(noteDaoConfig, this);        registerDao(Note.class, noteDao);    }        public voID clear() {        noteDaoConfig.clearIDentityScope();    }    public NoteDao getNoteDao() {        return noteDao;    }}

你不用太多的关心上面两个类。我们来看一下数据库的初始化,以及数据库的库名和数据库中与我们这个实体类Note.class对象对应的数据表在哪里命名?

数据库的初始化:自定义MyApplication.class继承Application类,并在Manifest中声明这个MyApplication.class如下:

package org.greenrobot.greendao.example;import androID.app.Application;import androID.content.Context;import org.greenrobot.greendao.database.Database;public class MyApplication extends Application {    private DaoSession daoSession;    @OverrIDe    public voID onCreate() {        super.onCreate();        /**         * 1、通过DaoMaster内部类OpenHelper获取需要连接的一个标准的数据库对象:sqliteDatabase         */        ExampleOpenHelper helper = new ExampleOpenHelper(this, "notes-db");        Database db = helper.getWritableDb();        /**         * 2、创建数据库管理对象         * DaoMaster是使用greenDAO的入口点。DaoMaster负责管理数据库对象(sqliteDatabase)和DAO类(对象),         * 我们可以通过它内部类OpenHelper和DevOpenHelper sqliteOpenHelper创建不同模式的sqlite数据库         */        DaoMaster daoMaster = new DaoMaster(db);        /**         * 3、创建数据库链接会话         * 管理指定模式下的所有DAO对象,DaoSession提供了一些通用的持久性方法比如插入、负载、更新、更新和删除实体。         */        daoSession = daoMaster.newSession();    }    public DaoSession getDaoSession() {        return daoSession;    }    public static class ExampleOpenHelper extends DaoMaster.OpenHelper {        public ExampleOpenHelper(Context context, String name) {            super(context, name);        }        @OverrIDe        public voID onCreate(Database db) {            super.onCreate(db);            // Insert some example data.            // INSERT INTO NOTE (_ID, DATE, TEXT) VALUES(1, 0, 'Example Note')            db.execsql("INSERT INTO " + NoteDao.tablename + " (" +                    NoteDao.PropertIEs.ID.columnname + ", " +                    NoteDao.PropertIEs.Date.columnname + ", " +                    NoteDao.PropertIEs.Text.columnname +                    ") VALUES(1, 0, 'Example Note')");        }    }}

看上面的代码,第1步中获取数据库对象时new ExampleOpenHelper(this, "notes-db");第二个参数用于指定数据库的库名。

你也可以不用像上面那样继承DaoMaster.OpenHelper那样自定义自己的ExampleOpenHelper。可以直接使用DaoMaster.OpenHelper类进行获取数据库对象:

public class MyApplication extends Application {    public static DaoSession mSession;    @OverrIDe    public voID onCreate() {        super.onCreate();        initDb();    }    /**     * 连接数据库并创建会话     */    public voID initDb() {        // 1、获取需要连接的数据库对象        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "test.db");        sqliteDatabase db = devOpenHelper.getWritableDatabase();        // 2、创建数据库管理对象        DaoMaster daoMaster = new DaoMaster(db);        // 3、创建数据库会话        mSession = daoMaster.newSession();    }    // 供外接使用    public DaoSession getDaoSession() {        return mSession;    }}

我们还有一个自动生成的类没说,NoteDao.class:

package org.greenrobot.greendao.example;import androID.database.Cursor;import androID.database.sqlite.sqliteStatement;import org.greenrobot.greendao.AbstractDao;import org.greenrobot.greendao.Property;import org.greenrobot.greendao.internal.DaoConfig;import org.greenrobot.greendao.database.Database;import org.greenrobot.greendao.database.DatabaseStatement;// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT./**  * DAO for table "NOTE".*/public class NoteDao extends AbstractDao<Note, Long> {    public static final String tablename = "NOTE";    /**     * PropertIEs of entity Note.<br/>     * Can be used for queryBuilder and for referencing column names.     */    public static class PropertIEs {        public final static Property ID = new Property(0, Long.class, "ID", true, "_ID");        public final static Property Text = new Property(1, String.class, "text", false, "TEXT");        public final static Property Comment = new Property(2, String.class, "comment", false, "COMMENT");        public final static Property Date = new Property(3, java.util.Date.class, "date", false, "DATE");        public final static Property Type = new Property(4, String.class, "type", false, "TYPE");    }    private final NoteTypeConverter typeConverter = new NoteTypeConverter();    public NoteDao(DaoConfig config) {        super(config);    }        public NoteDao(DaoConfig config, DaoSession daoSession) {        super(config, daoSession);    }    /** Creates the underlying database table. */    public static voID createtable(Database db, boolean ifNotExists) {        String constraint = ifNotExists? "IF NOT EXISTS ": "";        db.execsql("CREATE table " + constraint + "\"NOTE\" (" + //                "\"_ID\" INTEGER PRIMARY KEY ," + // 0: ID                "\"TEXT\" TEXT NOT NulL ," + // 1: text                "\"COMMENT\" TEXT," + // 2: comment                "\"DATE\" INTEGER," + // 3: date                "\"TYPE\" TEXT);"); // 4: type        // Add Indexes        db.execsql("CREATE UNIQUE INDEX " + constraint + "IDX_NOTE_TEXT_DATE_DESC ON \"NOTE\"" +                " (\"TEXT\" ASC,\"DATE\" DESC);");    }    /** Drops the underlying database table. */    public static voID droptable(Database db, boolean ifExists) {        String sql = "DROP table " + (ifExists ? "IF EXISTS " : "") + "\"NOTE\"";        db.execsql(sql);    }    @OverrIDe    protected final voID bindValues(DatabaseStatement stmt, Note entity) {        stmt.clearBindings();         Long ID = entity.getID();        if (ID != null) {            stmt.bindLong(1, ID);        }        stmt.bindString(2, entity.getText());         String comment = entity.getComment();        if (comment != null) {            stmt.bindString(3, comment);        }         java.util.Date date = entity.getDate();        if (date != null) {            stmt.bindLong(4, date.getTime());        }         NoteType type = entity.getType();        if (type != null) {            stmt.bindString(5, typeConverter.convertToDatabaseValue(type));        }    }    @OverrIDe    protected final voID bindValues(sqliteStatement stmt, Note entity) {        stmt.clearBindings();         Long ID = entity.getID();        if (ID != null) {            stmt.bindLong(1, ID);        }        stmt.bindString(2, entity.getText());         String comment = entity.getComment();        if (comment != null) {            stmt.bindString(3, comment);        }         java.util.Date date = entity.getDate();        if (date != null) {            stmt.bindLong(4, date.getTime());        }         NoteType type = entity.getType();        if (type != null) {            stmt.bindString(5, typeConverter.convertToDatabaseValue(type));        }    }    @OverrIDe    public Long readKey(Cursor cursor, int offset) {        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);    }        @OverrIDe    public Note readEntity(Cursor cursor, int offset) {        Note entity = new Note( //            cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // ID            cursor.getString(offset + 1), // text            cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // comment            cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)), // date            cursor.isNull(offset + 4) ? null : typeConverter.convertToEntityProperty(cursor.getString(offset + 4)) // type        );        return entity;    }         @OverrIDe    public voID readEntity(Cursor cursor, Note entity, int offset) {        entity.setID(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));        entity.setText(cursor.getString(offset + 1));        entity.setComment(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));        entity.setDate(cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)));        entity.setType(cursor.isNull(offset + 4) ? null : typeConverter.convertToEntityProperty(cursor.getString(offset + 4)));     }        @OverrIDe    protected final Long updateKeyAfterInsert(Note entity, long rowID) {        entity.setID(rowID);        return rowID;    }        @OverrIDe    public Long getKey(Note entity) {        if(entity != null) {            return entity.getID();        } else {            return null;        }    }    @OverrIDe    public boolean hasKey(Note entity) {        return entity.getID() != null;    }    @OverrIDe    protected final boolean isEntityUpdateable() {        return true;    }    }

这个类中第一行一个静态变量就定义了与我们数据实体对象对应的数据表的表名。

在NoteActivity中查询数据并显示:(请不要复制这个例子到项目中运行,因为这里还有一些类我没有贴出。)

/* * copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de) * * licensed under the Apache license, Version 2.0 (the "license"); * you may not use this file except in compliance with the license. * You may obtain a copy of the license at * *      http://www.apache.org/licenses/liCENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implIEd. * See the license for the specific language governing permissions and * limitations under the license. */package org.greenrobot.greendao.example;import androID.os.Bundle;import androID.text.Editable;import androID.text.TextWatcher;import androID.util.Log;import androID.vIEw.VIEw;import androID.vIEw.inputmethod.EditorInfo;import androID.Widget.EditText;import org.greenrobot.greendao.query.query;import java.text.DateFormat;import java.util.Date;import java.util.List;import androIDx.appcompat.app.AppCompatActivity;import androIDx.recyclervIEw.Widget.linearlayoutmanager;import androIDx.recyclervIEw.Widget.RecyclerVIEw;public class NoteActivity extends AppCompatActivity {    private EditText editText;    private VIEw addNotebutton;    private NoteDao noteDao;    private query<Note> notesquery;    private NotesAdapter notesAdapter;    @OverrIDe    public voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.main);        setUpVIEws();        // get the note DAO        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();        noteDao = daoSession.getNoteDao();        /**         * 查询数据库对应表中所有的笔记数据         * query all notes, sorted a-z by their text         */        notesquery = noteDao.queryBuilder().orderAsc(NoteDao.PropertIEs.Text).build();        updateNotes();    }    private voID updateNotes() {        List<Note> notes = notesquery.List();        notesAdapter.setNotes(notes);    }    protected voID setUpVIEws() {        RecyclerVIEw recyclerVIEw = findVIEwByID(R.ID.recyclerVIEwNotes);        recyclerVIEw.setHasFixedSize(true);        recyclerVIEw.setLayoutManager(new linearlayoutmanager(this));        notesAdapter = new NotesAdapter(noteClickListener);        recyclerVIEw.setAdapter(notesAdapter);        addNotebutton = findVIEwByID(R.ID.buttonAdd);        addNotebutton.setEnabled(false);        editText = findVIEwByID(R.ID.editTextNote);        editText.setonEditorActionListener((v, actionID, event) -> {            if (actionID == EditorInfo.IME_ACTION_DONE) {                addNote();                return true;            }            return false;        });        editText.addTextChangedListener(new TextWatcher() {            @OverrIDe            public voID onTextChanged(CharSequence s, int start, int before, int count) {                boolean enable = s.length() != 0;                addNotebutton.setEnabled(enable);            }            @OverrIDe            public voID beforeTextChanged(CharSequence s, int start, int count, int after) {            }            @OverrIDe            public voID afterTextChanged(Editable s) {            }        });    }    public voID onAddbuttonClick(VIEw vIEw) {        addNote();    }    private voID addNote() {        String noteText = editText.getText().toString();        editText.setText("");        final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);        String comment = "Added on " + df.format(new Date());        Note note = new Note();        note.setText(noteText);        note.setComment(comment);        note.setDate(new Date());        note.setType(NoteType.TEXT);        noteDao.insert(note);        Log.d("DaoExample", "Inserted new note, ID: " + note.getID());        updateNotes();    }    NotesAdapter.NoteClickListener noteClickListener = new NotesAdapter.NoteClickListener() {        @OverrIDe        public voID onNoteClick(int position) {            Note note = notesAdapter.getNote(position);            Long noteID = note.getID();            noteDao.deleteByKey(noteID);            Log.d("DaoExample", "Deleted note, ID: " + noteID);            updateNotes();        }    };}

NoteActivity的布局文件:

<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"                xmlns:tools="http://schemas.androID.com/tools"                androID:layout_wIDth="match_parent"                androID:layout_height="match_parent"                androID:paddingBottom="@dimen/activity_vertical_margin"                androID:paddingleft="@dimen/activity_horizontal_margin"                androID:paddingRight="@dimen/activity_horizontal_margin"                androID:paddingtop="@dimen/activity_vertical_margin"                tools:context="org.greenrobot.greendao.example.NoteActivity"                tools:ignore="RtlHardcoded">    <button        androID:ID="@+ID/buttonAdd"        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:layout_alignParentRight="true"        androID:onClick="onAddbuttonClick"        androID:text="@string/add"/>    <EditText        androID:ID="@+ID/editTextNote"        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:layout_toleftOf="@ID/buttonAdd"        androID:hint="@string/enter_new_note"        androID:imeOptions="actionDone"        androID:inputType="text"/>    <TextVIEw        androID:ID="@+ID/textVIEwNoteInstructions"        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:layout_below="@ID/editTextNote"        androID:gravity="center_horizontal"        androID:paddingBottom="8dp"        androID:paddingleft="8dp"        androID:paddingRight="8dp"        androID:text="@string/click_to_remove"        androID:textSize="12sp"/>    <androIDx.recyclervIEw.Widget.RecyclerVIEw        androID:ID="@+ID/recyclerVIEwNotes"        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"        androID:layout_below="@ID/textVIEwNoteInstructions"        androID:scrollbars="vertical"/></relativeLayout>

RecyclerVIEw适配器代码如下:

package org.greenrobot.greendao.example;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;import androID.Widget.TextVIEw;import java.util.ArrayList;import java.util.List;import androIDx.annotation.NonNull;import androIDx.recyclervIEw.Widget.RecyclerVIEw;public class NotesAdapter extends RecyclerVIEw.Adapter<NotesAdapter.NoteVIEwHolder> {    private NoteClickListener clickListener;    private List<Note> dataset;    public interface NoteClickListener {        voID onNoteClick(int position);    }    static class NoteVIEwHolder extends RecyclerVIEw.VIEwHolder {        public TextVIEw text;        public TextVIEw comment;        public NoteVIEwHolder(VIEw itemVIEw, final NoteClickListener clickListener) {            super(itemVIEw);            text = itemVIEw.findVIEwByID(R.ID.textVIEwNoteText);            comment = itemVIEw.findVIEwByID(R.ID.textVIEwNoteComment);            itemVIEw.setonClickListener(vIEw -> {                if (clickListener != null) {                    clickListener.onNoteClick(getAdapterposition());                }            });        }    }    public NotesAdapter(NoteClickListener clickListener) {        this.clickListener = clickListener;        this.dataset = new ArrayList<>();    }    public voID setNotes(@NonNull List<Note> notes) {        dataset = notes;        notifyDataSetChanged();    }    public Note getNote(int position) {        return dataset.get(position);    }    @NonNull    @OverrIDe    public NotesAdapter.NoteVIEwHolder onCreateVIEwHolder(VIEwGroup parent, int vIEwType) {        VIEw vIEw = LayoutInflater.from(parent.getContext())                .inflate(R.layout.item_note, parent, false);        return new NoteVIEwHolder(vIEw, clickListener);    }    @OverrIDe    public voID onBindVIEwHolder(NotesAdapter.NoteVIEwHolder holder, int position) {        Note note = dataset.get(position);        holder.text.setText(note.getText());        holder.comment.setText(note.getComment());    }    @OverrIDe    public int getItemCount() {        return dataset.size();    }}

上面只是梳理了GreenDao的使用流程,以及我们需要知道的知识点。当然这并不是所有的知识点,我们需要学习的还很多。这个例子请不要复制到项目中运行,因为这里还有一些类我没有贴出。如果想看完整的代码、并运行上面的实例,请至GreenDao的GitHub地址:https://github.com/greenrobot/greenDAO下载demo示例。上面的例子就是来自官网给的实例。

 

在说会上面的NoteActivity.class,一般对数据的增删改查,正式的项目开发中我们并不会直接在Activity中直接那么写。而是把它封装到一个诸如NoteDBManager.class的类中,这里贴出一个示例:

public class MessageManager {    private static MessageManager messageManager;    /**     * DaoSession     */    private DaoSession mDaoSession;    private MessageDao messageDao;    private MessageManager() {    }    @Deprecated    public static MessageManager getMMInstance(Context context) {        return getInstance();    }    public static MessageManager getInstance() {        if (null == messageManager) {            synchronized (MessageManager.class) {                if (messageManager == null) {                    messageManager = new MessageManager();                    messageManager.mDaoSession = MyApplication.getDaoSession();                    messageManager.messageDao = messageManager.mDaoSession.getMessageDao();                }            }        }        return messageManager;    }    /**     * 每天执行一次删除无效过期消息     */    public static voID oneDayDelinvalIDMsg() {        Context context = MyApplication.getInstance().getApplicationContext();        final SharedPreferences msgSp = context.getSharedPreferences(MsgCenteractivity.MSG_SP_name,                Context.MODE_PRIVATE);        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());        final String curDay = format.format(new Date());        String deleteDay = msgSp.getString("delete_day", "");        if (!curDay.equals(deleteDay)) {            MessageManager.getInstance().deleteInvalIDMessage();            SharedPreferences.Editor editor = msgSp.edit();            editor.putString("delete_day", curDay);            editor.commit();        }    }    /**     * 根据ID删除推送消息     *     * @param mID     */    public voID deleteMessageByMID(String mID) {        try {            queryBuilder<Message> qb = messageDao.queryBuilder();            Deletequery<Message> bd = qb.where(PropertIEs.MID.eq(mID)).buildDelete();            bd.executeDeleteWithoutDetachingEntitIEs();        } catch (Exception e) {            e.printstacktrace();        }    }    /**     * 根据ID删除推送消息(假删除)     *     * @param mID     */    public voID deleteMessageNewByMID(String mID) {        try {            queryBuilder<Message> qb = messageDao.queryBuilder();            List<Message> msgList ;            msgList = qb.where(PropertIEs.MID.eq(mID)).List();            if (null != msgList && !msgList.isEmpty()) {                Message msg = msgList.get(0);                if (null != msg) {                    msg.setIsdelete(1);                    messageDao.insertOrReplace(msg);                }            }        } catch (Exception e) {            e.printstacktrace();        }    }    public voID deleteMessageByMID(String mID, String mobile) {        try {            queryBuilder<Message> qb = messageDao.queryBuilder();            Deletequery<Message> bd = qb.where(qb.and(PropertIEs.MID.eq(mID), PropertIEs.Mobile.eq(mobile)))                    .buildDelete();            bd.executeDeleteWithoutDetachingEntitIEs();        } catch (Exception e) {            e.printstacktrace();        }    }    /**     * 根据类型ID删除所有消息     *     * @param typeID     */    public voID deleteMessageByType(String typeID) {        try {            queryBuilder<Message> qb = messageDao.queryBuilder();            Deletequery<Message> bd = qb.where(PropertIEs.MsgType.eq(typeID)).buildDelete();            bd.executeDeleteWithoutDetachingEntitIEs();        } catch (Exception e) {            e.printstacktrace();        }    }    /**     * 根据类型ID删除该用户手机号     *     * @param typeID     * @param mobile     */    public voID deleteTypeMessageByTypeMob(String typeID, String mobile) {        try {            queryBuilder<Message> qb = messageDao.queryBuilder();            Deletequery<Message> bd = qb.where(qb.and(PropertIEs.MsgType.eq(typeID), PropertIEs.Mobile.eq(mobile)))                    .buildDelete();            bd.executeDeleteWithoutDetachingEntitIEs();        } catch (Exception e) {            e.printstacktrace();        }    }    public voID deleteInvalIDMessage() {        try {            queryBuilder<Message> qb = messageDao.queryBuilder();            Deletequery<Message> bd = qb.where(qb.and(PropertIEs.EffectiveTime.lt(System.currentTimeMillis()),                    PropertIEs.EffectiveTime.isNotNull())).buildDelete();            bd.executeDeleteWithoutDetachingEntitIEs();        } catch (Exception e) {            e.printstacktrace();        }    }    public voID updateMessageStatus(String mobile) {        try {            String curTime = getCurTime();            queryBuilder<Message> qb = messageDao.queryBuilder();            List<Message> msgList ;            msgList = qb.where(qb.and(PropertIEs.Status.eq(0),                    PropertIEs.Mobile.eq(mobile), PropertIEs.Isdelete.notEq(1))).List();            if (null != msgList && !msgList.isEmpty()) {                int size = msgList.size();                for (int i = 0; i < size; i++) {                    Message msg = msgList.get(i);                    if (null != msg) {                        msg.setStatus(1);                        msg.setReadTime(curTime);                        messageDao.update(msg);                    }                }            }        } catch (Exception e) {            e.printstacktrace();        }    }}

然后通过管理类的单例在Activity中调用封装后的增删改查方法!。

忠言逆耳:对于初学者请一定先运行GitHub官网给的dome示例。而不是盲目的找示例demo,那样只会放慢你学习的脚步。

岁月鎏金,用知识铭刻生命的每分每秒!

总结

以上是内存溢出为你收集整理的Android greenDAO数据库开发梳理 : Android ORM for your SQLite database全部内容,希望文章能够帮你解决Android greenDAO数据库开发梳理 : Android ORM for your SQLite database所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1018542.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存