For reprinting, please indicate the source: http://www.cnblogs.com/cnwutianhao/p/6719380.html
As an Android developer, you must not be unfamiliar with Green Dao and ReactiveX.
GreenDao Android's fastest relational database
ReactiveX Rx is a programming model that aims to provide a consistent programming interface to help developers handle asynchronous data streams more easily.
Next, we will use an example to illustrate how GreenDao should be used to add and delete when Rx support is available or not.
First import the required libraries (for GreenDao in this article, version 3.x and version 1.x)
GreenDao's instructions for importing requirements libraries: https://github.com/greenrobot/greenDAO/
Under build.gradle(Project:Xxx), add:
buildscript {
repositories {
...
mavenCentral()
...
}
dependencies {
...
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
...
}
}
Under build.gradle(Module:Xxx), add:
...
apply plugin: 'org.greenrobot.greendao'
...
dependencies {
...
compile 'org.greenrobot:greendao:3.2.2'
...
}
Rx Import Requirement Library Description: https://github.com/ReactiveX/RxJava/tree/1.x
Under build.gradle(Module:Xxx), add:
dependencies {
...
compile 'io.reactivex:rxjava:1.2.9'
compile 'io.reactivex:rxandroid:1.2.1'
...
}
Once the requirement library is added, you can get to the point.
1. Reference Green Dao Official Documents Add the necessary classes 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(); } }
After the necessary classes have been added, the next thing is to focus on:
Speaking in code, horizontal comparison of how GreenDao should write with or without Rx support
1. Initialization class
No Rx Writing * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
private NoteDao noteDao; private Query<Note> notesQuery;
Rx
private RxDao<Note, Long> noteDao; private RxQuery<Note> notesQuery;
2. Keep records in DAO
Rx-free writing
DaoSession daoSession = ((BaseApplication) getApplication()).getDaoSession();
noteDao = daoSession.getNoteDao();
Rx
DaoSession daoSession = ((BaseApplication) getApplication()).getDaoSession();
noteDao = daoSession.getNoteDao().rx();
3. Query all records and classify them by A-Z
Rx-free writing
notesQuery = noteDao.queryBuilder().orderAsc(NoteDao.Properties.Text).build();
Rx
notesQuery = daoSession.getNoteDao().queryBuilder().orderAsc(NoteDao.Properties.Text).rx();
4. Initialize View
Rx-free writing
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. Updating Records
Rx-free writing
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. Add Records
Rx-free writing
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. Delete records
Rx-free writing
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(); } }); } };
Finally, don't forget to create a new Application class and add it to 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; } }
Extra libraries that may be used in this article
compile 'com.jakewharton.rxbinding:rxbinding:1.0.1'
compile 'net.zetetic:android-database-sqlcipher:3.5.6'
follow My Sina Weibo Get more information about Android development!
follow Science and Technology Critics Understand technology, innovation, education and maximize human wisdom and imagination!