简体   繁体   中英

How to save data on online server using MVVM pattern in android

I am making an app using MVVM design pattern.Initially I tried adding data in offline database.Now I want to save data to online server.

Below is my code for offline data storage:

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();
        }
    }
}

In the MainActivity I am getting data from AddNotes Activity using startActivityForResult method.I want to know how can I modify my code so that I can add data to the online server. Someone please guide any help would be appreciated.

THANKS

Create 2 repository

  1. NoteRepositoryLocal
  2. NoteRepositoryLive

As your code NoteRepositoryLocal similar to NoteRepository Add a new Repository for API call. (Implement okhttp and retrofit for API call in your project)

In your ViewModel, there are two methods call.

noteRepositoryLocal.insert(note);
noteRepositoryLive.insert(note);

I am not adding NoteRepositoryLive related code. If you have a problem let me know.

Hope this answer helps you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM