Dig*_*jay 6 android retrofit2 rx-java2 android-room
我在我的 android 应用程序中使用 Retrofit2 和 Rxjava2 作为网络库,使用 NodeJS 和 MongoDB 作为后端服务。我想从服务器获取数据并将数据存储在房间数据库中,以便如果用户再次打开应用程序,它会从房间和在服务器上添加一些新数据之前,不会来自服务器。
到目前为止,我已成功从服务器获取数据并将其显示在回收站视图中。
我想要达到的目标:
1) 从服务器获取数据后,将数据存储在房间数据库中。
2) 显示房间数据库中的数据,直到服务器上更新了一些新数据。
这是我的代码如下:
接口服务.java
public interface ApiService {
@POST("retrofitUsers")
@FormUrlEncoded
Observable<String> saveData(@Field("name") String name,
@Field("age") String age);
@GET("getUsers")
Observable<List<BioData>> getData();
}
Run Code Online (Sandbox Code Playgroud)
改造客户端.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getInstance(){
if(retrofit == null)
retrofit = new Retrofit.Builder()
.baseUrl("https://bookbudiapp.herokuapp.com/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit;
}
private RetrofitClient(){
}
}
Run Code Online (Sandbox Code Playgroud)
生物数据.java
public class BioData {
@SerializedName("name")
@Expose
private String name;
@SerializedName("age")
@Expose
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Run Code Online (Sandbox Code Playgroud)
主活动.java
public class Users extends AppCompatActivity {
RecyclerView recycle;
UserAdapter adapter;
List<BioData> list;
CompositeDisposable compositeDisposable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycle = findViewById(R.id.recycle);
recycle.setHasFixedSize(true);
recycle.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
compositeDisposable = new CompositeDisposable();
fetchData();
}
private void fetchData(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService myApi = retrofit.create(ApiService.class);
Disposable disposable = myApi.getData().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<BioData>>() {
@Override
public void accept(List<BioData> bioData) throws Exception {
adapter = new UserAdapter(bioData,getApplicationContext());
recycle.setAdapter(adapter);
}
});
compositeDisposable.add(disposable);
}
@Override
protected void onStop() {
super.onStop();
compositeDisposable.clear();
}
}
Run Code Online (Sandbox Code Playgroud)
如何在我的应用程序中添加 Room 数据库让我知道我不知道任何帮助将不胜感激。
谢谢
房间基础
Room 库充当底层 SQLite 数据库的抽象层。因此,使用 Room 注释:
Room 有 3 个主要组件
实体:用@Entity 注释的类映射到数据库中的表。每个实体都保存在自己的表中,类中的每个字段都代表列名。
tableName 属性用于定义表的名称每个实体类必须至少有一个主键字段,用@PrimaryKey 注释实体类中的字段可以用@ColumnInfo(name = “name_of_column”) 注释给出特定列名字
DAO:数据访问对象要么是一个接口,要么是一个用@Doa 注释的抽象类,包含定义要对数据执行的操作的所有方法。方法可以用注释
@Query 从数据库中检索数据
@Insert 将数据插入数据库
@Delete 从数据库中删除数据
@Update 更新数据库中的数据
添加这些依赖项:
dependencies {
// Room dependencies
compile 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
}
Run Code Online (Sandbox Code Playgroud)
创建实体
在创建数据库之前,让我们创建一个实体,命名为 Note,稍后,该类的对象将被添加到数据库中。
@Entity
public class Note {
@PrimaryKey(autoGenerate = true)
private int note_id;
@ColumnInfo(name = "note_content") // column name will be "note_content" instead of "content" in table
private String content;
private String title;
private
public Note(int note_id, String content, String title) {
this.note_id = note_id;
this.content = content;
this.title = title;
}
public int getNote_id() {
return note_id;
}
public void setNote_id(int note_id) {
this.note_id = note_id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Note)) return false;
Note note = (Note) o;
if (note_id != note.note_id) return false;
return title != null ? title.equals(note.title) : note.title == null;
}
@Override
public int hashCode() {
int result = note_id;
result = 31 * result + (title != null ? title.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Note{" +
"note_id=" + note_id +
", content='" + content + '\'' +
", title='" + title + '\'' +
'}';
}}
Run Code Online (Sandbox Code Playgroud)
创建 DAO
DAO 定义了访问数据库的所有方法,并使用 @Dao 注释进行了注释。DAO 充当对数据库中的数据执行 CRUD 操作的合约。
@Dao
public interface NoteDao {
@Query("SELECT * FROM user "+ Constants.TABLE_NAME_NOTE)
List<Note> getAll();
/*
* Insert the object in database
* @param note, object to be inserted
*/
@Insert
void insert(Note note);
/*
* update the object in database
* @param note, object to be updated
*/
@Update
void update(Note repos);
/*
* delete the object from database
* @param note, object to be deleted
*/
@Delete
void delete(Note note);
/*
* delete list of objects from database
* @param note, array of objects to be deleted
*/
@Delete
void delete(Note... note); // Note... is varargs, here note is an array
}
Run Code Online (Sandbox Code Playgroud)
创建数据库
现在,我们将表定义为实体,并通过 NoteDao 定义了 CRUD 方法。数据库难题的最后一部分是数据库本身。
@Database(entities = { Note.class }, version = 1)
public abstract class NoteDatabase extends RoomDatabase {
public abstract NoteDao getNoteDao();
private static NoteDatabase noteDB;
public static NoteDatabase getInstance(Context context) {
if (null == noteDB) {
noteDB = buildDatabaseInstance(context);
}
return noteDB;
}
private static NoteDatabase buildDatabaseInstance(Context context) {
return Room.databaseBuilder(context,
NoteDatabase.class,
Constants.DB_NAME)
.allowMainThreadQueries().build();
}
public void cleanUp(){
noteDB = null;
}
}
Run Code Online (Sandbox Code Playgroud)
实现数据库交互
下面的代码片段将演示使用 Room 数据库的插入、更新和删除功能的工作。
public class AddNoteActivity extends AppCompatActivity {
private TextInputEditText et_title,et_content;
private NoteDatabase noteDatabase;
private Note note;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
et_title = findViewById(R.id.et_title);
et_content = findViewById(R.id.et_content);
noteDatabase = NoteDatabase.getInstance(AddNoteActivity.this);
Button button = findViewById(R.id.but_save);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// fetch data and create note object
note = new Note(et_content.getText().toString(),
et_title.getText().toString());
// create worker thread to insert data into database
new InsertTask(AddNoteActivity.this,note).execute();
}
});
}
private void setResult(Note note, int flag){
setResult(flag,new Intent().putExtra("note",note));
finish();
}
private static class InsertTask extends AsyncTask<Void,Void,Boolean> {
private WeakReference<AddNoteActivity> activityReference;
private Note note;
// only retain a weak reference to the activity
InsertTask(AddNoteActivity context, Note note) {
activityReference = new WeakReference<>(context);
this.note = note;
}
// doInBackground methods runs on a worker thread
@Override
protected Boolean doInBackground(Void... objs) {
activityReference.get().noteDatabase.getNoteDao().insertNote(note);
return true;
}
// onPostExecute runs on main thread
@Override
protected void onPostExecute(Boolean bool) {
if (bool){
activityReference.get().setResult(note,1);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
检索和显示 NoteList
public class NoteListActivity extends AppCompatActivity implements NotesAdapter.OnNoteItemClick{
private TextView textViewMsg;
private RecyclerView recyclerView;
private NoteDatabase noteDatabase;
private List<Note> notes;
private NotesAdapter notesAdapter;
private int pos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeVies();
displayList();
}
private void displayList(){
// initialize database instance
noteDatabase = NoteDatabase.getInstance(NoteListActivity.this);
// fetch list of notes in background thread
new RetrieveTask(this).execute();
}
private static class RetrieveTask extends AsyncTask<Void,Void,List<Note>>{
private WeakReference<NoteListActivity> activityReference;
// only retain a weak reference to the activity
RetrieveTask(NoteListActivity context) {
activityReference = new WeakReference<>(context);
}
@Override
protected List<Note> doInBackground(Void... voids) {
if (activityReference.get()!=null)
return activityReference.get().noteDatabase.getNoteDao().getNotes();
else
return null;
}
@Override
protected void onPostExecute(List<Note> notes) {
if (notes!=null && notes.size()>0 ){
activityReference.get().notes = notes;
// hides empty text view
activityReference.get().textViewMsg.setVisibility(View.GONE);
// create and set the adapter on RecyclerView instance to display list
activityReference.get().notesAdapter = new NotesAdapter(notes,activityReference.get());
activityReference.get().recyclerView.setAdapter(activityReference.get().notesAdapter);
}
}
}
private void initializeVies(){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textViewMsg = (TextView) findViewById(R.id.tv\_\_empty);
// Action button to add note
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(listener);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(NoteListActivity.this));
}
}
Run Code Online (Sandbox Code Playgroud)
更新说明
public class AddNoteActivity extends AppCompatActivity {
private TextInputEditText et_title,et_content;
private NoteDatabase noteDatabase;
private Note note;
private boolean update;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
et_title = findViewById(R.id.et_title);
et_content = findViewById(R.id.et_content);
noteDatabase = NoteDatabase.getInstance(AddNoteActivity.this);
Button button = findViewById(R.id.but_save);
if ( (note = (Note) getIntent().getSerializableExtra("note"))!=null ){
getSupportActionBar().setTitle("Update Note");
update = true;
button.setText("Update");
et_title.setText(note.getTitle());
et_content.setText(note.getContent());
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
note.setContent(et_content.getText().toString());
note.setTitle(et_title.getText().toString());
noteDatabase.getNoteDao().updateNote(note);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
删除笔记
noteDatabase.getNoteDao().deleteNote(notes.get(pos));
adapterObj.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)
Android 开发者有一个很好的 Room 入门教程:https ://developer.android.com/training/data-storage/room/index.html
对于您想要添加的功能,使用存储库模式是有好处的。为了简单起见,存储库模式就像应用程序和服务器之间的一个类,您在其中询问一些数据(例如用户名),而应用程序不知道该数据来自何处(数据库或服务器)。存储库将执行以下操作:
class UserRepository {
public User getUser() {
User user = db.userDao().getUser() //Room sintax
if(user==null){
//access to server and get user object
db.userDao().insert(user)
}
return db.userDao().getUser()
}
}
Run Code Online (Sandbox Code Playgroud)
这允许应用程序解耦,例如,如果您将来想要更改服务器,则只需更改存储库类,应用程序的其余部分将是相同的。我建议你调查一下。您还应该使用存储库应该实现的接口,这可以进一步解耦
| 归档时间: |
|
| 查看次数: |
10277 次 |
| 最近记录: |