Sorry for newbie question: I’m new in Android/Kotlin.
There is the RecyclerView in which a remote JSON is being parsed.
Here is an actual code of the Activity with this RecyclerView:
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import okhttp3.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val client = OkHttpClient()
val list = ArrayList<ListItem>()
val rcView = findViewById<RecyclerView>(R.id.rv_content)
rcView.layoutManager = LinearLayoutManager(this)
rcView.adapter = MyAdapter(list, this)
rcView.hasFixedSize()
val request: Request = Request.Builder()
.url("http://89.111.173.213:8000/api/")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
val strResponse = response.body!!.string()
val jsonObj: JSONObject = JSONObject(strResponse)
try {
val episodeArray = JSONArray(jsonObj)
for (i in 0 until episodeArray.length()) {
val episodeDetails = episodeArray.getJSONObject(i)
list.add(
ListItem(
episodeDetails.getString("pub_date"),
episodeDetails.getString("title"),
episodeDetails.getString("description"),
episodeDetails.getString("youtube_link")
)
)
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
})
}
}
The problem is that the app builds, but the RecyclerView is empty.
Could you please point out where I made a mistake?
2
Answers
You have to call rcView.adapter.notifyDataSetChanged() to notify your adapter that the data list has changed, it recommended to have your adapter in a separated variable
Set notifyDataSetChanged() on Recyclerview adapter
Inside your adapter, which you have overridden, you must also override methods for displaying and outputting information, see here for an example https://www.geeksforgeeks.org/android-recyclerview-in-kotlin/.