2

我的代码适用于视图模型,但是当我开始使用实时数据观察值时

model.d.observe(this, Observer<RespCategories> {
                r->resp=r
})

r inresp=r的类型从RespCategoriesto更改为RespCategories? 与寻呼机适配器的参数不匹配,因此我对其进行了一些更改,例如转换 var resp: RespCategories为, var resp: RespCategories? = null因此在观察r->resp=rresp 值为 null 时出现了一个新问题。如何解决问题?

kotlin.KotlinNullPointerException   at com.example.xyz.MainActivity.showData(MainActivity.kt:83)
                      at com.example.xyz.MainActivity$fetchData$1.onResponse(MainActivity.kt:65)

主要活动

class MainActivity : AppCompatActivity()
 {

    var userService: UserService = ApiUtils.getUserService()
    var dotscount: Int = 0
    lateinit var sliderDotspanel: LinearLayout
    lateinit var sectionPagerAdapter: SectionPagerAdapter
    lateinit var respCategories: RespCategories
    var resp: RespCategories? = null

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

        sliderDotspanel = findViewById(R.id.sliderdots)
        fetchData()


    }


    fun fetchData() {

        var call: Call<RespCategories>

        call = userService.getData()

        call.enqueue(object : Callback<RespCategories> {
            override fun onFailure(call: Call<RespCategories>, t: Throwable) {
                Toast.makeText(this@MainActivity, "fail", Toast.LENGTH_LONG).show()
            }

            override fun onResponse(call: Call<RespCategories>, response: Response<RespCategories>) {
                Toast.makeText(this@MainActivity, "success", Toast.LENGTH_LONG).show()
                respCategories = response.body()!!
                var dataGenerator:DataGenerator
                dataGenerator=DataGenerator()
                dataGenerator.addData(respCategories)
              //  DataGenerator.addData(respCategories)
                showData()
            }

        })

    }

    fun showData(){

        //var resp:RespCategories=DataGenerator.getData()
        val model=ViewModelProviders.of(this).get(DataGenerator::class.java)
       // var resp=model.getData()

        model.d.observe(this, Observer<RespCategories> {
                r->resp=r
        })

        if (viewPager != null) {

            sectionPagerAdapter = SectionPagerAdapter(supportFragmentManager, resp)
            viewPager.adapter = sectionPagerAdapter

            dotscount = sectionPagerAdapter.getCount()
            var dots: Array<ImageView?>? = null
            dots = arrayOfNulls(dotscount)

            for (i in 0 until dotscount) {
                dots[i] = ImageView(this@MainActivity)
                dots[i]!!.setImageDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.non_active_dots))

                val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                params.setMargins(8, 0, 8, 0)
                sliderDotspanel.addView(dots[i], params)
            }

            dots[0]!!.setImageDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.active_dots))
            viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

                }

                override fun onPageSelected(position: Int) {
                    for (i in 0 until dotscount) {
                        dots[i]!!.setImageDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.non_active_dots))

                    }

                    dots[position]!!.setImageDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.active_dots))

                }

                override fun onPageScrollStateChanged(state: Int) {

                }
            })
        }

    }
}
>Datagenerator
````````````
class DataGenerator constructor(): ViewModel() {

    companion object {
       // lateinit var da:RespCategories
    //   lateinit var da:MutableLiveData<RespCategories>
    }

            val d=MutableLiveData<RespCategories>()

    fun addData(respCategories: RespCategories){
       // d=respCategories
        d.value=respCategories

    }
    fun getData():MutableLiveData<RespCategories>{
        return d
    }
}
>RespCategories
````````````
data class RespCategories constructor(

    @field:SerializedName("type")
    val type: String? = null,

    @field:SerializedName("value")
    val value: List<String?>? = null


)

  [1]: https://i.stack.imgur.com/eDAhx.png
4

1 回答 1

0

您的代码中有错误:您的观察者在showData()观察一个DataGenerator对象,但onResponse()将数据回调到另一个对象。你应该

关于类型参数可空性的几句话LiveData。看Observer界面:

public interface Observer<T> {
    void onChanged(@Nullable T t);
}

方法的参数用onChanged()注释@NullableLiveData此方法根据类型参数的可空性观察可空类型。即使您LiveData使用非 null 类型参数定义,您也可以期待 null:

  • 如果您调用liveData.value新对象,但您可以覆盖默认空值并设置您自己的

    val d = MutableLiveData<RespCategories>().apply { value = RespCategories.DEFAULT }
    
  • 如果您的 java 代码发布空值(不被禁止)

于 2019-03-30T15:32:52.000 回答