如何使 LiveData getValue() 函数 return 成为 Android 房间数据库中的项目列表?

How can I make the LiveData getValue() function return the list of items from my rooms database in Android?

我的 ViewModel class 中有一个 getAllFlights() 方法,它应该 return 我房间数据库中的所有航班,但是,当我在我的 [=20= 中调用该方法时],它 return 为空,即使我在数据库中有航班。下面是我调用 flightViewModel.getAllFlights.getValue() 方法的 activity 的代码。我正在使用 MVVM 模型。

Activity代码

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

        uploadAllBtn = findViewById(R.id.uploadAllReports);
        searchFlights = findViewById(R.id.searchFlightText);
        mRecyclerView = findViewById(R.id.recyclerView);


        flightViewModel = new ViewModelProvider(this).get(FlightViewModel.class);

        flightViewModel.getAllFlights().observe(this, new Observer<List<Flight>>() {
            @Override
            public void onChanged(List<Flight> flight_list) {

                String flightno = flight_list.get(1).getFlightNumber();
                String flightdate = flight_list.get(1).getDate();

                String[] flight_details = new String[2];
                flight_details[0]= flightno;
                flight_details[1] = flightdate;

                Log.v("pp", flight_details[0]);

                for(int i = 0; i <flight_list.size();i++){
                    String flightnumber = flight_list.get(i).getFlightNumber();
                    String departuredate = flight_list.get(i).getDate();

                    reportitems.add(new ReportItem(flightnumber,departuredate));

                    
                }
                flightViewModel.getAllFlights().removeObservers(ReportListingActivity.this);
            }
        });

        mLayoutManager = new LinearLayoutManager(ReportListingActivity.this);
        mAdapter = new ReportAdapter(reportitems, ReportListingActivity.this);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
    }

你不应该使用 getValue() 在观察数据的情况下你应该使用你的实时数据的 observe() 方法。

更新:

您可以使用此代码:

flightViewModel.getAllFlights().observe(this, new Observer<List<Flight>>() {
    @Override
    public void onChanged(List<Flight> flight_list) {

        if (flight_list.size() == 0) return;
    
        String flightno = flight_list.get(0).getFlightNumber();
        String flightdate = flight_list.get(0).getDate();

        String[] flight_details = new String[2];
        flight_details[0]= flightno;
        flight_details[1] = flightdate;

        for(int i = 0; i <flight_list.size();i++){
            String flightnumber = flight_list.get(i).getFlightNumber();
            String departuredate = flight_list.get(i).getDate();

            reportitems.add(new ReportItem(flightnumber,departuredate));
        }
        mRecyclerView.getAdapter().notifyDataSetChanged()
        flightViewModel.getAllFlights().removeObservers(this);
    }
});