How do I get the value from a single LiveData Object [duplicate] - android

This question already has answers here:
Paging Library Filter/Search
(3 answers)
Closed 2 years ago.
I decided to optimize my code and therefore switch to liveData. I followed a tutorial on youtube (youtube link) but I do not quite understand how I can filter my recyclerView when the user enters a word since I do not store any list in my Adapter. I use a simple searchview filter system on my MainActivity.
Moreover, I use DiffUtil to update my recyclerView and I update my Adapter thanks to:
noteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, adapter::submitList);
My code is almost identical to the video but here is a part of it:
ViewModel:
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(List<Note> notes) {
repository.delete(notes);
}
public LiveData<List<Note>> getAllNotes() {
return allNotes;
}
}
My repository:
public class NoteRepository {
private NotesDAO notesDAO;
private LiveData<List<Note>> allNotes;
public NoteRepository(Application application) {
NotesDB database = NotesDB.getInstance(application);
notesDAO = database.notesDAO();
allNotes = notesDAO.getAllNotes();
}
public void insert(Note note) {
new InsertNoteAsyncTask(notesDAO).execute(note);
}
public void update(Note note) {
new UpdateNoteAsyncTask(notesDAO).execute(note);
}
public void delete(List<Note> note) {
new DeleteNoteAsyncTask(notesDAO).execute(note);
}
public LiveData<List<Note>> getAllNotes() {
return allNotes;
}
private static class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> { // SOME STUFF }
private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> { // SOME STUFF }
private static class DeleteNoteAsyncTask extends AsyncTask<List<Note>, Void, Void> { // SOME STUFF }
}

Finally, thanks to #EpicPandaForce, I did that:
My ViewModel:
public class NoteViewModel extends AndroidViewModel {
private NoteRepository repository;
private final LiveData<List<Note>> allNotes;
private MutableLiveData<String> filterText = new MutableLiveData<>();
public NoteViewModel(#NonNull Application application) {
super(application);
repository = new NoteRepository(application);
allNotes = Transformations.switchMap(filterText, (input) ->
{
if(input == null || input.equals(""))
return repository.getAllNotes();
else
return repository.filter(input);
});
}
public void setFilter(String query) {
filterText.setValue(query);
}
public LiveData<List<Note>> getAllNotes() {
return allNotes;
}
}
In my repository:
public LiveData<List<Note>> filter(String input) {
try {
return new FilterNoteAsyncTask(notesDAO).execute(input).get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
private static class FilterNoteAsyncTask extends AsyncTask<String, Void, LiveData<List<Note>>> {
private NotesDAO notesDAO;
private FilterNoteAsyncTask(NotesDAO notesDAO) {
this.notesDAO = notesDAO;
}
#Override
protected LiveData<List<Note>> doInBackground(String... strings) {
return notesDAO.filter(strings[0]);
}
}
And I perform the request in the database thanks to:
#Query("SELECT * FROM note_table WHERE LOWER(title) LIKE '%' || :search || '%'")
LiveData<List<Note>> filter(String search);

Related

How to call sequence of function in Observer in android

Currently this line "observer = data -> createTokenMap(data.getPositions());" calls a function and do some logic.
How can I accept a return value from this function and pass it into another function and so on.
public class PositionViewModel extends AndroidViewModel {
private final LiveData<PositionResponse> positionResponseLiveData;
private final Observer<PositionResponse> observer;
private final Map<String, Long> tokenMap = new HashMap<>();
public PositionViewModel(#NonNull Application application) {
super(application);
observer = data -> createTokenMap(data.getPositions());
positionResponseLiveData = PositionRepository.getInstance().getPositions();
positionResponseLiveData.observeForever(observer);
}
public LiveData<PositionResponse> getPositions() {
return positionResponseLiveData;
}
private void createTokenMap(Positions positions) {
for (Net position : positions.getNet()) {
tokenMap.put(position.getTradingsymbol(), position.getInstrument_token());
}
for (Day position : positions.getDay()) {
tokenMap.put(position.getTradingsymbol(), position.getInstrument_token());
}
}
public Map<String, Long> getTokenMap() {
return tokenMap;
}
#Override
protected void onCleared() {
super.onCleared();
positionResponseLiveData.removeObserver(this.observer);
}
}
Any help will be highly appreciated.

How should I code if i want Query specific the with Room? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am now learing how to save data in a local database using Room in Android Dev Doc. And I had done the Codelab in this links.https://developer.android.com/codelabs/android-room-with-a-view#0 I can Upddate, Insert, Delete and Query all data in table.
Now, I want Query the data with specific id. How should I code in ViewModel and Repository class? Thanks.
My table named "Diary",
Diary.class
#Entity(tableName = "diary_table")
public class Diary {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "diary_title")
private String diary_Title;
#ColumnInfo(name = "diary_content")
private String diary_Content;
public Diary(#NonNull String diary_Title, String diary_Content) {
this.diary_Title = diary_Title;
this.diary_Content = diary_Content;
}
public void setDiary_Title(String diary_Title) {
this.diary_Title = diary_Title;
}
public void setDiary_Content(String diary_Content) {
this.diary_Content = diary_Content;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getStrId() {
return String.valueOf(id);
}
public String getDiary_Title() {
return diary_Title;
}
public String getDiary_Content() {
return diary_Content;
}
}
DiaryDao.class
#Dao
public interface DiaryDao {
#Insert
void insertDiaries(Diary... diaries);
#Update
void updateDiaries(Diary... diaries);
#Delete
void deleteDiaries(Diary... diaries);
//删除到一无所有 慎用!
#Query("DELETE FROM diary_table")
void deleteAllDiaries();
#Query("SELECT * FROM diary_table ORDER BY ID ASC")
LiveData<List<Diary>>getAllDiariesLive();//get all diary
#Query("SELECT * FROM diary_table WHERE ID=:id")
LiveData<Diary> getSpecificDiariesLive(int id);//get specific diary
}
DiaryRepository
class DiaryRepository {
private LiveData<Diary> specificDiary;
private LiveData<List<Diary>> allDiariesLive;
private DiaryDao diaryDao;
DiaryRepository(Context context) {
DiaryRoomDatabase diaryRoomDatabase = DiaryRoomDatabase.getDiaryDatabase(context.getApplicationContext());
diaryDao = diaryRoomDatabase.getDiaryDao();
allDiariesLive = diaryDao.getAllDiariesLive();
specificDiary = diaryDao.getSpecificDiariesLive(/**how should i code here***/);
}
void insetDiaries(Diary... diaries) {
new InsertAsyncTask(diaryDao).execute(diaries);
}
void updateDiaries(Diary... diaries) {
new UpdateAsyncTask(diaryDao).execute(diaries);
}
void deleteDiaries(Diary... diaries) {
new DeleteAsyncTask(diaryDao).execute(diaries);
}
void deleteAllDiaries(Diary... diaries) {
new DeleteAllAsyncTask(diaryDao).execute();
}
LiveData<Diary> getSpecificDiary(int i) {return specificDiary; }
LiveData<List<Diary>> getAllDiariesLive() {
return allDiariesLive;
}
static class InsertAsyncTask extends AsyncTask<Diary, Void, Void> {
private DiaryDao diaryDao;
InsertAsyncTask(DiaryDao diaryDao) {
this.diaryDao = diaryDao;
}
#Override
protected Void doInBackground(Diary... diaries) {
diaryDao.insertDiaries(diaries);
return null;
}
}
static class UpdateAsyncTask extends AsyncTask<Diary, Void, Void> {
private DiaryDao diaryDao;
UpdateAsyncTask(DiaryDao diaryDao) {
this.diaryDao = diaryDao;
}
#Override
protected Void doInBackground(Diary... diaries) {
diaryDao.updateDiaries(diaries);
return null;
}
}
static class DeleteAsyncTask extends AsyncTask<Diary, Void, Void> {
private DiaryDao diaryDao;
DeleteAsyncTask(DiaryDao diaryDao) {
this.diaryDao = diaryDao;
}
#Override
protected Void doInBackground(Diary... diaries) {
diaryDao.deleteDiaries(diaries);
return null;
}
}
static class DeleteAllAsyncTask extends AsyncTask<Void, Void, Void> {
private DiaryDao diaryDao;
DeleteAllAsyncTask(DiaryDao diaryDao) {
this.diaryDao = diaryDao;
}
#Override
protected Void doInBackground(Void... voids) {
diaryDao.deleteAllDiaries();
return null;
}
}
}
DiaryViewModel.class
public class DiaryViewModel extends AndroidViewModel {
private DiaryRepository diaryRepository;
public DiaryViewModel(#NonNull Application application) {
super(application);
diaryRepository = new DiaryRepository(application);
}
public LiveData<Diary> getSpecificDiary(/**how should i code here?**/) {
return diaryRepository.getSpecificDiary(i);
}
public LiveData<List<Diary>> getAllDiariesLive() {
return diaryRepository.getAllDiariesLive();
}
public void insertDiaries(Diary... diaries) {
diaryRepository.insetDiaries(diaries);
}
public void updateDiaries(Diary... diaries) { diaryRepository.updateDiaries(diaries); }
public void deleteDiary(Diary... diaries) { diaryRepository.deleteDiaries(diaries);}
public void deleteAllDiaries() {
diaryRepository.deleteAllDiaries();
}
}
I think in DiaryRepository:
class DiaryRepository {
private LiveData<List<Diary>> allDiariesLive;
private DiaryDao diaryDao;
DiaryRepository(Context context) {
DDiaryRoomDatabase diaryRoomDatabase = DiaryRoomDatabase.getDiaryDatabase(context.getApplicationContext());
diaryDao = diaryRoomDatabase.getDiaryDao();
allDiariesLive = diaryDao.getAllDiariesLive();
}
void insetDiaries(Diary... diaries) {
new InsertAsyncTask(diaryDao).execute(diaries);
}
void updateDiaries(Diary... diaries) {
new UpdateAsyncTask(diaryDao).execute(diaries);
}
void deleteDiaries(Diary... diaries) {
new DeleteAsyncTask(diaryDao).execute(diaries);
}
void deleteAllDiaries(Diary... diaries) {
new DeleteAllAsyncTask(diaryDao).execute();
}
LiveData<Diary> getSpecificDiary(int i) {
return diaryDao.getSpecificDiariesLive(i);
}
LiveData<List<Diary>> getAllDiariesLive() {
return allDiariesLive;
}
...
so your ViewModel will be changed to this:
public class DiaryViewModel extends AndroidViewModel {
private DiaryRepository diaryRepository;
public DiaryViewModel(#NonNull Application application) {
super(application);
diaryRepository = new DiaryRepository(application);
}
public LiveData<Diary> getSpecificDiary(int i) {
return diaryRepository.getSpecificDiary(i);
}
...
DiaryRepository.class and ViewModel.class like hosseini sajad code. And i should use this with livedata like follow:
mDiaryViewModel = new ViewModelProvider(activity).get(DiaryViewModel.class);
mDiaryViewModel.getSpecificDiary(pos+1).observe(activity, diary -> {
Log.d("test", "Here is the Title: " + diary.getDiary_Title() + "\n" + "Here is the Content: " +diary.getDiary_Content() );
});

Room database is returning 1 extra object

I have a room DB class that creates 3 user objects -
#Database(entities = {User.class}, version = 1, exportSchema = false)
public abstract class UserDatabase extends RoomDatabase {
private static UserDatabase instance;
public abstract UserDao userDao();
public static synchronized UserDatabase getInstance(Context context) {
Log.d("inside observe - ", "inside database");
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(), UserDatabase.class, "user_database").fallbackToDestructiveMigration().addCallback(roomUserCallback).build();
}
return instance;
}
private static RoomDatabase.Callback roomUserCallback = new RoomDatabase.Callback() {
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
new PopulateDbAsyncTask(instance).execute();
}
};
//TODO - delete this in the future. This is just for populating.
private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
static final String URL = "https://www.shortlist.com/media/images/2019/05/40-favourite-songs-of-famous-people-28-1556672663-9rFo-column-width-inline.jpg";
static final String URL2 = "https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BBR9VUw.img?h=416&w=624&m=6&q=60&u=t&o=f&l=f&x=2232&y=979";
static final String URL3 = "https://dz9yg0snnohlc.cloudfront.net/new-what-famous-people-with-depression-have-said-about-the-condition-1.jpg";
private UserDao userDao;
private PopulateDbAsyncTask(UserDatabase db) {
userDao = db.userDao();
}
#Override
protected Void doInBackground(Void... voids) {
userDao.insert(new User(URL, "Barak Obama1", "/#BarakObama1"));
userDao.insert(new User(URL2, "Barak Obama2", "/#BarakObama2"));
userDao.insert(new User(URL3, "Barak Obama3", "/#BarakObama3"));
return null;
}
}
}
I am using viewmodel in order to fetch the users as LiveData.
For some reason, at the first time I install my app, I get one extra "barak obama1" user created, and immedeatly after than all 3 "normal" users by order - barak obama3, 2 and 1.
Here is my MainActivity -
private ArrayList<User> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fetchUserList();
}
private void fetchUserList() {
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
final Observer<List<User>> userObserver = users -> {
Log.d("inside observe - ", "inside main activity, list size - " + users.size());
usersList = (ArrayList) users;
initViewsAndListeners();
addCards();
};
userViewModel.getAllUsers().observe(this, userObserver);
}
private void addCards(){
TinderCardView tinderCardView;
for (int i = 0; i < usersList.size(); i++) {
tinderCardView = new TinderCardView(this);
tinderCardView.bind(usersList.get(i));
Log.d("inside observe - ", "inside main activity, user value - " + usersList.get(i).getUsername());
tinderStackLayout.addCard(tinderCardView);
Log.d("addCardCalled - ", "\nindex value - " + i + "\n" +
"userlist size - " + usersList.size());
}
}
#Override
public void onClick(View view) {
int buttonTag = Integer.valueOf(String.valueOf(view.getTag()));
TinderCardView topCardOnStack = tinderStackLayout.getTopCardOnStack();
topCardOnStack.handleButtonPressed(buttonTag);
// if (buttonTag == 1) { // TODO - move logic to card class
// userViewModel.delete(usersList.get(0));
// //fetchUserList();
// }
}
private void initViewsAndListeners() {
tinderStackLayout = findViewById(R.id.activity_main_tinder_stack_layout);
mDeleteButton = findViewById(R.id.activity_main_delete_button);
mPassButton = findViewById(R.id.activity_main_pass_button);
mApproveButton = findViewById(R.id.activity_main_approve_button);
mDeleteButton.setOnClickListener(this);
mApproveButton.setOnClickListener(this);
mPassButton.setOnClickListener(this);
}
As you can see I have log messages all over so you can understand what I am about to show you now. I am getting one extra user, "barak obama1" user first and then after that all other 3 -
The livedata figures out that there was 1 user in the list, adds in as a card and than the DB creates new objects and the livedata recalls the method, adding 3 more users.
Why is this happening?? I would glady kiss someone's leg if he solves this issue, no joke.
edit -
here is my ViewModel -
public class UserViewModel extends AndroidViewModel {
private UserRepository repository;
private LiveData<List<User>> allUsers;
public UserViewModel(#NonNull Application application) {
super(application);
repository = new UserRepository(application);
allUsers = repository.getAllUsers();
}
public void insert(User user) {
repository.insert(user);
}
public void update(User user) {
repository.update(user);
}
public void delete(User user) {
repository.delete(user);
}
public void deleteAllUsers(){
repository.deleteAllUsers();
}
public LiveData<List<User>> getAllUsers() {
Log.d("inside observe - ", "inside viewmodel");
return allUsers;
}
}
and my respository -
public class UserRepository {
private UserDao userDao;
private LiveData<List<User>> allUsers;
public UserRepository(Application application) {
UserDatabase database = UserDatabase.getInstance(application);
userDao = database.userDao();
allUsers = userDao.getAllUsers();
}
public void insert(User user) {
new InsertUserAsyncTask(userDao).execute(user);
}
public void update(User user) {
new UpdateUserAsyncTask(userDao).execute(user);
}
public void delete(User user) {
new DeleteUserAsyncTask(userDao).execute(user);
}
public void deleteAllUsers() {
new DeleteAllUsersAsyncTask();
}
public LiveData<List<User>> getAllUsers() {
Log.d("inside observe - ", "inside repository");
return allUsers;
}
//TODO - migrate all 4 async tasks into one.
private static class InsertUserAsyncTask extends AsyncTask<User, Void, Void> {
private UserDao userDao;
private InsertUserAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.insert(users[0]);
return null;
}
}
private static class UpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
private UserDao userDao;
private UpdateUserAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.update(users[0]);
return null;
}
}
private static class DeleteUserAsyncTask extends AsyncTask<User, Void, Void> {
private UserDao userDao;
private DeleteUserAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.delete(users[0]);
return null;
}
}
private static class DeleteAllUsersAsyncTask extends AsyncTask<Void, Void, Void> {
private UserDao userDao;
private DeleteAllUsersAsyncTask() {
this.userDao = userDao;
}
#Override
protected Void doInBackground(Void... voids) {
userDao.deleteAllUsers();
return null;
}
}
}
edit -
here is my dao -
#Dao
public interface UserDao {
#Insert
void insert(User user);
#Update
void update(User user);
#Delete
void delete(User user);
#Query("DELETE FROM user_table")
void deleteAllUsers();
#Query("SELECT * FROM user_table ORDER BY id DESC")
LiveData<List<User>> getAllUsers();
}
Insert all users in 1 transaction.
2 approaches:
1. Create a function in dao that receive list of users.
2. Create a transaction in roomDB (google how. Very simple)
I prefer the first one
try to understand
i have made comments
this is raw code just to give you idea
private ArrayList<User> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.usersList = new ArrayList(); // initalise the array list here
fetchUserList();
}
private void fetchUserList() {
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
final Observer<List<User>> userObserver = users -> {
Log.d("inside observe - ", "inside main activity, list size - " + users.size());
usersList = (ArrayList) users; //dont do this ! instead follow the below instructions
// to do
for(User user : users){
if(!usersList.contains(user)){
usersList.add(user);
}
}
// to do ends here
initViewsAndListeners();
addCards();
};
userViewModel.getAllUsers().observe(this, userObserver);
}
}
look what i have done:
initalised the usersList
and when observing the users live data i use loop and in that loop i
check if this user is already added
do you get it ?

