Я пытался создать приложение, в котором присутствует база данных, в которой хранится информация. В ней есть два столбца: name и roll_no . Есть два запроса: один на insert и другие, чтобы вернуть список информации
Но каждый раз, когда запускается, есть кра sh.
Я знаю, что вопрос немного длинный и простите я за это и предоставлю мне способ решить эту проблему.
info.kt
class info : Fragment() {
private var roll=0
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// val viewModel = ViewModelProviders.of(this).get(InfoViewModel::class.java)
val viewModel: InfoViewModel by activityViewModels()
val binding:InfoFragmentBinding= DataBindingUtil.inflate(inflater,R.layout.info_fragment,container,false)
fun updateRollNo():Int{
return roll+1
}
binding.add.setOnClickListener {
viewModel.onAdded(updateRollNo(),binding.name.toString())
//binding.database.text=viewModel.infoString.toString()
}
return binding.root
}
}
infoViewModel.kt
class InfoViewModel (
val database: InformationDatabaseDao, application: Application)
: AndroidViewModel(application) {
// TODO: Implement the ViewModel
/**
* viewModelJob allows us to cancel all coroutines started by this ViewModel.
*/
private var viewModelJob = Job()
/**All coroutines can be cancelled by viewmodelJob.cancel() and Dispatcher.main is byDefault choice
*/
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
private val currenctInfo = MutableLiveData<Information?>()
private val allInfo = database.getAllInfo()
val infoString = Transformations.map(allInfo){allInfo->
formatStrings(allInfo,application.resources)
}
init{
intializeThisInfo()
}
private fun intializeThisInfo(){
uiScope.launch {
currenctInfo.value=getFromDatabase()
}
}
private suspend fun getFromDatabase(): Information? {
return withContext(Dispatchers.IO){
val info =database.getThisInfo()
info
}
}
private suspend fun insert(thisInfo: Information) {
withContext(Dispatchers.IO) {
database.insert(thisInfo)
}
}
fun onAdded(roll_no: Int, name: String) {
uiScope.launch {
val thisInfo = Information(roll_no, name)
insert(thisInfo)
currenctInfo.value=getFromDatabase()
}
}
/**
* Called when the ViewModel is dismantled.
* At this point, we want to cancel all coroutines;
* otherwise we end up with processes that have nowhere to return to
* using memory and resources.
*/
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
}
База данных информации
@Database(entities =[Information::class],version=1)
abstract class InformationDatabase:RoomDatabase()
{
abstract fun InformationDatabaseDao():InformationDatabaseDao
companion object{
fun provideDatabase(context:Context):InformationDatabase{
return Room.databaseBuilder(context.applicationContext,InformationDatabase::class.java,"Information_databse").build()
}
}
}
Ниже представлен вывод терминала logcat
** ВЫХОД ТЕРМИНАЛА LOG CAT **
--------- beginning of crash
2020-04-01 14:38:38.731 3506-3506/com.example.exp6 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.exp6, PID: 3506
java.lang.RuntimeException: Cannot create an instance of class com.example.exp6.InformationFragment.InfoViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:269)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
at com.example.exp6.InformationFragment.info$onCreateView$2.onClick(info.kt:37)
at android.view.View.performClick(View.java:6600)
at android.view.View.performClickInternal(View.java:6577)
at android.view.View.access$3100(View.java:781)
at android.view.View$PerformClick.run(View.java:25912)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6923)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)
Caused by: java.lang.NoSuchMethodException: <init> [class android.app.Application]
at java.lang.Class.getConstructor0(Class.java:2327)
at java.lang.Class.getConstructor(Class.java:1725)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
at com.example.exp6.InformationFragment.info$onCreateView$2.onClick(info.kt:37)
at android.view.View.performClick(View.java:6600)
at android.view.View.performClickInternal(View.java:6577)
at android.view.View.access$3100(View.java:781)
at android.view.View$PerformClick.run(View.java:25912)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6923)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)
--------- beginning of the system