Room
是個Google官方提供的套件
on base在androidx
之上(感覺androidx就是很潮就對了)
用來存取SQLite
達到本地資料庫的CRUD(我把它定位成跟CoreDate一樣的東西☘️☘️☘️)
dependencies {
def room_version = "2.2.0-rc01"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
第二行也要加不然會閃退:"_Impl does not exist"
1. Entity
@Entity(tableName = "note_t")
public class Note
{
@PrimaryKey(autoGenerate = true)
public int uid;
//欄位不同用@ColumnInfo(name = “column_name”)
public String user;
public String time;
public String todo;
public Note(String user, String time, String todo)
{
this.user = user;
this.time = time;
this.todo = todo;
}
}
2. DAO
@Dao
public interface NoteDAO
{
@Insert
public void insert(Note note);
@Query("SELECT * FROM note_t WHERE user = :user")
List<Note> getAllNotesBy(String user);
}
3. Database
@Database(entities = {Note.class}, version = 1)//版本是要幹嘛的?
public abstract class IDLADB extends RoomDatabase
{
public abstract NoteDAO noteDAO();
//Singleton
private static IDLADB INSTANCE;
public static IDLADB getDatabase(Context context)
{
if (INSTANCE == null)
{
INSTANCE = Room.databaseBuilder(context,IDLADB.class,"idlaDB")
.allowMainThreadQueries()//其實這種耗時的動作應該丟到背景去執行,特殊原因要強制就家這句
.build();
}
return INSTANCE;
}
}
simpleAdapter = new SimpleAdapter(this,
maps,
android.R.layout.simple_list_item_2,
new String[] {"time", "todo"},
new int[] {android.R.id.text1,android.R.id.text2});
for(Note note: notes)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put( "time", note.time);
map.put( "todo", note.todo);
maps.add(map);
}
listView.setAdapter(simpleAdapter);
可以去 https://github.com/mark33699/IDLA 看一下順便給顆⭐️
如果你喜歡我的影片別忘了按讚分享加訂閱,開啟紅色的小鈴鐺,我們明天見~