GreenDao與ReactiveX的完美搭配,greendaoreactivex

來源:互聯網
上載者:User

GreenDao與ReactiveX的完美搭配,greendaoreactivex

轉載請註明出處:http://www.cnblogs.com/cnwutianhao/p/6719380.html 

 

作為Android開發人員,一定不會對 GreenDao 和 ReactiveX 陌生。

GreenDao   號稱Android最快的關係型資料庫

ReactiveX    Rx是一個編程模型,目標是提供一致的編程介面,協助開發人員更方便的處理非同步資料流。

下面我們就通過一個執行個體,來講解有無Rx支援的時候GreenDao應該怎麼用,實現增刪操作。

首先匯入需要的庫(本文針對的 GreenDao 是 3.x 版本, Rx 是 1.x 版本)

GreenDao匯入需求庫的說明: https://github.com/greenrobot/greenDAO/

在 build.gradle(Project:Xxx) 下,添加:

buildscript {    repositories {        ...        mavenCentral()        ...    }    dependencies {        ...        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'        ...    }}

在 build.gradle(Module:Xxx) 下,添加:

...apply plugin: 'org.greenrobot.greendao'...dependencies {    ...    compile 'org.greenrobot:greendao:3.2.2'    ...}

 

Rx匯入需求庫的說明: https://github.com/ReactiveX/RxJava/tree/1.x

在 build.gradle(Module:Xxx) 下,添加:

dependencies {    ...    compile 'io.reactivex:rxjava:1.2.9'    compile 'io.reactivex:rxandroid:1.2.1'    ...}

 

需求庫添加完之後就可以進入正題了

1.參考GreenDao官方文檔,添加必要的類 Note 、 NotesAdapter 、 NoteType 、 NoteTypeConverter

Note :

/** * 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;    }}

NotesAdapter :

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 = (TextView) itemView.findViewById(R.id.textViewNoteText);            comment = (TextView) itemView.findViewById(R.id.textViewNoteComment);            itemView.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View view) {                    if (clickListener != null) {                        clickListener.onNoteClick(getAdapterPosition());                    }                }            });        }    }    public NotesAdapter(NoteClickListener clickListener) {        this.clickListener = clickListener;        this.dataset = new ArrayList<Note>();    }    public void setNotes(@NonNull List<Note> notes) {        dataset = notes;        notifyDataSetChanged();    }    public Note getNote(int position) {        return dataset.get(position);    }    @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();    }}

NoteType :

public enum NoteType {    TEXT, LIST, PICTURE}

NoteTypeConverter :

public class NoteTypeConverter implements PropertyConverter<NoteType, String> {    @Override    public NoteType convertToEntityProperty(String databaseValue) {        return NoteType.valueOf(databaseValue);    }    @Override    public String convertToDatabaseValue(NoteType entityProperty) {        return entityProperty.name();    }}

 

必要的類添加之後,接下來就是重頭戲:

用代碼說話,橫向比較 GreenDao 在有無 Rx 的支援下應該如何書寫

1.初始化類

無 Rx 寫法                                                

private NoteDao noteDao;private Query<Note> notesQuery;

 有 Rx 寫法

private RxDao<Note, Long> noteDao;private RxQuery<Note> notesQuery;

 

2.將記錄儲存到DAO裡

無 Rx 寫法 

DaoSession daoSession = ((BaseApplication) getApplication()).getDaoSession();noteDao = daoSession.getNoteDao();

有 Rx 寫法

DaoSession daoSession = ((BaseApplication) getApplication()).getDaoSession();noteDao = daoSession.getNoteDao().rx();

 

3.查詢所有記錄,按A-Z分類

無 Rx 寫法

notesQuery = noteDao.queryBuilder().orderAsc(NoteDao.Properties.Text).build();

有 Rx 寫法

notesQuery = daoSession.getNoteDao().queryBuilder().orderAsc(NoteDao.Properties.Text).rx();

 

4.初始化View

無 Rx 寫法

protected void setUpViews() {        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerViewNotes);        //noinspection ConstantConditions        recyclerView.setHasFixedSize(true);        recyclerView.setLayoutManager(new LinearLayoutManager(this));        notesAdapter = new NotesAdapter(noteClickListener);        recyclerView.setAdapter(notesAdapter);        addNoteButton = findViewById(R.id.buttonAdd);        //noinspection ConstantConditions        addNoteButton.setEnabled(false);        editText = (EditText) findViewById(R.id.editTextNote);        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {            @Override            public boolean onEditorAction(TextView v, int actionId, KeyEvent 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) {            }        });    }

有 Rx 寫法

protected void setUpViews() {        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerViewNotes);        //noinspection ConstantConditions        recyclerView.setHasFixedSize(true);        recyclerView.setLayoutManager(new LinearLayoutManager(this));        notesAdapter = new NotesAdapter(noteClickListener);        recyclerView.setAdapter(notesAdapter);        addNoteButton = findViewById(R.id.buttonAdd);        editText = (EditText) findViewById(R.id.editTextNote);        //noinspection ConstantConditions        RxTextView.editorActions(editText).observeOn(AndroidSchedulers.mainThread())                .subscribe(new Action1<Integer>() {                    @Override                    public void call(Integer actionId) {                        if (actionId == EditorInfo.IME_ACTION_DONE) {                            addNote();                        }                    }                });        RxTextView.afterTextChangeEvents(editText).observeOn(AndroidSchedulers.mainThread())                .subscribe(new Action1<TextViewAfterTextChangeEvent>() {                    @Override                    public void call(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) {                        boolean enable = textViewAfterTextChangeEvent.editable().length() > 0;                        addNoteButton.setEnabled(enable);                    }                });    }

 

5.更新記錄

無 Rx 寫法

private void updateNotes() {    List<Note> notes = notesQuery.list();    notesAdapter.setNotes(notes);}

有 Rx 寫法

private void updateNotes() {    notesQuery.list()            .observeOn(AndroidSchedulers.mainThread())            .subscribe(new Action1<List<Note>>() {                @Override                public void call(List<Note> notes) {                    notesAdapter.setNotes(notes);                }            });}

 

6.添加記錄

無 Rx 寫法

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();    }

有 Rx 寫法

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(null, noteText, comment, new Date(), NoteType.TEXT);        noteDao.insert(note)                .observeOn(AndroidSchedulers.mainThread())                .subscribe(new Action1<Note>() {                    @Override                    public void call(Note note) {                        Log.d("DaoExample", "Inserted new note, ID: " + note.getId());                        updateNotes();                    }                });    }

 

7.刪除記錄

無 Rx 寫法

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();        }    };

有 Rx 寫法

NotesAdapter.NoteClickListener noteClickListener = new NotesAdapter.NoteClickListener() {        @Override        public void onNoteClick(int position) {            Note note = notesAdapter.getNote(position);            final Long noteId = note.getId();            noteDao.deleteByKey(noteId)                    .observeOn(AndroidSchedulers.mainThread())                    .subscribe(new Action1<Void>() {                        @Override                        public void call(Void aVoid) {                            Log.d("DaoExample", "Deleted note, ID: " + noteId);                            updateNotes();                        }                    });        }    };

 

最後別忘了建立一個Application類,並添加到Manifest中

public class BaseApplication extends Application {    /**     * A flag to show how easily you can switch from standard SQLite to the encrypted SQLCipher.     */    public static final boolean ENCRYPTED = true;    private DaoSession daoSession;    @Override    public void onCreate() {        super.onCreate();        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(
this, ENCRYPTED ? "notes-db-encrypted" : "notes-db"); Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb(); daoSession = new DaoMaster(db).newSession(); } public DaoSession getDaoSession() { return daoSession; }}

 

文中額外可能會用到的庫

compile 'com.jakewharton.rxbinding:rxbinding:1.0.1'compile 'net.zetetic:android-database-sqlcipher:3.5.6'

 

關注我的新浪微博,擷取更多Android開發資訊!
關注科技評論家,領略科技、創新、教育以及最大化人類智慧與想象力!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.