我正在使用MVVM设计模式制作应用程序。最初,我尝试在离线数据库中添加数据。现在,我想将数据保存到在线服务器中。
以下是我用于离线数据存储的代码:
NoteDao.java
@Dao
public interface NoteDao {
@Insert
void insert(Note note);
@Query("SELECT * FROM My_notes ORDER BY id DESC")
LiveData<List<Note>> getAllNotes();
}
NotesviewModel.java
public class NotesviewModel extends AndroidViewModel {
private NoteRepository noteRepository;
private LiveData<List<Note>> allNotes;
public NotesviewModel(@NonNull Application application) {
super(application);
noteRepository = new NoteRepository(application);
allNotes = noteRepository.getAllNotes();
}
public void insert(Note note){
noteRepository.insert(note);
}
public LiveData<List<Note>> getAllNotes(){
return allNotes;
}
}
NoteRepository.java
public class NoteRepository {
private NoteDao noteDao;
private LiveData<List<Note>> allNotes;
public NoteRepository(Application application){
DatabaseSingleton db = DatabaseSingleton.getInstance(application);
noteDao = db.noteDao();
allNotes = noteDao.getAllNotes();
}
public void insert(Note note){
new InsertNoteAsyncTask(noteDao).execute(note);
}
public LiveData<List<Note>> getAllNotes(){
return allNotes;
}
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.insert(notes[0]);
return null;
}
}
}
AddNotes.java
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveNote();
}
});
private void saveNote(){
String str1 = title.getText().toString();
String str2 = description.getText().toString();
if(str1.equals("") || str2.equals("")){
Toast.makeText(getApplicationContext(),"Field cannot be empty",Toast.LENGTH_SHORT).show();
}else{
Intent i = new Intent(AddNotes.this,MainActivity.class);
i.putExtra("title",str1);
i.putExtra("desc",str2);
setResult(RESULT_OK,i);
finish();
}
}
MainActivity.java
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ADD_NOTE && resultCode == RESULT_OK){
if(data != null){
String title = data.getStringExtra("title");
String desc = data.getStringExtra("desc");
Note mynote = new Note(title,desc);
noteViewModel.insert(mynote);
Toast.makeText(getApplicationContext(),"Note saved",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Unable to save note",Toast.LENGTH_SHORT).show();
}
}
}
在 MainActivity 中,我正在使用startActivityForResult方法从 AddNotes 活动中获取数据。我想知道如何修改代码,以便可以将数据添加到在线服务器。请有人指导,将不胜感激。
谢谢
答案 0 :(得分:0)
创建2个存储库
您的代码NoteRepositoryLocal
与NoteRepository
类似
为API调用添加新的存储库。 (在您的项目中实施okhttp并进行API调用的改进)
在ViewModel中,有两个方法调用。
noteRepositoryLocal.insert(note);
noteRepositoryLive.insert(note);
我没有添加NoteRepositoryLive
相关代码。如果您有问题,请告诉我。
希望这个答案对您有帮助:)