get(position)显示为空引用

时间:2018-09-07 14:04:34

标签: android android-recyclerview kotlin recycler-adapter

所以,我有两个带有不同适配器的recyclerview。如果我单击一个按钮,我想显示其中之一。另一个适配器运行良好。但是没有第二个适配器。

身体

09-07 21:41:37.000 11177-11219/com.example.android.footballmatchschedule I/System.out: {"events":[{"idEvent":"576511","idSoccerXML":"389896","strEvent":"Huddersfield Town vs Crystal Palace","strFilename":"English Premier League 2018-09-15 Huddersfield Town vs Crystal Palace","strSport":"Soccer","idLeague":"4328","strLeague":"English Premier League","strSeason":"1819","strDescriptionEN":null,"strHomeTeam":"Huddersfield Town","strAwayTeam":"Crystal Palace","intHomeScore":null,"intRound":"5","intAwayScore":null,"intSpectators":null,"strHomeGoalDetails":null,"strHomeRedCards":null,"strHomeYellowCards":null,"strHomeLineupGoalkeeper":null,"strHomeLineupDefense":null,"strHomeLineupMidfield":null,"strHomeLineupForward":null,"strHomeLineupSubstitutes":null,"strHomeFormation":null,"strAwayRedCards":null,"strAwayYellowCards":null,"strAwayGoalDetails":null,"strAwayLineupGoalkeeper":null,"strAwayLineupDefense":null,"strAwayLineupMidfield":null,"strAwayLineupForward":null,"strAwayLineupSubstitutes":null,"strAwayFormation":null,"intHomeShots":null,"intAwayShots":null,"dateEvent":"2018-09-15","strDate":"15\/09\/18","strTime":"14:00:00+00:00","strTVStation":null,"idHomeTeam":"133932","idAwayTeam":"133632","strResult":null,"strCircuit":null,"strCountry":null,"strCity":null,"strPoster":null,"strFanart":null,"strThumb":null,"strBanner":null,"strMap":null,"strLocked":"unlocked"},{"idEvent":"576512","idSoccerXML":"389897","strEvent":"Man City vs Fulham","strFilename":"English Premier League 2018-09-15 Man City vs Fulham","strSport":"Soccer","idLeague":"4328","strLeague":"English Premier League","strSeason":"1819","strDescriptionEN":null,"strHomeTeam":"Man City","strAwayTeam":"Fulham","intHomeScore":null,"intRound":"5","intAwayScore":null,"intSpectators":null,"strHomeGoalDetails":null,"strHomeRedCards":null,"strHomeYellowCards":null,"strHomeLineupGoalkeeper":null,"strHomeLineupDefense":null,"strHomeLineupMidfield":null,"strHomeLineupForward":null,"strHomeLineupSubstitutes":null,"strHomeFormation":null,"strAwayRedCards":null,"strAwayYellowCards":null,"strAwayGoalDetails":null,"strAwayLineupGoalkeeper":null,"strAwayLineupDefense":null,"strAwayLineupMidfield":null,"strAwayLineupForward":null,"strAwayLineupSubstitutes":null,"strAwayFormation":null,"intHomeShots":null,"intAwayShots":null,"dateEvent":"2018-09-15","strDate":"15\/09\/18","strTime":"14:00:00+00:00","strTVStation":null,"idHomeTeam":"133613","idAwayTeam":"133600","strResult":null,"strCircuit":null,"strCountry":null,"strCity":null,"strPoster":null,"strFanart":null,"strThumb":null,"strBanner":null,"strMap":null,"strLocked":"unlocked"},{"idEvent":"576513","idSoccerXML":"389898","strEvent":"Newcastle vs Arsenal","strFilename":"English Premier League 2018-09-15 Newcastle vs Arsenal","strSport":"Soccer","idLeague":"4328","strLeague":"English Premier League","strSeason":"1819","strDescriptionEN":null,"strHomeTeam":"Newcastle","strAwayTeam":"Arsenal","intHomeScore":null,"intRound":"5","intAwayScore":null,"intSpectators":null,"strHomeGoalDetails":null,"strHomeRedCards":null,"strHomeYellowCards":null,"strHomeLineupGoalkeeper":null,"strHomeLineupDefense":null,"strHomeLineupMidfield":null,"strHomeLineupForward":null,"strHomeLineupSubstitutes":null,"strHomeFormation":null,"strAwayRedCards":null,"strAwayYellowCards":null,"strAwayGoalDetails":null,"strAwayLineupGoalkeeper":null,"strAwayLineupDefense":null,"strAwayLineupMidfield":null,"strAwayLineupForward":null,"strAwayLineupSubstitutes":null,"strAwayFormation":null,"intHomeShots":null,"intAwayShots":null,"dateEvent":"2018-09-15","strDate":"15\/09\/18","strTime":"14:00:00+00:00","strTVStation":null,"idHomeTeam":"134777","idAwayTeam":"133604","strResult":null,"strCircuit":null,"strCountry":null,"strCity":null,"strPoster":null,"strFanart":null,"strThumb":null,"strBanner":null,"strMap":null,"strLocked":"unlocked"},{"idEvent":"576515","idSoccerXML":"389900","strEvent":"Bournemouth vs Leicester","strFilename":"English Premier League 2018-09-15 Bournemouth vs Leicester","strSport":"Soccer","idLeague":"4328","strLeague":"English Premier League","strSeason":"1819","strDescriptionEN":null,"strHomeTeam":"Bournemout

NextMatch类

class NextMatch(val event: List<Event>)
class Event(val strDate: String, val strHomeTeam: String, val strAwayTeam: String)

fetchJson函数

fun fetchJson(){
    //Json for prev match
    val url = "https://www.thesportsdb.com/api/v1/json/1/eventspastleague.php?id=4328"
    val url2 = "https://www.thesportsdb.com/api/v1/json/1/eventsnextleague.php?id=4328"
    val request = Request.Builder().url(url).build()
    val request2 = Request.Builder().url(url2).build()
    val client = OkHttpClient()
    client.newCall(request).enqueue(object: Callback{
        override fun onResponse(call: Call?, response: Response?){
            println("sukses")
            val body = response?.body()?.string()
            println(body)

            val gson = GsonBuilder().create()

            val prevMatch = gson.fromJson(body, PrevMatch::class.java)

            runOnUiThread { recyclerView_prevMatch.adapter = MainAdapters(prevMatch) }
        }
        override fun onFailure(call: Call?, e: IOException?){
            println("failed request")
        }
    })
    client.newCall(request2).enqueue(object: Callback{
        override fun onResponse(call: Call?, response: Response?){
            println("sukses")
            val body = response?.body()?.string()
            println(body)

            val gson = GsonBuilder().create()

            val nextMatch = gson.fromJson(body, NextMatch::class.java)

            runOnUiThread { recyclerView_nextMatch.adapter = MainAdapter(nextMatch) }
        }
        override fun onFailure(call: Call?, e: IOException?){
            println("failed request")
        }
    })

MainAdapter.kt 文件:

class MainAdapter(val nextMatch: NextMatch): RecyclerView.Adapter<CustomViewHolder>(){

//Adapter Next Match

override fun getItemCount(): Int {
    return 15
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
    val layoutInflater = LayoutInflater.from(parent.context)
    val callForRow = layoutInflater.inflate(R.layout.item_row,parent,false)
    return CustomViewHolder(callForRow)
}

override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
    holder.view.team_home.text =  nextMatch.event.get(position).strHomeTeam
    holder.view.team_away.text =  nextMatch.event.get(position).strAwayTeam
    holder.view.time_schedule.text = nextMatch.event.get(position).strDate
}

}

当我尝试运行它时,它强制停止了。在查看Logcat之后:

Process: com.example.android.footballmatchschedule, PID: 8307
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
    at com.example.android.footballmatchschedule.MainAdapter.onBindViewHolder(MainAdapter.kt:24)
    at com.example.android.footballmatchschedule.MainAdapter.onBindViewHolder(MainAdapter.kt:9)
    at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
    at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
    at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5913)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5752)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5748)
    at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2232)
    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1559)
    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1519)
    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:614)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3812)
    at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3225)
    at android.view.View.measure(View.java:19147)
    at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1212)
    at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1552)
    at android.view.View.measure(View.java:19147)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6113)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:223)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:141)
    at android.view.View.measure(View.java:19147)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6113)
    at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:400)
    at android.view.View.measure(View.java:19147)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6113)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:223)
    at android.view.View.measure(View.java:19147)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6113)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1723)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:788)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:648)
    at android.view.View.measure(View.java:19147)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6113)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:223)
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:3346)
    at android.view.View.measure(View.java:19147)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2491)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1450)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1704)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1323)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6718)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894)
    at android.view.Choreographer.doCallbacks(Choreographer.java:696)
    at android.view.Choreographer.doFrame(Choreographer.java:631)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880)
    at android.os.Handler.handleCallback(Handler.java:815)
    at android.os.Handler.dispatchMessage(Handler.java:104)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:5737)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller

它表明API的get(position)函数试图从空对象获取它。怎么可能?我的意思是我该怎么解决?

2 个答案:

答案 0 :(得分:1)

怀疑您的NextMatch是Java定义的类型,其中event可以为null。 尝试将onBindViewHolder函数更改为以下

fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
    val event = nextMatch.event
    if (event != null) {
        holder.view.team_home.text = event.get(position).strHomeTeam
        holder.view.team_away.text = event.get(position).strAwayTeam
        holder.view.time_schedule.text = event.get(position).strDate
    } else {
        Log.d("TAG", "event is null!!")
    }
}

如果您看到日志event is null,则确认您需要先在event对象中设置nextMatch,然后再使用它。

已更新

根据其他共享信息,此问题是由于event的{​​{1}}变量与正文JSON名称NextMatch不匹配。

要解决,只需更改

events

class NextMatch(val event: List<Event>)

然后gson反序列化将起作用,其中class NextMatch(val events: List<Event>) 现在不再为空。

答案 1 :(得分:1)

您的RecyclerView适配器的项目数是常数,您确定吗?

override fun getItemCount(): Int {
     return 15
}