无法从Room Library获取数据库数据

时间:2018-05-24 11:36:42

标签: android android-room

我正在使用Room来安装我的android项目。我能够成功地将数据插入数据库,但我无法从数据库中读取数据。我尝试了很多方法,但没有运气。也没有错误。我使用LiveData。我没有使用allowMainThreadQueries()

我的道......

@Dao
public interface VehicleDao {

    @Query("SELECT * FROM vehicle_login")
    LiveData<List<Vehicle>> getAll();

    @Insert
    void insertAll(Vehicle... users);

}

我的数据库......

public abstract class DispatchDatabase extends RoomDatabase {

    private static DispatchDatabase INSTANCE;
    public abstract VehicleDao vehicleDao();

    public static DispatchDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), DispatchDatabase.class, "user-database").build();
        }
        return INSTANCE;
    }

}

... MyViewModel

public class MyViewModel extends AndroidViewModel {
    private final LiveData<List<Vehicle>> currentList;
    private DispatchDatabase appDataBase;

    public MyViewModel(@NonNull Application application) {
        super(application);
        appDataBase = DispatchDatabase.getAppDatabase(application.getApplicationContext());
        currentList = appDataBase.vehicleDao().getAll();
    }

    public LiveData<List<Vehicle>> getCurrentData() {
        return currentList;
    }
}

我的活动......

 MyViewModel mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
mViewModel.getCurrentData().observe(LoginActivity.this, new Observer<List<Vehicle>>() {
    @Override
    public void onChanged(List<Vehicle> vehicles) {
        Log.d("vehicleNumber : ", String.valueOf(vehicles.size()));
    }
});

0 个答案:

没有答案