DialogFragment中的ViewModel

时间:2019-12-06 12:15:18

标签: android mvvm viewmodel android-room android-livedata

我正在尝试更改此类以与我的房间查询配合使用

@Query("select * from customer_contacts where serverCustomerId = :id and contactName like '%' || :name || '%'")
fun fetchCustomerContactsByName(id:Int, name:String): LiveData<List<CustomerContact>>

和我的视图模型

class CustomerContactVM : ViewModel() {
var customers: LiveData<List<CustomerContact>> = MutableLiveData<List<CustomerContact>>()

fun getCustomerContacts(id: Int, name: String) {
    customers = CustomerContactDao().fetchCustomerContactsByName(id, name)
}
}

我不明白如何在对话框片段中创建视图模型,因为我一直无法解决尝试使用ViewModelProviders.of(this).get(CustomerContactVM.class)的错误

public class CustomerContactListFragment extends DialogFragment {

private CustomerContactVM customerContactVM;

@Override
public void onStart() {
    super.onStart();
    //setEmptyText("No Items");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    if (savedInstanceState != null) { mCustomer = savedInstanceState.getString(ARG_CUSTOMER);
        if (savedInstanceState.getString(ARG_QUERY) != null) {
            mQuery = savedInstanceState.getString(ARG_QUERY);
        }
    }

    GlobalState globalState = (GlobalState) getActivity().getApplication();
   // mState.addScreenLog("CustomerContactListFragment");

    return inflater.inflate(R.layout.fragment_catalogue_items, container, false);
}
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

@Override
public void onDetach() {
    dbHelper.close();
    super.onDetach();
}


}

1 个答案:

答案 0 :(得分:0)

ViewModelProviders.of(此)已弃用。因此,您应该使用生命周期组件的最新版本。

     implementation "androidx.lifecycle:lifecycle-extensions:2.2.0-rc03"

     //for kotlin
     implementation "group: 'androidx.lifecycle', name:'lifecycle-viewmodel-ktx', version:2.2.0-rc03"
     kapt "androidx.lifecycle:lifecycle-compiler:2.2.0-rc03"

ViewModel初始化(Java):

private CustomerContactVM customerContactVM;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   customerContactVM = ViewModelProvider(this).get(CustomerContactVM.class);
   // Other setup code below...
}

ViewModel初始化(Kotlin):

var customerContactVM:CustomerContactVM? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    customerContactVM = ViewModelProvider(this).get(CustomerContactVM::class.java)
    // Other setup code below...
    }