How can I make the repository take more than one column?

The below code is from an APP I am making based on another simple APP where the Entity had only one column.
Now I have added another column (materialBrand) and I am having difficulties in implementing the same on the repository class in the AsynkTask.
Please Help.
This is the class Entity:
#Entity(tableName = "material_table")
public class MaterialEntity {
#PrimaryKey
#NonNull
#ColumnInfo(name = "material_name")
private String mMaterialName;
#ColumnInfo(name = "material_brand")
private String mMaterialBrand;
public MaterialEntity(#NonNull String materialName, String materialBrand) {
this.mMaterialName = materialName;
this.mMaterialBrand = materialBrand;
}
public String getMaterialName(){
return this.mMaterialName;
}
public String getMaterialBrand(){
return this.mMaterialBrand;
}
}
This is the Dao:
#Dao
public interface MaterialDao {
#Insert
void insert(MaterialEntity materialName, MaterialEntity materialBrand);
#Query("DELETE FROM material_table")
void deleteAll();
#Query("SELECT * from material_table ORDER BY material_name ASC")
LiveData<List<MaterialEntity>> getAllMaterials();
}
This is the Repository Class:
public class MaterialRepository {
private MaterialDao mMaterialDao;
private LiveData<List<MaterialEntity>> mAllMaterial;
public MaterialRepository(Application application) {
MaterialRoomDatabase db = MaterialRoomDatabase.getDatabase(application);
mMaterialDao = db.materialDao();
mAllMaterial = mMaterialDao.getAllMaterials();
}
public LiveData<List<MaterialEntity>> getAllMaterials() {
return mAllMaterial;
}
public void insert (MaterialEntity materialName, MaterialEntity materialBrand) {
new insertAsyncTask(mMaterialDao).execute(materialName, materialBrand);
}
private static class insertAsyncTask extends AsyncTask<MaterialEntity, Void, Void> {
private MaterialDao mAsyncTaskDao;
insertAsyncTask(MaterialDao dao) {
mAsyncTaskDao = dao;
}
#Override
protected Void doInBackground(final MaterialEntity... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
}
below insert method has two params as args
#Dao
public interface MaterialDao {
#Insert
void insert(MaterialEntity materialName, MaterialEntity materialBrand);
#Query("DELETE FROM material_table")
void deleteAll();
#Query("SELECT * from material_table ORDER BY material_name ASC")
LiveData<List<MaterialEntity>> getAllMaterials();
}
You cannot send only one param.
mAsyncTaskDao.insert(params[0]);

Android - Room Repository and AsyncTask, how to use query to get back data from table

How do you get data from your Room entity using AsyncTask? I've been looking through the answers regarding AsyncTask but I don't get it.
This is my Dao:
#Dao
public interface BudgetDao {
#Insert
public void insert (Budget budget);
#Update
public void update (Budget budget);
#Query("SELECT id FROM budget_table WHERE category = :category AND date = :date")
int getId(String category, String date);
#Query("SELECT * FROM budget_table")
LiveData<List<Budget>> getAllBudgets();
#Query("SELECT category FROM budget_table")
List<String> getAllCategories();
}
How do I get the AsyncTask in my repository to return a list of strings? Right now the code is public void getAllCategories() {new getAllCatsAsyncTask(mBudgetDao).execute(); When I change the void to List, an error shows that I can't return a list of strings
My Repository:
public class BudgetRepository {
private BudgetDao mBudgetDao;
private LiveData<List<Budget>> mAllBudgets;
BudgetRepository(Application application) {
BudgetRoomDatabase db = BudgetRoomDatabase.getDatabase(application);
mBudgetDao = db.budgetDao();
mAllBudgets = mBudgetDao.getAllBudgets();
}
LiveData<List<Budget>> getAllBudgets() {return mAllBudgets;}
public void insert (Budget budget) {new insertAsyncTask(mBudgetDao).execute(budget);}
public void getAllCategories() {new getAllCatsAsyncTask(mBudgetDao).execute();}
//How do I return a list of strings?
private static class insertAsyncTask extends AsyncTask<Budget, Void, Void> {
//code
}
private class getAllCatsAsyncTask extends AsyncTask<Void, Void, List<String>> {
private BudgetDao mAsyncTaskDao;
getAllCatsAsyncTask(BudgetDao dao) {mAsyncTaskDao = dao;}
#Override
protected List<String> doInBackground(Void... voids) {
return mAsyncTaskDao.getAllCategories();
}
}
}
In my ViewModel:
public class BudgetViewModel extends AndroidViewModel {
private BudgetRepository mRepository;
private LiveData<List<Budget>> mAllBudgets;
public BudgetViewModel(#NonNull Application application) {
super(application);
mRepository = new BudgetRepository(application);
mAllBudgets = mRepository.getAllBudgets();
}
LiveData<List<Budget>> getAllBudgets() {return mAllBudgets;}
public void insert(Budget budget) {mRepository.insert(budget);}
public List<String> getAllCats() { return mRepository.getAllCategories();}
//Android Studios show incompatible types (Void vs List<String>)
Right now, in my ViewModel, mRepository.getAllCategories does not return a list of strings.
Do I have to call onPostExecute in my AsyncTask? How do I link the results from onPostExecute so that getAllCategories can return a list of strings in my AsyncTask? Or is there a better way to call for queries from my Dao?
Try this code..
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DisplayData displayData=new DisplayData(studentDatabase);
displayData.execute();
}
/**
* this method display student.
*/
private void DisplayStudent() {
mStudentList.addAll(studentDatabase.studentDao().getStudent());
}
private class DisplayData extends AsyncTask<Void,Void,Void>
{
private StudentDatabase studentDatabase;
public DisplayData(StudentDatabase studentDatabase) {
this.studentDatabase = studentDatabase;
}
#Override
protected Void doInBackground(Void... params) {
DisplayStudent();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mDialog.dismiss();
mStu_adapter=new StudentAdapter(mStudentList,getApplicationContext());
mStu_adapter.notifyDataSetChanged();
mRvStudent.setAdapter(mStu_adapter);
DividerItemDecoration divider=new DividerItemDecoration(getApplicationContext(),LinearLayout.VERTICAL);
divider.setDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.divider));
mRvStudent.addItemDecoration(divider);
}
}
if you want to allow on mainThread then set this line.
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").allowMainThreadQueries().build();

Categories

Resources