我在这个网站上研究了这个问题,发现了几个类似的问题。我尝试了提供的所有建议,但显然,我的实施或我对解释的理解导致这些解决方案不起作用。我希望获得有关如何解决此问题的指导。
我的项目由以下 ViewModel 组成:
public SelectList MonthList { get; set; }
public SelectList ReverseMonthsLists()
{
var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });
for (int i = 1; i < stringViewOfDates.Count(); i++)
{
list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
}
var selectList = new SelectList(list);
return selectList;
}
public static IEnumerable<DateTime> GetDates()
{
DateTime startDate = …Run Code Online (Sandbox Code Playgroud) 我有一个继承自 ViewModelBase 的 ViewModel。目前我在 ViewModel 中调用我的服务,如下所示:
private void Login(string _username, string _password)
{
Task.Run(async () =>
{
var isLoginSuccess = await _authenticationDataService.Login(_username, _password);
if (isLoginSuccess == true) { }
});
}
Run Code Online (Sandbox Code Playgroud)
在我的 AuthenticarionService 中,它看起来像这样:
public async Task<bool> Login(string username, string password)
{
Token = await GetAPIToken(username, password);
return true;
}
private static async Task<string> GetAPIToken(string userName, string password)
{
//Blah blah blah wont bore you with the detail
}
Run Code Online (Sandbox Code Playgroud)
现在我想要的是在我的 ViewModelBase 中放置一个通用的 Task 方法,它将运行我传递给它的任何“awaitables”并返回一个通用结果(我可以在我的视图模型中正确地转换结果)。
这样我就可以做这样的事情:
private void Login(string _username, string …Run Code Online (Sandbox Code Playgroud) 这是我的依赖项:
//Room and Lifecycle Libraries
kapt "androidx.room:room-compiler:2.2.0-alpha02"
kapt 'androidx.room:room-compiler:2.2.0-alpha02'
kapt "androidx.lifecycle:lifecycle-compiler:2.2.0-alpha03"
implementation "androidx.room:room-runtime:2.2.0-alpha02"
implementation 'androidx.room:room-runtime:2.2.0-alpha02'
implementation "androidx.lifecycle:lifecycle-viewmodel:2.2.0-alpha03"
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0-alpha03"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha03"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha03"
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
Run Code Online (Sandbox Code Playgroud)
如您所见,我实现了最终版本,但我无法访问 liveData 构建器。我怎样才能解决这个问题?
我喜欢使用 mvvm 从片段获取传感器数据(例如陀螺仪)。到目前为止,我已经让它工作了,但只是在一个片段中,完全围绕 mvvm 环境工作。它不适用于视图模型文件。如何将传感器数据传输到 LiveData 中?
这是工作代码,但绕过了视图模型:
class RPMFragment : Fragment(), SensorEventListener {
private lateinit var rpmViewModel: RPMViewModel
private lateinit var sensorManager: SensorManager
private lateinit var gyroscope: Sensor
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rpmViewModel = ViewModelProviders.of(this).get(RPMViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_rpm, container, false)
val textView: TextView = text_rpm
rpmViewModel.text.observe(this, Observer {
textView.text = it
})
this.sensorManager = activity!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)?.let {
this.gyroscope = it
}
return root
}
override fun onSensorChanged(event: SensorEvent?) {
if …Run Code Online (Sandbox Code Playgroud) I have just created a demo project for learning and the MVVM and how to use the Mvvm in our project. but I have found an error while running the project
error: cannot find symbol class ViewModel
error: package ViewModel does not exist
error: package ViewModel does not exist
error: package ViewModel does not exist
and here is my code
public class User extends BaseObservable {
String email,password;
boolean isDataValidate;
public String getEmail() {
return email;
}
public void setEmail(String …Run Code Online (Sandbox Code Playgroud) 我需要更改 ViewModel 中 MutableLiveData 的值,但我无法做到这一点,因为该值等于 null,我认为需要建立一个观察者在其中更改它,但我不知道该怎么做,并且这是否是一个好主意。
录音机列表视图模型
class AudioRecordersListViewModel() : ViewModel() {
var audioRecordsLiveData: MutableLiveData<MutableList<AudioRecordUI>> = MutableLiveData();
private var audioRecordDao: AudioRecordDao? = null
@Inject
constructor(audioRecordDao: AudioRecordDao) : this() {
this.audioRecordDao = audioRecordDao
viewModelScope.launch {
val liveDataItems = audioRecordDao
.getAll().value!!.map { item -> AudioRecordUI(item) }
.toMutableList()
if (liveDataItems.size > 0) {
liveDataItems[0].isActive = true
}
audioRecordsLiveData.postValue(liveDataItems)
}
}
}
Run Code Online (Sandbox Code Playgroud)
录音道
@Dao
interface AudioRecordDao {
@Query("SELECT * FROM AudioRecordEmpty")
fun getAll(): LiveData<MutableList<AudioRecordEmpty>>
}
Run Code Online (Sandbox Code Playgroud) 我正在使用ViewModel更新操作栏中的标题
共享视图模型
class SharedViewModel @ViewModelInject constructor(
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
val title: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
val backButton: MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>()
}
}
Run Code Online (Sandbox Code Playgroud)
主活动观察者
@AndroidEntryPoint
...
sharedViewModel.title.observe(this, Observer {
supportActionBar?.title = it
})
Run Code Online (Sandbox Code Playgroud)
使用下面的代码似乎创建了一个新实例Fragment(在调试器中检查):
@AndroidEntryPoint
...
private val viewModel: SharedViewModel by viewModels()
Run Code Online (Sandbox Code Playgroud)
但似乎以这种方式工作
val viewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
Run Code Online (Sandbox Code Playgroud)
这是应该这样做还是我做错了什么?
谢谢!
我的数据仅在创建时才获取...我使用视图模型...当按后退按钮时,它不会更新以前的数据..onresume 在此不起作用...
我引用了这个,但这些都没有帮助-->对 ViewModel 中的活动生命周期做出反应
我需要帮助
提前致谢
活动: -
class MyAccount : BaseClassActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.myaccount)
var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
setSupportActionBar(mActionBarToolbar);
setEnabledTitle()
val resetbutton=findViewById<Button>(R.id.resetpwd)
resetbutton.setOnClickListener {
val i=Intent(applicationContext,
ResetPasswordActivity::class.java)
startActivity(i)
}
val editbutton=findViewById<Button>(R.id.editdetail)
editbutton.setOnClickListener {
val i=Intent(applicationContext, EditProfile::class.java)
startActivity(i)
}
hello()
}
override fun onResume() {
super.onResume()
hello()
}
fun hello(){
val first_name = findViewById<TextView>(R.id.firstname)
val last_name = findViewById<TextView>(R.id.lastname)
val emailuser = findViewById<TextView>(R.id.emailuser)
val phone_no = findViewById<TextView>(R.id.phone_no)
val birthday = findViewById<TextView>(R.id.birthday)
val image=findViewById<ImageView>(R.id.imageprofile)
val …Run Code Online (Sandbox Code Playgroud) 我正在制作一个函数,当我触摸 recyclerView 项目时,该函数会打开一个对话框。我将 viewModel 放在适配器中,将 onClick 函数放在 viewHolder 中,以使用 viewModel 打开对话框。
\n看起来像这样。
\n Adapter(viewModel) // Initialize adapter in Activity or ViewModel
\xe2\x86\x93
\nclass Adapter(viewModel: ViewModel) : ViewModel() {\n inner class ViewHolder() {\n fun onClick(binding: RecyclerViewItemBinding) : RecyclerView.ViewHolder(binding.root) {\n Dialog(viewModel) // Open Dialog with viewModel\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n我可以在适配器或对话框中使用 ViewModel 吗?如果不能,我该怎么办?我需要通过从对话框接收更改后的值来更改 ViewModel 的数据。
\n我有一个带有 Fragment 的 Android Activity,让我们将其命名为MyFragment。
在 MyFragment 的onCreate() 中,我的 ViewModel 是这样的:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class);
}
Run Code Online (Sandbox Code Playgroud)
问题:
有时,当我将应用程序置于后台并导航到其他应用程序时,当我尝试打开此应用程序并将其带回前台时,应用程序会因以下错误而崩溃:
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.MyViewModel
...
at com.example.MyFragment.onCreate(MyFragment.java:64)
Run Code Online (Sandbox Code Playgroud)
其中第 64 行是这个:
myViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class);
Run Code Online (Sandbox Code Playgroud)
在查看了ViewModel 的官方文档后,我在代码片段中注意到,在所有 Fragment 中,ViewModel 是在onViewCreated()而不是onCreate() 中获得的。我将该更改应用于我的代码,并且我的应用程序不再因上述堆栈跟踪而崩溃。
问题:
在 Fragment 的onCreate() 中获取 ViewModel 是否有任何特殊原因可能导致应用程序崩溃,如果是,那么为什么在onViewCreated()上获取 ViewModel似乎可以解决此问题?
我们应该总是在onViewCreated()的 Fragment 中获取 ViewModel而不是onCreate() …
viewmodel ×10
android ×8
kotlin ×5
mvvm ×4
c# ×2
asp.net ×1
asp.net-mvc ×1
dagger ×1
dagger-hilt ×1
data-binding ×1
generics ×1
java ×1
lifecycle ×1
task ×1