Search code examples
javaandroidandroid-roomandroid-livedataandroid-viewmodel

ViewModel in DialogFragment


I am trying to change this class to work with my room query

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

and my view model

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

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

I dont understand how to create the viewmodel in the dialog fragment as I keep getting cannot resolve errors trying 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();
}


}

Solution

  • ViewModelProviders.of (this) is deprecated. So you should use the latest version of lifecycle components.

         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 initizalition (Java):

    private CustomerContactVM customerContactVM;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
    
       customerContactVM = ViewModelProvider(this).get(CustomerContactVM.class);
       // Other setup code below...
    }
    

    ViewModel initizalition (Kotlin):

    var customerContactVM:CustomerContactVM? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        customerContactVM = ViewModelProvider(this).get(CustomerContactVM::class.java)
        // Other setup code below...
        }