LiveD和ViewM TRU

时间:2019-04-20 04:14:58

标签: java

我正在为roomDatabase创建一个liveData和ViewModel类,并且对如何调用SQL命令更改数据库内容感到困惑。

Room持久性库在SQLite上提供了一个抽象层,以在利用SQLite的全部功能的同时允许更健壮的数据库访问。有关更多信息,请参见参考文档。

修复了一个错误,即如果添加了内容表和外部内容FTS表的观察者,则无效跟踪器将停止观察内容表。 b / 128508917 更新了Room的SQLite语法以匹配SQLite 3.24.0。 b / 110883668

LIVEDATA AND VIEWMODEL WITH ROOMDATABASE

Defining Table in roomDatabase with corresponding column names and a unique primaryKey

@Entity(tableName = "note_table")
public class Note {

 Variables below are names of the column names

@PrimaryKey(autoGenerate = true)
    private int id;

    private String title;

    private String description;

    private int priority;

    public Note(String title, String description, int priority) {
        this.title = title;
        this.description = description;
        this.priority = priority;
    }
    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }
    public int getPriority() {
        return priority;
    }
}
This is an interface class where methods are created with corresponding SQL statements
@Dao
public interface NoteDao {

    @Insert
    void insert(Note note);

    @Update
    void update(Note note);

    @Delete
    void delete(Note note);

    @Query("DELETE FROM note_table")
    void deleteAllNotes();

    @Query("SELECT * FROM note_table ORDER BY priority DESC")
    (Comment: LiveData acts as an observer for any changes in the DB) LiveData<List<Note>> getAllNotes();
}
Repository class executes sql commands to insert, delete, update or deleteAll data in the Room Database
public class NoteRepository {
    private NoteDao noteDao;
    private LiveData<List<Note>> allNotes;

    public NoteRepository(Application application) {
        NoteDatabase database = NoteDatabase.getInstance(application);
        noteDao = database.noteDao();
        allNotes = noteDao.getAllNotes();
    }

    public void insert(Note note) {
        new InsertNoteAsyncTask(noteDao).execute(note);
    }

    public void update(Note note) {
        new UpdateNoteAsyncTask(noteDao).execute(note);
    }

    public void delete(Note note) {
        new DeleteNoteAsyncTask(noteDao).execute(note);
    }

    public void deleteAllNotes() {
        new DeleteAllNotesAsyncTask(noteDao).execute();
    }

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

    private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> {
        private NoteDao noteDao;

        private UpdateNoteAsyncTask(NoteDao noteDao) {
            this.noteDao = noteDao;
        }

        @Override
        protected Void doInBackground(Note... notes) {
            noteDao.update(notes[0]);
            return null;
        }
    }

    private static class DeleteNoteAsyncTask extends AsyncTask<Note, Void, Void> {
        private NoteDao noteDao;

        private DeleteNoteAsyncTask(NoteDao noteDao) {
            this.noteDao = noteDao;
        }

        @Override
        protected Void doInBackground(Note... notes) {
            noteDao.delete(notes[0]);
            return null;
        }
    }

    private static class DeleteAllNotesAsyncTask extends AsyncTask<Void, Void, Void> {
        private NoteDao noteDao;

        private DeleteAllNotesAsyncTask(NoteDao noteDao) {
            this.noteDao = noteDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            noteDao.deleteAllNotes();
            return null;
        }
    }
}
ViewModel class updates the UI in the mainActivity when changes occur in room database through repository class
public class NoteViewModel extends AndroidViewModel {
    private NoteRepository repository;
    private LiveData<List<Note>> allNotes;

    public NoteViewModel(@NonNull Application application) {
        super(application);
        repository = new NoteRepository(application);
        allNotes = repository.getAllNotes();
    }

    public void insert(Note note) {
        repository.insert(note);
    }

    public void update(Note note) {
        repository.update(note);
    }

    public void delete(Note note) {
        repository.delete(note);
    }

    public void deleteAllNotes() {
        repository.deleteAllNotes();
    }

    public LiveData<List<Note>> getAllNotes() {
        return allNotes;
    }

public class NoteViewModel extends AndroidViewModel {
    private NoteRepository repository;
    private LiveData<List<Note>> allNotes;

    public NoteViewModel(@NonNull Application application) {
        super(application);
        repository = new NoteRepository(application);
        allNotes = repository.getAllNotes();
    }

    public void insert(Note note) {
        repository.insert(note);
    }

    public void update(Note note) {
        repository.update(note);
    }

    public void delete(Note note) {
        repository.delete(note);
    }

    public void deleteAllNotes() {
        repository.deleteAllNotes();
    }
    public LiveData<List<Note>> getAllNotes() {
        return allNotes;
    }
}
MainActivity has the UI whose data can be updated using the viewModel class(instance of view model class needs to be created in MainActivity)
public class MainActivity extends AppCompatActivity {
    private NoteViewModel noteViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

        final NoteAdapter adapter = new NoteAdapter();
        recyclerView.setAdapter(adapter);

        noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
        noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
            @Override
            public void onChanged(@Nullable List<Note> notes) {
                adapter.setNotes(notes);
            }
        });
    }
}

H’s LiveData and ViewModel class

LiveData class with setValue and getValue methods
public class MutabxleLiveData<T> extends LiveData<T> {

    @Override
    protected void setValue(T value) {
        super.setValue(value);
    }


    @Override
    public T getValue() {
        return super.getValue();
    }
}


ViewModel class

public class createNumber extends ViewModel {

    private MutableLiveData<String> myRandomNumber;

    public MutableLiveData<String> getNumber() {
        Log.i("viewmodel", "Create new number");
         if (myRandomNumber == null) {
             myRandomNumber = new MutableLiveData<>();
             createNumber();
        }
        return myRandomNumber;
    }

    public void createNumber() {
        Log.i("viewmodel", "Create new number");
        Random random = new Random();
        myRandomNumber.setValue("Number: " + (random.nextInt(10 - 1) + 1));
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        Log.i("viewmodel", "ViewModel: onCleared");

    }
}

MainActivity 

public class MainActivity extends AppCompatActivity {
    TextView mytext;
    Button btn01;
    createNumber myviewmodel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mytext = (TextView) findViewById(R.id.textView01);
        btn01 = (Button)findViewById(R.id.button01);
        myviewmodel = ViewModelProviders.of(this).get(createNumber.class);
        LiveData<String> myrandomnumber =  myviewmodel.getNumber();
        myrandomnumber.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                mytext.setText(s);
            }
        });


        btn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myviewmodel.createNumber();
            }
        });
    }



}




MainActivity 

public class MainActivity extends AppCompatActivity {
    TextView mytext;
    Button btn01;
    createNumber myviewmodel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mytext = (TextView) findViewById(R.id.textView01);
        btn01 = (Button)findViewById(R.id.button01);
        myviewmodel = ViewModelProviders.of(this).get(createNumber.class);
        LiveData<String> myrandomnumber =  myviewmodel.getNumber();
        myrandomnumber.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                mytext.setText(s);
            }
        });


        btn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myviewmodel.createNumber();
            }
        });
    }



}

This should update the UI in the mainActivity

0 个答案:

没有答案