天天看點

開源 android room,android----Room資料庫的簡單操作(1)

packagecom.example.roomtest;importandroidx.appcompat.app.AppCompatActivity;importandroidx.room.Room;importandroidx.room.RoomDatabase;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.TextView;importorg.w3c.dom.Text;importjava.util.List;public class MainActivity extendsAppCompatActivity {

WordDatabase wordDatabase;

WordDao wordDao;

TextView textView;

Button buttonInsert,buttonDelete,buttonUpdata,buttonwClear;

@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

wordDatabase= Room.databaseBuilder(this, WordDatabase.class,"word_database")

.allowMainThreadQueries().build();//強制讓它在主線程運作

wordDao =wordDatabase.getWordDao();

textView=findViewById(R.id.textView);

buttonInsert=findViewById(R.id.button_insert);

buttonDelete=findViewById(R.id.button_delete);

buttonUpdata=findViewById(R.id.button_updata);

buttonwClear=findViewById(R.id.button_clear);//插入

buttonInsert.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

Word word1= new Word("Hello", "你好");

Word word2= new Word("World", "世界");

wordDao.insertWords(word1,word2);

updataView();

}

});//清空

buttonwClear.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

wordDao.deleteAllWords();

updataView();

}

});//修改

buttonUpdata.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

Word word= new Word("Thanks","謝謝");

word.setId(29);

wordDao.updataWords(word);

updataView();

}

});//删除

buttonDelete.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View v) {

Word word= new Word("aa", "bb");

word.setId(30);

wordDao.deleteWords(word);

updataView();

}

});

}//更新界面

voidupdataView(){

List list =wordDao.getAllWords();

StringBuilder text= newStringBuilder();for(int i = 0;i

Word word=list.get(i);

text.append(word.getId()).append("、").append(word.getEnglish_word()).append(":").append(word.getChinese_meaning()).append('\n');

}

textView.setText(text);

}

}