gpt4 book ai didi

java - ViewModelProviders 弃用的正确替代方案是什么?

转载 作者:行者123 更新时间:2023-12-02 03:59:58 27 4
gpt4 key购买 nike

由于所说的贬值,我不再使用 ViewModelProviders.of(this)。我研究了其他问题并使用了答复中的代码。所有代码都没有错误,但当我尝试运行该应用程序时,出现异常。

此处发生错误。

Process: com.example.checkingin, PID: 555
java.lang.RuntimeException: Cannot create an instance of class com.example.checkingin.MainViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.example.checkingin.CheckInRecentList.onActivityCreated(CheckInRecentList.java:123)

checkin 最近列表

package com.example.checkingin;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;

/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link CheckInRecentList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link CheckInRecentList#newInstance} factory method to
* create an instance of this fragment.
*/
public class CheckInRecentList extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView recyclerView;
private RecyclerView.Adapter checkInListAdapter;
//private RecyclerView.LayoutManager layoutManager;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MainViewModel mViewModel;
private CheckInListAdapter adapter;
private TextView checkInLastDateTime;
private TextView checkInTitle;
private TextView checkInDestinationName;
private TextView checkInComments;

private OnFragmentInteractionListener mListener;

public CheckInRecentList() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment CheckInRecentList.
*/
// TODO: Rename and change types and number of parameters
public static CheckInRecentList newInstance(String param1, String param2) {
CheckInRecentList fragment = new CheckInRecentList();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// These were originally set up from the recycler view add to the fragment
// recyclerView = findViewById(R.id.check_in_recent_recycler_view);

// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
//recyclerView.setHasFixedSize(true);
/*
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
*/
// specify an adapter (see also next example)
//checkInListAdapter = new CheckInListAdapter();
// recyclerView.setAdapter(checkInListAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_check_in_recent_list, container, false);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = new ViewModelProvider(this).get(MainViewModel.class);**

checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
checkInTitle = getView().findViewById(R.id.checkInTitle);
checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
checkInComments = getView().findViewById(R.id.checkInComments);

listenerSetup();
observerSetup();
recyclerSetup();
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void clearFields() {
checkInLastDateTime.setText("");
checkInDestinationName.setText("");
checkInTitle.setText("");
checkInComments.setText("");
}

private void listenerSetup() {

Button editCheckInButton = getView().findViewById(R.id.checkInEditButton);
Button resendCheckInButton = getView().findViewById(R.id.checkInResendButton);

editCheckInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//put in edit check in logic
}
});
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//put in resend logic
}
});

}

private void observerSetup() {

mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>> ()
{
@Override
public void onChanged(@Nullable final List<CheckInTable> checkIn) {
adapter.setCheckInList(checkIn);
}
});

mViewModel.getSearchCheckInResults().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>() {
@Override
public void onChanged(@Nullable final List<CheckInTable> checkIn) {

if (checkIn.size() > 0) {

checkInLastDateTime.setText(checkIn.get(0).getCheckInLastDateTime());
checkInDestinationName.setText(checkIn.get(0).getCheckInDestinationName());
checkInTitle.setText(checkIn.get(0).getCheckInTitle());
checkInComments.setText(checkIn.get(0).getCheckInComments());
} else {
checkInLastDateTime.setText("None Found");
}
}
});
}
private void recyclerSetup() {

RecyclerView recyclerView;

adapter = new CheckInListAdapter(R.layout.recycler_view_item);
recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
}
}

MainViewModel

package com.example.checkingin;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.util.List;

public class MainViewModel extends AndroidViewModel {

private CheckInRecipientsTableRepository checkInRecipientsTableRepository;
private LiveData<List<CheckInRecipientsTable>> allRecipients;
private MutableLiveData<List<CheckInRecipientsTable>> searchRecipientResults;

private ContactGroupsTableRepository contactGroupsTableRepository;
private LiveData<List<ContactGroupsTable>> allContactGroups;
private MutableLiveData<List<ContactGroupsTable>> searchContactGroupsResults;

private CheckInTableRepository checkInTableRepository;
private LiveData<List<CheckInTable>> allCheckIn;
private MutableLiveData<List<CheckInTable>> searchCheckInResults;

public MainViewModel (Application application) {
super(application);

checkInRecipientsTableRepository = new CheckInRecipientsTableRepository(application);
allRecipients = checkInRecipientsTableRepository.getAllCheckInRecipients();
searchRecipientResults = checkInRecipientsTableRepository.getSearchRecipientResults();

checkInTableRepository = new CheckInTableRepository(application);
allCheckIn = checkInTableRepository.getAllCheckIn();
searchCheckInResults = checkInTableRepository.getSearchCheckInResults();

contactGroupsTableRepository = new ContactGroupsTableRepository(application);
allContactGroups = contactGroupsTableRepository.getAllContactGroups();
searchContactGroupsResults = contactGroupsTableRepository.getSearchContactGroupsResults();
}


MutableLiveData<List<CheckInRecipientsTable>> getSearchRecipientResults() {
return getSearchRecipientResults();
}
LiveData<List<CheckInRecipientsTable>> getAllCheckInRecipients() {
return getAllCheckInRecipients();
}

public void insertCheckInRecipientsTable(CheckInRecipientsTable checkInRecipientsTable) {
checkInRecipientsTableRepository.insertCheckInRecipientsTable(checkInRecipientsTable);
}
public void deleteCheckInRecipient(int checkInPrimaryKey) {
checkInRecipientsTableRepository.deleteCheckInRecipient(checkInPrimaryKey);
}
public void findCheckInRecipient(int checkInPrimaryKey) {
checkInRecipientsTableRepository.findCheckInRecipient(checkInPrimaryKey);
}


MutableLiveData<List<ContactGroupsTable>> getSearchContactGroupsResults() {
return getSearchContactGroupsResults();
}
LiveData<List<ContactGroupsTable>> getAllContactGroups() {
return getAllContactGroups();
}

public void insertContactGroupsTable(ContactGroupsTable contactGroupsTable) {
contactGroupsTableRepository.insertContactGroups(contactGroupsTable);
}
public void deleteContactGroups(int contactGroupsTablePrimaryKey) {
contactGroupsTableRepository.deleteContactGroups(contactGroupsTablePrimaryKey);
}
public void findContactGroups(int contactGroupsTablePrimaryKey) {
contactGroupsTableRepository.findContactGroups(contactGroupsTablePrimaryKey);
}

MutableLiveData<List<CheckInTable>> getSearchCheckInResults() {
return getSearchCheckInResults();
}
LiveData<List<CheckInTable>> getAllCheckIn() {
return getAllCheckIn();
}

public void insertCheckInTable(CheckInTable checkInTable) {
checkInTableRepository.insertCheckIn(checkInTable);
}
public void deleteCheckIn(int checkInTablePrimaryKey) {
checkInTableRepository.deleteCheckIn(checkInTablePrimaryKey);
}
public void findCheckIn(int checkInTablePrimaryKey) {
checkInTableRepository.findCheckIn(checkInTablePrimaryKey);
}
}

最佳答案

您将需要创建一个 ViewModelFactory,一个实现 ViewModelProvider.Factory 的类,因为您的 ViewModel 不使用默认的无参数构造函数。您可以修改this并将 UserDataSource 替换为 Application

在 Fragment 中创建 ViewModelFactory 对象后(理想情况下您应该执行此 onAttachonCreate 操作),替换

mViewModel = new ViewModelProvider(this).get(MainViewModel.class);

mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);

关于java - ViewModelProviders 弃用的正确替代方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59810645/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com