1

我的数据库类是

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

存储库类是

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 类

@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 类是

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

在按钮单击的片段中,我调用公共方法 getVillages 总是返回 null。

在 Fragment Button Onclick 方法中,我使用了这样的观察者

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

对 ViewModel 方法的此调用不返回任何内容。在调试应用程序时,我发现来自 DAO 的查询返回 null,即使数据库具有预填充的值。

请指导我解决问题,因为我已经浪费了 6 个小时在互联网上寻找解决方案。

4

0 回答 0