简体   繁体   English

Android体系结构组件:ViewModel在配置更改时返回null

[英]Android Architecture components: ViewModel returns null on configuration change

I`m developing a gallery app in kotlin using pixabay api, implementing Android Architecture components and retrofit to interact with the server. 我正在使用Foto api在Kotlin开发图库应用程序,实现Android Architecture组件并进行改进以与服务器进行交互。 the app works fine but when i change the configuration the view model returns null! 该应用程序工作正常,但是当我更改配置时,视图模型返回null! what is the problem ? 问题是什么 ?

interface PhotoApi {
    @GET(context.getString(R.string.api_key))
    fun getPhotos(): Call<PhotoList>
}

Retrofit setup 改造设置

object PhotoRetriever {
    val BASE_URL = "https://pixabay.com/api/"
    val service: PhotoApi

    init {
        val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create()).build()
        service = retrofit.create(PhotoApi::class.java)
    }

}

class MainActivity : AppCompatActivity() {
    //var photoList: List<Photo>? = null
    lateinit var viewModel: MainActivityViewModel

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

        viewModel = ViewModelProviders.of(this@MainActivity).get(MainActivityViewModel::class.java)
        viewModel.getList().observe(this, object :Observer<List<Photo>> {
            override fun onChanged(t: List<Photo>?) {
                    textview.setText(t?.get(1)?.webFormatUrl)
            }
        })

the view model class 视图模型类

class MainActivityViewModel : ViewModel() {

    private val repository: Repository
    lateinit var photoList: LiveData<List<Photo>>
    val itemsListObservable: MediatorLiveData<List<Photo>>


    init {
        repository = Repository()
        itemsListObservable = MediatorLiveData()
    }

    fun getList(): LiveData<List<Photo>> {

       photoList = repository.getNetworkData()
        Log.i("RECEIVED","size is ${photoList.value?.size} from viewModel ")
        return photoList
    }
}

the Repository class 存储库类

class Repository {
    val photoApi: PhotoApi
    var photoList: List<Photo>?
    val retlist = MutableLiveData<List<Photo>>()

    init {
        photoApi = PhotoRetriever.service
        photoList = ArrayList<Photo>()
    }

    fun getItemsListFromWeb() {
        photoApi.getPhotos().enqueue(object : Callback<PhotoList> {
            override fun onFailure(call: Call<PhotoList>?, t: Throwable?) {
                // Log.i("RECEIVED","${t?.message} from repository ")
                // retlist.value = null
            }

            override fun onResponse(call: Call<PhotoList>?, response: Response<PhotoList>?) {
                if (response!!.isSuccessful) {
                    retlist.value = response.body()?.hits
                } else {
                    retlist.value = null
                }
                Log.i("RECEIVED", "size is ${retlist.value?.size} from repository ")
            }

        })

    }

    fun getNetworkData(): LiveData<List<Photo>> {
        getItemsListFromWeb()
        return retlist
    }

}

i have solved the problem, the problem was in retrofit onResponse callback method i remove the else block and everything works fine 我已经解决了问题,问题出在onResponse回调方法的改进上,我删除了else块,一切正常

before 之前

 override fun onResponse(call: Call<PhotoList>?, response: Response<PhotoList>?) {
                if (response!!.isSuccessful) {
                    retlist.value = response.body()?.hits
                } else {
                    retlist.value = null
                }
                Log.i("RECEIVED", "size is ${retlist.value?.size} from repository ")
            }

after

 override fun onResponse(call: Call<PhotoList>?, response: Response<PhotoList>?) {
                    if (response!!.isSuccessful) {
                        retlist.value = response.body()?.hits
                    } 
                    Log.i("RECEIVED", "size is ${retlist.value?.size} from repository ")
                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android架构组件ViewModel上下文 - Android Architecture Components ViewModel Context Android架构组件:绑定到ViewModel - Android Architecture Components: bind to ViewModel Android架构组件ViewModel上下文问题 - Android Architecture Components ViewModel context issue Android架构组件:使用ViewModel for RecyclerView项目 - Android Architecture Components: using ViewModel for RecyclerView items Android架构组件ViewModel - 与Service / IntentService的通信 - Android Architecture Components ViewModel - communication with Service/IntentService Android架构组件 - ViewModel Observable和Proguard - Android Architecture Components - ViewModel Observable & Proguard ViewModel 实例 - Activity UI - Android 架构组件 - ViewModel instance - Activity UI - Android Architecture Components Android体系结构组件室ViewModel CompleteableFormAction - Android Architecture Components Room ViewModel CompleteableFormAction Android 生命周期感知组件如何检测 ViewModel 中的配置更改 - Android How Lifecycle-Aware Components Detect Configuration Change inside ViewModel Android MVVM + 数据绑定 + 架构组件(ViewModel 和 Room)示例 - Example of Android MVVM + Databinding + Architecture Components (ViewModel and Room)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM