实现一个简单的安卓小程序-记事本(备忘录)涉及到几个关键的组件和服务:Activity、Fragment、ViewModel、Room数据库等。以下是实现记事本功能的核心代码示例:
- 创建一个实体类
Note
,用于表示备忘录上的每条记录:
@Entity
public class Note {
@PrimaryKey
private int id;
private String title;
private String content;
// 省略getter和setter方法
}
- 创建一个Dao接口
NoteDao
,用于数据库操作:
@Dao
public interface NoteDao {
@Query("SELECT * FROM Note")
List<Note> getAllNotes();
@Query("SELECT * FROM Note WHERE id IN (:ids)")
List<Note> loadAllByIds(int[] ids);
@Query("SELECT * FROM Note WHERE id = :id")
Note getNoteById(int id);
@Insert
void insertNote(Note... notes);
@Delete
void deleteNote(Note... notes);
@Update
void updateNote(Note... notes);
}
- 创建Room数据库
NoteDatabase
:
@Database(entities = {Note.class}, version = 1)
public abstract class NoteDatabase extends RoomDatabase {
public abstract NoteDao noteDao();
}
- 创建
NoteViewModel
来处理记事本的业务逻辑:
public class NoteViewModel extends AndroidViewModel {
private NoteDao noteDao;
public NoteViewModel(@NonNull Application application) {
super(application);
noteDao = NoteDatabase.getInstance(application).noteDao();
}
public LiveData<List<Note>> getAllNotes() {
return new LiveData<List<Note>>() {
@Override
protected void onActive() {
super.onActive();
Log.d("NoteViewModel", "onActive");
}
};
}
public void insert(Note note) {
new InsertNoteAsyncTask(noteDao).execute(note);
}
public void delete(Note note) {
new DeleteNoteAsyncTask(noteDao).execute(note);
}
public void update(Note note) {
new UpdateNoteAsyncTask(noteDao).execute(note);
}
private static class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> {
private NoteDao noteDao;
private InsertNoteAsyncTask(NoteDao noteDao) {
this.noteDao = noteDao;
}
@Override
protected Void doInBackground(Note... notes) {
noteDao.insertNote(notes[0]);
return null;
}
}
// Delete和Update的AsyncTask类似
}
- 创建
NoteListFragment
来展示和管理记事本的UI界面: