gpt4 book ai didi

android - java.lang.RuntimeException : Cannot create an instance of ViewModel class 错误

转载 作者:行者123 更新时间:2023-11-29 16:28:51 34 4
gpt4 key购买 nike

我正在尝试在我的 Activity 中实例化 UserViewModel,但它一直给我一个 java.lang.RuntimeException: Cannot create an instance of viewmodel class 请协助。

这就是我的 ViewModel 的样子

public class UserViewModel extends AndroidViewModel {

private NodeAuthService api;
private SharedPreferences pref;
private static MutableLiveData<List<User>> userDetails = new MutableLiveData<>();

public UserViewModel(@NonNull Application application) {
super(application);
api = AuthRetrofitClient.getInstance().create(NodeAuthService.class);
}


private String email = pref.getString("email", "");

public void loadUser(){
Call<List<User>> call;
call = api.getUser(email);
call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
userDetails.postValue(response.body());

}

@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.d("USER",t.getMessage());
}
});

}

public MutableLiveData<List<User>>getUserDetails(){
return userDetails;
}
}

我的 Activity 是这样设置的

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

userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);

userViewModel.loadUser();

userViewModel.getUserDetails().observe(this, new Observer<List<User>>() {
@Override
public void onChanged(List<User> users) {
if (users != null){
for (int i = 0; i<users.size(); i++){
nameVm = String.valueOf(users.get(0));
}
}
}
});

}

最佳答案

创建 ViewModelFactory 类

public class MyViewModelFactory implements ViewModelProvider.Factory {
private Application mApplication;
public MyViewModelFactory(Application application) {
mApplication = application;
}

@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
// Replace UserViewModel → with whatever or however you create your ViewModel
return (T) new UserViewModel(mApplication);
}
}

和初始化 ViewModel 一样

UserViewModel myViewModel = ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication())).get(UserViewModel.class);

关于android - java.lang.RuntimeException : Cannot create an instance of ViewModel class 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58185863/

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