build.gradle配置
//room
implementation 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
创建数据库类
@Database(entities = {Note.class},version = 1,exportSchema = false)
public abstract class NoteDatabase extends RoomDatabase {
public static final String DB_NAME="note.db";
private static volatile NoteDatabase instance;
public static synchronized NoteDatabase getInstance(Context context){
if (instance==null){
instance = create(context);
}
return instance;
}
public static NoteDatabase create(final Context context){
return Room.databaseBuilder(
context,
NoteDatabase.class,
DB_NAME
).build();
}
public abstract NoteDao getNoteDao();
创建数据库实体类
@Entity
public class Note {
@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String content;
private Long day_time;
private int state;
private String msg;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Long getDay_time() {
return day_time;
}
public void setDay_time(Long day_time) {
this.day_time = day_time;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
创建操作数据库实体类接口
@Dao
public interface NoteDao {
@Insert
void insert(Note...notes);
@Update
void update(Note...notes);
@Delete
void delete(Note...notes);
@Query("select * from note")
List<Note> getAllNote();
@Query("select * from note where id=:id")
Note getNote(int id);
}
在Activity 中子线程使用
public class NoteActivity extends AppCompatActivity {
EditText et_title,et_content;
Button save_btn;
NoteDao noteDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
noteDao= NoteDatabase.create(this).getNoteDao();
initView();
}
private void initView() {
et_title=findViewById(R.id.et_title);
et_content=findViewById(R.id.et_content);
save_btn=findViewById(R.id.save_btn);
save_btn.setOnClickListener(v -> new Thread(saveData).start());
}
public Runnable saveData=new Runnable() {
@Override
public void run() {
String title=et_title.getText().toString();
String content=et_content.getText().toString();
Long date_time=System.currentTimeMillis();
Note note=new Note();
note.setTitle(title);
note.setContent(content);
note.setDay_time(date_time);
noteDao.insert(note);
}
};
}
|