簡體   English   中英

在 kotlin 中編譯時出現未解析的引用

[英]I am getting Unresolved Reference when compiling in kotlin

我是 kotlin 新手,編譯時收到未解析的引用
它無法引用我的課程,這里有兩個課程。

這是我的Activity

房間活動.kt

class RoomActivity : AppCompatActivity() {

val NEW_WORD_ACTIVITY_REQUEST_CODE = 1

//    private var mWordViewModel: WordViewModel? = null
private var mWordViewModel: WordViewModel?=null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_room)

    val toolbar = findViewById<Toolbar>(R.id.toolbar)
    setSupportActionBar(toolbar)

    val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
    val adapter = WordListAdapter(this)
    recyclerView.adapter = adapter
    recyclerView.layoutManager = LinearLayoutManager(this)

    // Get a new or existing ViewModel from the ViewModelProvider.
    mWordViewModel = ViewModelProviders.of(this).get(WordViewModel::class.java)

    // Add an observer on the LiveData returned by getAlphabetizedWords.
    // The onChanged() method fires when the observed data changes and the activity is
    // in the foreground.
    mWordViewModel!!.allWords.observe(this, Observer<List<Word>> {
        adapter.setWords(Word)
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    })

    val fab = findViewById<FloatingActionButton>(R.id.fab)
    fab.setOnClickListener(object : View.OnClickListener {
        override fun onClick(view: View) {
            val intent = Intent(this@RoomActivity, NewWordActivity::class.java)
            startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE)
        }
    })
}

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        val word = Word(data!!.getStringExtra(NewWordActivity.EXTRA_REPLY))
        mWordViewModel!!.insert(word)
    } else {
        Toast.makeText(
                applicationContext,
                R.string.empty_not_saved,
                Toast.LENGTH_LONG).show()
    }
}

}

這是我的ViewModel

WordViewModel.kt

class WordViewModel(application: Application) : AndroidViewModel(application) {

private var parentJob = Job()
private val coroutineContext: CoroutineContext
    get() = parentJob + Dispatchers.Main
private val scope = CoroutineScope(coroutineContext)

private val repository: WordRepository
val allWords: LiveData<List<Word>>

init {
    val wordsDao = WordRoomDatabase.getDatabase(application)?.wordDao()
    repository = WordRepository(wordsDao!!)
    allWords = repository.allWords
}

fun insert(word: Word) = scope.launch(Dispatchers.IO) {
    repository.insert(word)
}

override fun onCleared() {
    super.onCleared()
    parentJob.cancel()
}
}

有什么問題請幫幫我。

如果您從另一個項目復制了文件WordViewModel.kt ,請確保將第一行中的程序包名稱更改為您在項目中使用的名稱。

package application.hdlakhani.com.myapplication

AndroidViewModel-當您需要上下文時使用該類,而在其他情況下則使用ViewModel()類。 如果您使用的是androidviewmodel或viewmodel,則以下代碼均有效。

class UserViewModel : ViewModel() {

lateinit var userList: LiveData<PagedList<User>>

private val compositeDisposable = CompositeDisposable()

private val pageSize = 10

lateinit var sourceFactory: UsersDataSourceFactory

lateinit var productList:LiveData<PagedList<ProductsItem>>
var tDataSource: LiveData<ProductListSource>? = null

lateinit var productListSource:ProductDataSourceFactory

var networkState: LiveData<NetworkState>? = null
var productData: LiveData<Product>? = null
fun init(apiListener: ApiListener) {
    sourceFactory = UsersDataSourceFactory(compositeDisposable, apiListener)
    val config = PagedList.Config.Builder()
            .setPageSize(pageSize)
            .setEnablePlaceholders(false)
            .build()
    userList = LivePagedListBuilder<Long, User>(sourceFactory, config).build()
}
fun getProductData(apiListener: ApiListener){
    productListSource= ProductDataSourceFactory(apiListener)
    tDataSource = productListSource.mutableLiveData
    networkState = Transformations.switchMap(productListSource.mutableLiveData) { dataSource -> dataSource.networkState }
    productData = Transformations.switchMap(productListSource.mutableLiveData) { dataSource -> dataSource.productList }

    val config=PagedList.Config.Builder()
            .setInitialLoadSizeHint(5)
            .setPageSize(pageSize)
            .setEnablePlaceholders(false)
            .build()
    productList=LivePagedListBuilder<Long,ProductsItem>(productListSource,config).build()
}
override fun onCleared() {
    super.onCleared()
    compositeDisposable.dispose()
}
fun retryGetProduct() {
    productListSource.mutableLiveData.value!!.retry()
}

fun retry() {
    sourceFactory.usersDataSourceLiveData.value!!.retry()
}

fun refresh() {
    sourceFactory.usersDataSourceLiveData.value!!.invalidate()
}

/ *好玩的getNetworkStateData():LiveData = Transformations.switchMap(productListSource.mutableLiveData,{it.networkState})

fun getNetworkState(): LiveData<NetworkState> = Transformations.switchMap<UsersDataSource, NetworkState>(
        sourceFactory.usersDataSourceLiveData, { it.networkState })

fun getRefreshState(): LiveData<NetworkState> = Transformations.switchMap<UsersDataSource, NetworkState>(
        sourceFactory.usersDataSourceLiveData, { it.initialLoad })*/

}

這樣訪問..

 viewModel = ViewModelProviders.of(this).get(UserViewModel::class.java)

您的回答為時已晚,但我認為這會對某人有所幫助。 我今天遇到了同樣的問題,我通過重建我的項目來解決它。 只需轉到: Build -> Rebuild Project

圖片

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM