У меня следующая ошибка при попытке создать проект с MVVM и привязкой данных. Я просмотрел все, что смог найти здесь, в StackOverflow, или распространенные ошибки в inte rnet, но в моем случае ничего не помогло.
Единственное сообщение, которое я получаю, - это ошибка. Это выглядит так в buildOutput
:
I've had my packages named with capital letters and I've found here that this might be the cause because compiler treat them as names of classes, so I've changed them all to start with small letters, but that haven't helped.
I've created ViewModelFactory
for creating my ViewModel
inside Activity
so I could send additional parameters with constructor using factory, so I've tried to remove it and use no parameters and create instance without using factory for this purpose, but still I havn't got any results (same error)
I was chaning both build.gradle
's in different ways but result was always the same.
Finally I've deleted data binding and variable from XML, then I was able to run the app (with other errors, but I would be probably able to deal with those by myself) but I want to leave it as it is and just deal with my error.
I am not experienced with MVVM and data binding so it can be just a stupid mistake, but it is hard to find it if I don't know where I should look for it.
Here I post most important codes, if you need more then let me know:
build.grale(app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 30
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.rickmorty"
minSdkVersion 24
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures{
dataBinding = true
viewBinding = true
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.1'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.3.0-alpha02'
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "androidx.cardview:cardview:1.0.0"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.7'
implementation 'com.github.bumptech.glide:glide:4.6.1'
kapt 'com.github.bumptech.glide:compiler:4.4.0'
}
**build.gradle(project)
buildscript {
ext.kotlin_version = "1.3.72"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
MainActivity
class MainActivity : AppCompatActivity() {
lateinit var mainViewModel: MainViewModel
lateinit var mAdapter: CharactersAdapter
lateinit var api: CharacterAPI
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retrofit = RetrofitClient.instance
api = retrofit.create(CharacterAPI::class.java)
setupViewModel()
setupRecycler()
mainViewModel.getData().observe(this,
Observer> { t ->
mAdapter = CharactersAdapter(this@MainActivity, t!!)
rvCharacters.adapter = mAdapter
})
}
fun setupRecycler() {
val lManager = LinearLayoutManager(this@MainActivity)
rvCharacters.apply {
setHasFixedSize(true)
layoutManager = lManager
}
rvCharacters.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val visibleItems = lManager.childCount
val totalItems = lManager.itemCount
val firstVisible = lManager.findFirstVisibleItemPosition()
if (dy > 0) {
if (!mainViewModel.isLoading.value!! && (visibleItems + firstVisible) >= totalItems) {
mainViewModel.scrolledNext()
}
} else {
if (!mainViewModel.isLoading.value!! && (totalItems - visibleItems) <= 0) {
mainViewModel.scrolledPrev()
}
}
}
})
}
fun setupViewModel() {
mainViewModel = ViewModelProviders.of(this, MainViewModelFactory(application, api))
.get(MainViewModel::class.java)
DataBindingUtil.setContentView<ActivityMainBinding>(
this, R.layout.activity_main
).apply {
lifecycleOwner = this@MainActivity
viewmodel = mainViewModel
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
Как я уже писал ранее, после удаления variable
из XML и привязки из MainActivity
ошибка пропадает. Я знаю, что это много кода, поэтому, если что-то излишне, просто дайте мне знать. Класс factory все еще отсутствует, но я отправлю его, если это необходимо. Также MainRepo
- это тот, который я сюда не прикреплял, но он довольно длинный, но я могу опубликовать его все, если он вам понадобится.