Как решить "recyclerView не должен быть нулевым" - PullRequest
0 голосов
/ 28 марта 2020

Я пытаюсь реализовать представление Recycler в Activity после анализа данных с использованием Retrofit. Но проблема в том, что представление Recycler не может быть нулевым, даже после инициализации внутри onCreate метода до доступа.

Mainactitivty.kt

        class MainActivity : AppCompatActivity() {
        lateinit var myRecyclerView: RecyclerView

        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        retroInstance = RetroInstance()
        val instance = retroInstance.getInstance()
        val api = instance.create(RetroInterface::class.java)
        val callAll=api.getAllDetail()
    callAll.enqueue(object :retrofit2.Callback<ModelAll>{
           override fun onFailure(call: Call<ModelAll>, t: Throwable) {
               Toast.makeText(applicationContext,t.message,Toast.LENGTH_LONG).show()
           }

           override fun onResponse(call: Call<ModelAll>, response: Response<ModelAll>) {
               val allDetail=response.body()!!
                myRecyclerView=findViewById(R.id.recyclerView)
              myRecyclerView.layoutManager=LinearLayoutManager(this@MainActivity)
               myRecyclerView.adapter=CoronaAdapter(allDetail)
           }

       })
    }
  }

Операция с включенным видом переработчика

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AllCountries">


    <SearchView
        android:id="@+id/searchView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="2dp"
        android:layout_marginTop="5dp"
        android:layout_marginEnd="2dp"
        android:background="@drawable/custom_search"
        android:elevation="5dp"
        android:queryHint="Search here..."
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/searchView" />
</androidx.constraintlayout.widget.ConstraintLayout>

Logcat https://gist.github.com/devpawann/af3cef9d204a6f99cd7ed11937684fa2

EDIT : - Проблема решена, ошибка была в том, что я инициализировал представление рециркулятора в другом занятие

Ответы [ 2 ]

0 голосов
/ 28 марта 2020

Возможно, вы можете попробовать что-то вроде этого:

class MainActivity : AppCompatActivity() {
        private var allDetails: MutableList<ModelAll> = ArrayList()

        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        retroInstance = RetroInstance()
        val instance = retroInstance.getInstance()
        val api = instance.create(RetroInterface::class.java)
        val callAll=api.getAllDetail()


        //Init your recyclerview
        val myRecyclerView = findViewById(R.id.recyclerView)
        myRecyclerView.layoutManager=LinearLayoutManager(this)
        val coronaAdapter = CoronaAdapter(allDetails)
        myRecyclerView.adapter = adapter

        callAll.enqueue(object :retrofit2.Callback<ModelAll>{
           override fun onFailure(call: Call<ModelAll>, t: Throwable) {
               Toast.makeText(applicationContext,t.message,Toast.LENGTH_LONG).show()
           }

           override fun onResponse(call: Call<ModelAll>, response: Response<ModelAll>) {
               if(response.isSucessful()){
                    allDetails = response.body()!!
                    coronaAdapter.notifyDataSetChanged()
               }
           }

       })
}

РЕДАКТИРОВАТЬ: Проблема заключалась в том, что recyclerView был в другом макете, который раздули.

0 голосов
/ 28 марта 2020

Ваш recyclerView не был создан (в настоящее время он ссылается на null ).

Добавьте эту строку

 recyclerview = findViewById(R.id.recyclerView)

Или если вы используете Android Extensions , а затем убедитесь, что вы используете правильную программу повторного просмотра

...