我是 MVVM 新手。因此,我的片段/活动向服务器发出了 2 个请求,第一个请求的结果将用作第二个请求的输入参数。
因此,首先在我的片段中,当单击按钮时,我会发出请求以检查用户是否被禁止,如果没有,则该用户可以创建帖子。
所以首先我检查用户是否被禁止或没有在我的片段中使用此代码
class CreateEventFragment : Fragment() {
lateinit var model: CreateEventViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
model = ViewModelProvider(this).get(CreateEventViewModel::class.java)
button.setOnClickListener {
model.checkIfUserIsBanned()
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是视图模型
class CreateEventViewModel(application: Application) : AndroidViewModel(application) {
val mUserIsBanned :MutableLiveData<Boolean> = UserClient.mUserIsBanned
fun checkIfUserIsBanned(userID: String) {
UserRepository.checkIfUserIsBanned(id)
}
}
Run Code Online (Sandbox Code Playgroud)
这是客户端(为了简单起见,我跳过了存储库)
object UserClient {
val mUserIsBanned = MutableLiveData<Boolean>()
fun checkIfUserIsBanned(userID: String) {
// perform networking, after getting the value then
if (user.isBanned) {
mUserIsBanned.postValue(true) …Run Code Online (Sandbox Code Playgroud) android kotlin android-livedata android-viewmodel android-architecture-components
我正在使用导航组件,我有Fragment A和Fragment B,从Fragment A我使用安全参数将一个对象发送到Fragment B并导航到它。
override fun onSelectableItemClick(position:Int,product:Product) {
val action = StoreFragmentDirections.actionNavigationStoreToOptionsSelectFragment(product,position)
findNavController().navigate(action)
}
Run Code Online (Sandbox Code Playgroud)
现在,在我的Fragment B中进行一些逻辑之后,我想再次将该数据传递给我使用的Fragment A
btn_add_to_cart.setOnClickListener {button ->
findNavController().previousBackStackEntry?.savedStateHandle?.set("optionList",Pair(result,product_position))
findNavController().popBackStack()
}
Run Code Online (Sandbox Code Playgroud)
然后在片段 A中,我用
findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Pair<MutableList<ProductOptions>,Int>>("optionList")
?.observe(viewLifecycleOwner, Observer {
storeAdapter.updateProductOptions(it.second,it.first)
})
Run Code Online (Sandbox Code Playgroud)
现在,这工作正常,但如果我从片段 A转到片段 B并按后退按钮,上面的观察者会再次触发,复制我当前的数据,有没有办法在我只按下片段btn_add_to_cart中的按钮时触发该观察者乙?
android android-fragments kotlin android-viewmodel android-architecture-navigation
我试图从我的 .ROOM 数据库中观察所有练习名称的列表AlertDialog。
但是我收到以下错误消息:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.Application android.app.Activity.getApplication()' on a null object reference
错误消息出现在这里:
childExerciseViewModel = ViewModelProviders.of((FragmentActivity) context).get(ChildExerciseViewModel.class);
Run Code Online (Sandbox Code Playgroud)
我怎样才能避免这个错误?
添加练习对话框
public class AddExerciseDialog extends AppCompatDialogFragment {
private EditText editTextExerciseName;
private ChildExerciseViewModel childExerciseViewModel;
String userEnteredExerciseName;
int exerciseTypeID;
Button cancelBtn;
Button addBtn;
Context context;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
childExerciseViewModel = ViewModelProviders.of((FragmentActivity) context).get(ChildExerciseViewModel.class);
//return view;
return inflater.inflate(R.layout.layout_dialog_add_exercise, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable …Run Code Online (Sandbox Code Playgroud) java android android-alertdialog android-livedata android-viewmodel
我已经尝试了我能找到的所有咒语,但在使用 viewModel 时仍然遇到问题。
这是有问题的代码:
class MainActivity: FlutterActivity(), OnSneakerClickListener, OnSneakerDismissListener {
private val httpclient = OkHttpClient()
val stripe = Stripe(this, "pk_test_yadayadayada")
private val viewModel: StripeIntentViewModel by viewModels() //<--dragons be here
Run Code Online (Sandbox Code Playgroud)
当我手动输入“import androidx.activity.viewModels”时,它会将其显示为“未使用的导入指令”。
我的模块 build.gradle 文件如下所示:
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'checkstyle'
id 'org.jetbrains.kotlin.plugin.parcelize'
}
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
...
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$androidLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$androidLifecycleVersion"
implementation "com.google.android.material:material:$materialVersion"
implementation "androidx.fragment:fragment-ktx:$fragmentVersion"
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation "androidx.activity:activity-ktx:1.1.0"
implementation "androidx.fragment:fragment-ktx:1.2.5"
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.activity:activity-ktx:1.2.0-rc01" …Run Code Online (Sandbox Code Playgroud) 我收到这个错误。我在同一个 ViewModel 类文件中创建了 ViewModelFactory 类。当我尝试初始化视图模型时,出现此错误。
//Code written in fragment class in onCreateView after binding code//
homeViewModelFactory = HomeViewModelFactory((requireActivity().application as Application).repository)
homeViewModel = ViewModelProvider(this, homeViewModelFactory)
.get(HomeViewModel::class.java)
//Viewmodelfactoryclass//
class HomeViewModelFactory(private val homeRepository: HomeRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(HomeViewModel::class.java)) {
return HomeViewModelFactory(homeRepository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
Run Code Online (Sandbox Code Playgroud) 我想将一个项目添加到 a Listof MutableLiveDatain中ViewModel。
List是read-only因为它是用初始化的listOf()。
但在特定情况下我想添加一个项目。
我以前是这样做的toMutableList(),type cast但是调试的结果是没有任何List变化LiveData。
如何将数据应用到Lista LiveData?
class WriteRoutineViewModel : ViewModel() {
private var _items: MutableLiveData<List<RoutineModel>> = MutableLiveData(listOf())
val items: LiveData<List<RoutineModel>> = _items
fun addRoutine(workout: String) {
val item = RoutineModel(workout, "TEST")
_items.value?.toMutableList()?.add(item) // nothing change
}
}
Run Code Online (Sandbox Code Playgroud) 我按照下一页中的说明创建了一个 viewModel,但当SavedStateHandle我关闭应用程序并再次打开它时,它不起作用。
这是页面:
这是我的视图模型类:
class UserViewModel(private val state : SavedStateHandle) : ViewModel(){
val userId: LiveData<String> by lazy {
state.getLiveData("userId")
}
fun setUserId(userId : String) {
state["userId"] = userId
}
val user : User by lazy {
User("")
} }
Run Code Online (Sandbox Code Playgroud)
以下是我在活动中使用 viewModel 的方式。
val userViewModel : UserViewModel by viewModels()
Run Code Online (Sandbox Code Playgroud)
我什至在我的活动中尝试过这个,但这也不起作用!
val userViewModel: UserViewModel by viewModels {
SavedStateViewModelFactory(
application,
this
)
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能将数据持久化SavedStateHandle?我的意思是,打开应用程序后state仍然是空的。
我试图在两个地方获取视图模型,其中一个在 MainActivity 中使用:
val viewModel:MyViewModel by viewModels()
Run Code Online (Sandbox Code Playgroud)
另一个地方是在 compose 函数内部,使用:
val viewModel:MyViewModel = hiltViewModel()
Run Code Online (Sandbox Code Playgroud)
当我调试时,似乎那是两个不同的对象。无论如何,我可以在两个地方获得相同的对象吗?
android android-viewmodel android-jetpack-compose dagger-hilt
我遇到了访问视图模型的问题。
我有一个活动和其中的 2 个片段。我有一个活动和片段的视图模型,使用在主机活动中创建的视图模型的相同实例。
class MyViewModel(var paymentDataModel: PaymentDataModel) : ViewModel(){
fun someMethod():Boolean{
//return Something
}
}
class MyViewModelFactory(var paymentDataModel: PaymentDataModel) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return MyViewModel(paymentDataModel) as T
}
}
class NewPaymentAmountFragment : Fragment() {
private val paymentViewModel: MyViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if(paymentViewModel.someMehtod()){
//Accessing activity viewmodel in fragment
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在活动函数中使用 viewModel 扩展定义 viewmodel,则会出现以下错误。
导致:java.lang.RuntimeException:无法创建类 com.app.MyViewModel 的实例
class MyActivity : BaseActivity(){
val myViewModel: …Run Code Online (Sandbox Code Playgroud) 我是android体系结构组件的新手,我对它一点也不困惑viewmodel。我正在构建一个从服务器获取项目列表并在布局中显示为列表的应用程序。我已经在Repository课堂上实现了网络通话。
Repository.java:
//Get list of top rated movies
public LiveData<NetworkResponse> getTopRatedMovies() {
final MutableLiveData<NetworkResponse> result = new MutableLiveData<>();
ApiService api = retrofit.create(ApiService.class);
Call<MovieData> call = api.getTopRateMovies("api_key");
call.enqueue(new Callback<MovieData>() {
@Override
public void onResponse(Call<MovieData> call, Response<MovieData> response) {
result.postValue(new NetworkResponse(response.body()));
}
@Override
public void onFailure(Call<MovieData> call, Throwable t) {
Log.e(TAG, t.getLocalizedMessage());
result.postValue(new NetworkResponse(t));
}
});
return result;
}
Run Code Online (Sandbox Code Playgroud)
现在在ViewModel课堂上我正在这样做:
public class MovieListViewModel extends ViewModel {
public LiveData<NetworkResponse> result, topRatedMovies;
public LiveData<List<MovieEntity>> favoriteMovies;
private Repository repository; …Run Code Online (Sandbox Code Playgroud) android android-livedata android-viewmodel android-architecture-components android-jetpack
android ×9
kotlin ×6
android-architecture-components ×2
android-architecture-navigation ×1
android-mvvm ×1
dagger-hilt ×1
java ×1
mvvm ×1
repository ×1
viewmodel ×1