Query in DAO is always returns null eventhough data exists in Database in Android-Room-LiveData-Fragments

122 views Asked by At

my database class is

public abstract class MyDatabase extends RoomDatabase {

private static MyDatabase instance;
public abstract DataAccess dataAccess();

public static MyDatabase getInstance(final Context context) {
    if(instance == null) {
        synchronized (MyDatabase.class) {
            if(instance == null) {
                instance = Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, "app.db")
                        .createFromAsset("test.db")
                        .fallbackToDestructiveMigration()
                        .build();
            }
        }

    }
    return instance;
}

repository class is

public class MyRepository {

private DataAccess dataAccess;    

public MyRepository(Application application) {
   MyDatabase myDatabase = MyDatabase.getInstance(application);
   dataAccess = mDatabase.dataAccess();
}

public LiveData<List<String>> getVillages(int id) {
    return dataAccess.getVillage(id);
}

private LiveData<List<VillagesModel>> fetchAllVillages(String search) {
    return dataAccess.AllVillages(search);
  }
}

DAO class

@Dao
public interface DataAccess {

   @Query("SELECT distinct Village FROM Villages  WHERE village like :search")
   LiveData<List<String>> AllVillages(String search);

   @Query("SELECT Village FROM Villages  WHERE id = :id")
   LiveData<List<String>> getVillages(int id);
}

ViewModel class is

 public class VillageViewModel extends AndroidViewModel {
    private MyRepository repository;
     private LiveData<List<lVillagesModel>> allVillages;

    public VillageViewModel(@NonNull Application application) {
        super(application);
    repository = new MyRepository(application);
   }


   public LiveData<List<VillagesModel>> getAllVillages(String poSearch) {
      return repository.AllVillages(pinSearch, poSearch);
   }
}

in Fragment on button click i called public method getVillages is returning always null.

in Fragment Button Onclick method i used observer like this

VillageViewModel.getAllVillages(search).observe(getViewLifecycleOwner(), new Observer<List<VillagesModel>>() {
            @Override
            public void onChanged(List<VillagesModel> fvillagesModels) {
                
                // updated the recyclerview contents here. 

                adapter.notifyDataSetChanged(); // this is recyclerView adapter
              }
            }

This call on ViewModel method returns nothing. While debugging the app, I found that Query from DAO is returning null even though Database has prepopulated values.

Please guide me to solve the problem as I already wasted 6 hours searching in internet for solution.

0

There are 0 answers