我有一个从数据库检索数据的应用程序。下载数据时,屏幕上会出现进度条和文本,通知数据正在下载。下载数据后,文本和旋转图标消失。然而,在某些情况下,应用程序的行为并不完全正确。有时应用程序会冻结,有时进度条和文本会消失,但数据无法正确下载。我正确执行了代码吗? 微调器仅用于在活动开始时显示某些默认值。
这是存储库:
fun getAllZebra(): LiveData<List<Int>>{
return sybaseDao.getAllZebra()
}
这是视图模型:
@HiltViewModel
class ZebraViewModel @Inject constructor(
private val repository: SybaseRepository
):ViewModel(){
val skladnici = repository.getSkladnik().asLiveData()
fun getAllZebra(): LiveData<List<Int>>{
return repository.getAllZebra()
}
}
这就是活动
@AndroidEntryPoint
class ZebraActivity : AppCompatActivity() {
//private val viewModel : ZebraViewModel by viewModels()
var idZebra : Int = 0
var idExp: Int = 0
private val zebraViewModel: ZebraViewModel by viewModels()
private val spinner3 by lazy {findViewById<Spinner>(R.id.zebra_spinner)}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
SybaseApi.initilaizeBaseUrl(this)
val binding = ActivityZebraBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.apply {
zebraViewModel.skladnici.observe(this@ZebraActivity) { result ->
val skladnici: List<Skladnik>? = result.data
if (skladnici != null) {
Log.e("Skladnici", skladnici.size.toString())
}
else{
Log.e("Skladnici", "NULL")
}
progressBarLogin.isVisible =
result is Resource.Loading && result.data.isNullOrEmpty()
textViewProgressBar.isVisible =
result is Resource.Loading && result.data.isNullOrEmpty()
textViewProgressBar.text = "Loading data from database"
textViewErrorLogin.isVisible =
result is Resource.Error && result.data.isNullOrEmpty()
textViewErrorLogin.text = result.error?.localizedMessage
textViewErrorLogin.isVisible = result is Resource.Success
textViewErrorLogin.text = "Data uploaded:"
}
}
override fun onResume() {
super.onResume()
SybaseApi.initilaizeBaseUrl(this)
initSpinnerData()
}
private fun initSpinnerData(){
val allDevices = this?.let {
ArrayAdapter<Any>(it, R.layout.simple_item_spinner, R.id.tv_simple_item)
}
allDevices?.clear()
zebraViewModel.getAllZebra()
.observe(this, { devices ->
devices?.forEach{
allDevices?.getPosition(it)?.let { it1 -> if (it1 < 0) allDevices?.add(it) }
}
} )
spinner3.adapter = allDevices
spinner3.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onItemSelected(parent: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
if (parent != null) {
val idZebraString = parent.getItemAtPosition(position).toString()
idZebra = idZebraString.toInt()
}
}
override fun onNothingSelected(p0: AdapterView<*>?) {
Toast.makeText(this@ZebraActivity, "You need to choose some item", Toast.LENGTH_LONG).show() }
}
}
}
我认为问题不在于数据库,而在于视图,我看到您正在将 Spinner 与 ArrayAdapter 一起使用,您是否使用该数据通过 ArrayAdapter 为 Spinner 提供数据?如果是,您可以检查是否可以使用 RecyclerView.Adapter。