I have a simple app that contains a TextView and stores data in a room database When the database contains information, the data is displayed in the text view
problem When I read the data from the room database and show the first time in the text view with the ViewModel that the database is empty for the first time, the application crashes! I have tested it with Recyclerview, well the recyclerview was empty
Question Why does the program not show the empty text view and it crashes, but this is not the case in Recycler View? How can I show the data in the text view?
my code in fragment
class HomeFragment : Fragment() {
private lateinit var viewModel: MyViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(this)[MyViewModel::class.java]
viewModel.getAllDataObservers().observe(viewLifecycleOwner){
//textview for show data
txt_show_number.text = it[0].question_number
txt_show_question.text = it[0].question
}
}
}
ViewModel
class MyViewModel(application: Application) : AndroidViewModel(application) {
var allUsers: MutableLiveData<List<EntityStudent>> = MutableLiveData()
fun getAllDataObservers(): MutableLiveData<List<EntityStudent>> {
getAllData()
return allUsers
}
fun getAllData() {
val dao = RoomDb.getAppDatabase((getApplication()))?.mainDao()
val list = dao?.getAllData()
allUsers.postValue(list!!)
}
fun insert(entityStudent: EntityStudent) {
val dao = RoomDb.getAppDatabase((getApplication()))?.mainDao()
val list = dao?.insert(entityStudent)
getAllData()
} }
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student, PID: 2679
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.student.HomeFragment.onViewCreated$lambda-0(HomeFragment.kt:32)
at com.example.student.HomeFragment.$r8$lambda$kFVd0uSVK9JwnEU47m0mSdTzXmo(Unknown Source:0)
at com.example.student.HomeFragment$$ExternalSyntheticLambda0.onChanged(Unknown Source:4)
line 32 is : txt_show_number.text = it[0].question_number