ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 数据库GreenDao框架 1.新创建Java实体类 ~~~ @Entity(indexes = { @Index(value = "text, date DESC", unique = true) }) public class Note { @Id private Long id; @NotNull private String text; private Date date; } ~~~ 2.Make Project 能生成三个文件,DaoMaster、DaoSession|、BeanDao 必须文件自己初始化那就是DaoSession, 3.自定义Application,获取DaoSession的实例化对象 注意true false的设置,设置为true,会报错,所以改为false ~~~ public class App extends Application { /** A flag to show how easily you can switch from standard SQLite to the encrypted SQLCipher. */ public static final boolean ENCRYPTED = false; private DaoSession daoSession; @Override public void onCreate() { super.onCreate(); DevOpenHelper helper = new 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; } } ~~~ 普通操作:插入、删除、更新、查找 4.完成插入Bean操作需要两步 第一步获取DaoSession对象 ~~~ // get the note DAO DaoSession daoSession = ((App) getApplication()).getDaoSession(); noteDao = daoSession.getNoteDao(); ~~~ 第二步,执行插入操作 ~~~ 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()); ~~~ 5.完成删除Bean操作需要两步 第一步同上 第二步,执行删除操作: `noteDao.deleteByKey(id);` 7.更新Bean操作 第二步,执行更新曹组 ~~~ note.setText("This note has changed."); noteDao.update(note); ~~~ 查找 ~~~ noteDao.queryBuilder().orderAsc(NoteDao.Properties.Text).build(); private void queryEq() { Son mingEq = sonDao.queryBuilder().where(SonDao.Properties.Name.eq("小明")).unique(); Log.d("mingEq", "queryEq() called" + mingEq); } ~~~ 8.设置数据库 ~~~ DevOpenHelper helper = new DevOpenHelper(this, "notes-db"); Database db = helper.getWritableDb(); daoSession = new DaoMaster(db).newSession(); ~~~ 9.更新数据库 什么情况下更新? 新建数据表 数据表字段更新 如何更新? 方法1 创建新的数据库 方法2 待定 # Green文档,Sample 6个类 1.APP类 ~~~ public class App 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(); DevOpenHelper helper = new 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; } } ~~~ 2.标注的实体类 ~~~ 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; } } ~~~ # 实体类的枚举属性 ~~~ public enum NoteType { TEXT, LIST, PICTURE } ~~~ # 转换器 import org.greenrobot.greendao.converter.PropertyConverter; 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(); } } # 数据库层主要用例Demo: ~~~ import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import org.greenrobot.greendao.query.Query; import java.text.DateFormat; import java.util.Date; import java.util.List; 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 = ((App) 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 = (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 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) { } }); } 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(); } }; } ~~~ # Item适配器 ~~~ import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; 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(); } } ~~~