android 在片段中使用ViewModel时Recylerview为空

6yoyoihd  于 2023-02-06  发布在  Android
关注(0)|答案(1)|浏览(168)

在这里,屏幕中的第一个流程有三个按钮,也是使用回收器视图创建的。视图模型正在传递数据以填充按钮内容,即图像和文本。这工作得很好。单击按钮后,将加载一个新的屏幕/片段,其中应显示列表。使用以下方法获取API数据:

public class TrackRepository {

    MutableLiveData<TrackData> trackData;
    RestClient restClient;
    SharedPreferences sharedPreferences;

    public TrackRepository() {
        trackData = new MutableLiveData<>();
        this.restClient = new RestClient();
        sharedPreferences = SessionManager.getPreferences();
    
    }

    public void getTrackList(String startDate,String endDate,String searchTest){
    int centerId = ClientInfo.getCenterId(sharedPreferences);
    String auth = ClientInfo.getAuthToken(sharedPreferences);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("CenterId",centerId);
        jsonObject.addProperty("SearchText",searchTest);
        jsonObject.addProperty("StartDate",startDate);
        jsonObject.addProperty("EndDate",endDate);

        restClient.getEndpoints().getTrackReports(auth,jsonObject).enqueue(new Callback<TrackData>() {
            @Override
            public void onResponse(Call<TrackData> call, Response<TrackData> response) {
                if (response.isSuccessful()){
                    boolean success = response.body().isSuccess();
                    String message = response.body().getMessage();
                    try {
                        if (success) {
                            trackData.postValue(response.body());
                        }else {
                            trackData.postValue(response.body());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<TrackData> call, Throwable t) {
                trackData.postValue(null);

            }
        });

    }

    public LiveData<TrackData> getTrackDataMutableLiveData() {
        return trackData;
    }
}

此后,创建了片段TrackHome和TrackScreen使用的TrackHomeViewModel,如下所示

public class TrackHomeViewModel extends ViewModel {

    ArrayList<String> btName;//button text
    ArrayList<Integer> btImage; //button image
    int FLAG;
    SimpleDateFormat inFormat;
    private TrackRepository trackRepository;
    List<TrackData> trackList;
    LiveData<TrackData> track;
 
    public TrackHomeViewModel() {
            btName = new ArrayList<>();
            this.btName.add("Previous Day");
            this.btName.add("Previous Three Days");

            btImage = new ArrayList<>();
            this.btImage.add(R.drawable.ic_baseline_calendar_today_24);
            this.btImage.add(R.drawable.ic_baseline_calendar_view_day_24);
            trackRepository = new TrackRepository();
            track = trackRepository.getTrackDataMutableLiveData();

        }

        public void captureCardClick(int adapterPosition) {
            String selectedChoice;
            String searchTest,startDate,endDate;

            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
            inFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);
            Calendar cal = Calendar.getInstance();

            selectedChoice = btName.get(adapterPosition);

            if (selectedChoice.equals("Previous Day")) {
                FLAG = 1;
                searchTest = "";
                endDate = dateFormatter.format(cal.getTime()); // get current date
                cal.add(Calendar.DATE, -1); //ONE day before of current date
                startDate = dateFormatter.format(cal.getTime()); // get PREVIOUS date
                //   int centerId = ClientInfo.getCenterId(preferences);
                getTrackList(startDate,endDate,searchTest);
            }else if(selectedChoice.equals("Previous Three Days")){
                FLAG = 2;
                searchTest = "";
                endDate = dateFormatter.format(cal.getTime()); // get current date
                cal.add(Calendar.DATE, -3); //Three day before of current date
                startDate = dateFormatter.format(cal.getTime()); // get PREVIOUS date
                //   int centerId = ClientInfo.getCenterId(preferences);
                getTrackList(startDate,endDate,searchTest);
            }
        }

        public void getTrackList(String startDate,String endDate,String searchTest) {
            trackRepository.getTrackList(startDate, endDate, searchTest);
         }

    public LiveData<TrackData> getTrackLiveData() {
  
        return track;
    }
}

TrackScreen片段中,加载回收视图,如下所示:

public class TrackScreen extends Fragment {

    private TrackHomeViewModel trackHomeViewModel;
    RecyclerView recyclerView;
    TrackAdapter trackAdapter;
    LinearLayoutManager linearLayoutManager;
    Fragment trackHome;
    SearchView searchView;
    List<TrackData> trackDataList;
    TextView currentFragment;
    MaterialToolbar toolbar;
    ImageButton back;
    TrackInterface trackInterface;
    TrackData trackD;

    public static TrackScreen newInstance() {
        return new TrackScreen();
    }
  
    @Override
    public void onCreate(@Nullable Bundle saveInstanceState) {

        super.onCreate(saveInstanceState);
        trackHomeViewModel = new ViewModelProvider(this).get(TrackHomeViewModel.class);
        trackHomeViewModel.getTrackLiveData().observe(this, new Observer<TrackData>() {
            @Override
            public void onChanged(TrackData trackData) {
                trackD = trackData;
            }
        });

        trackInterface = new TrackInterface() {
            @Override
            public void captureRowClick(TrackData trackData, int adapterPosition) {
                String patId = trackData.getPatientId();
                Toast.makeText(getContext(), "Patient ID is " + patId, Toast.LENGTH_SHORT).show();
            }
        };

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_track_screen,container,false);

   
        toolbar = view.findViewById(R.id.toolbar);
        searchView = view.findViewById(R.id.search_report);
        recyclerView = view.findViewById(R.id.track_recycler);
        currentFragment = view.findViewById(R.id.current_fragment);
        currentFragment.setText("Reports");
        back = view.findViewById(R.id.back_screen);
      
        trackHome = getParentFragmentManager().findFragmentByTag("TrackHome");
      
        linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        if(trackAdapter==null) {
        trackHomeViewModel.getTrackLiveData().observe(getViewLifecycleOwner(), new Observer<TrackData>() {
            @Override
            public void onChanged(TrackData trackData) {
                trackAdapter = new TrackAdapter(getContext(),trackData.getTrackData(),trackInterface);
                }
             });

                    recyclerView.setAdapter(trackAdapter);
                }else{
                    Toast.makeText(getContext(), "No Data Found", Toast.LENGTH_SHORT).show();
                }
     // other code
    }
}

从API加载数据,但TrackScreen显示空白屏幕,带有E/RecyclerView:未连接适配器;跳过布局消息,我测试了所有其他内容,仍然是相同的消息。问题是当TrackScreen片段加载列表时列表为空,执行getTrackLiveData()方法后,它加载API数据,因此加载列表为空,所以出现此消息。我不知道如何解决此问题。
当按钮被点击时,它应该加载带有列表的TrackScreen片段。如上所述尝试。

tzxcd3kk

tzxcd3kk1#

你得走了

recyclerView.setAdapter(trackAdapter);

public void onChanged(TrackData trackData) {
    ...
}

现在,当您将trackAdapter字段设置为recyclerView时,它为null,因为onChanged是异步调用的。

相关问题