nested recycler view not visible - android

I'm trying to create a nested recycler view with data received from the server(using Retrofit). The outer recyclerview prints fine, but the inner recyclerview doesn't print at all.
No Error, No Warning...I don't know why. please Help.
my recylcerview blueprint here
Layout Code
the layout xml look like this
(1) activity_main
<androidx.coordinatorlayout.widget.CoordinatorLayout
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=".MainActivity">
<com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.appbar.CollapsingToolbarLayout ...>
<androidx.appcompat.widget.Toolbar
android:id="#+id/homeToolbar" ... />
<androidx.constraintlayout.utils.widget.ImageFilterView
android:id="#+id/homeLogo" ... />
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/homeBanner" ... />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/outerRecycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="50dp" ... />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
(2) item_outer_recycler
<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="wrap_content">
<ImageView
android:id="#+id/houseImage"
android:contentDescription="main image"
android:layout_width="match_parent"
android:layout_height="150dp".../>
<TextView
android:id="#+id/houseName"
android:layout_width="200dp"
android:layout_height="30dp"
tools:text="some name" ... />
<TextView
android:id="#+id/houseAddress"
android:layout_width="300dp"
android:layout_height="20dp"
android:layout_marginStart="15dp"
tools:text="some address" ... />
<TextView
android:id="#+id/houseHomepage"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginEnd="15dp".../>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/innerRecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
(3) item_inner_recycler
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tool="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/houseTag"
android:layout_width="50dp"
android:layout_height="20dp"
android:textSize="12sp"
android:textColor="#878d95"
android:background="#e4e7ed"
android:textAlignment="center"
tool:text="roop top"/>
</LinearLayout>
Adapters Code
(1) outer recycler adapter
class MainHouseHolder(val binding: ItemOuterRecyclerBinding): RecyclerView.ViewHolder(binding.root)
class MainHouseAdapter(private val context: Context, private val data: List<House>):
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun getItemCount(): Int = data.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainHouseHolder =
MainHouseHolder(ItemOuterRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val house = data[position]
val binding = (holder as MainHouseHolder).binding
binding.innerRecycler.adapter = MainTagAdapter(house.tags)
binding.innerRecycler.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
// process outer recycler view
}
}
(2) inner recycler adapter
class MainTagHolder(val binding: ItemInnerRecyclerBinding) : RecyclerView.ViewHolder(binding.root)
class MainTagAdapter(private val data: String) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var tagData :MutableList<String> = mutableListOf()
override fun getItemCount(): Int {
tagData = data.split(",") as MutableList<String>
return tagData.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainTagHolder =
MainTagHolder(ItemInnerRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val binding = (holder as MainTagHolder).binding
binding.houseTag.text = tagData[position]
}
}
Activity Code
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var houseList : List<House>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.homeToolbar)
val apiClient = APIClient().connectInterface
val houseCall = apiClient.getHouseList()
houseCall.enqueue(object : Callback<HouseList> {
override fun onResponse(call: Call<HouseList>, response: Response<HouseList>) {
Log.d("CONNECTOR", "ON_RESPONSE")
houseList = response.body()?.list as List<House>
val adapter = MainHouseAdapter(applicationContext, houseList)
binding.houseList.adapter = adapter
binding.houseList.layoutManager = LinearLayoutManager(applicationContext)
adapter.notifyDataSetChanged()
}
override fun onFailure(call: Call<HouseList>, t: Throwable) {
Log.d("CONNECTOR", "FAILURE")
t.printStackTrace()
}
})
}
}

in item_outer_recycler
change
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/innerRecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="parent" />
to
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/innerRecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/houseAddress" />

I think you should change outer adapter from
class MainHouseHolder(val binding: ItemOuterRecyclerBinding): RecyclerView.ViewHolder(binding.root)
class MainHouseAdapter(private val context: Context, private val data: List<House>):
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun getItemCount(): Int = data.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainHouseHolder =
MainHouseHolder(ItemOuterRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val house = data[position]
val binding = (holder as MainHouseHolder).binding
binding.innerRecycler.adapter = MainTagAdapter(house.tags)
binding.innerRecycler.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
// process outer recycler view
}
}
to
class MainHouseAdapter(private val context: Context, private val data: List<House>):
RecyclerView.Adapter<MainHouseAdapter.MainHouseHolder>() {
override fun getItemCount(): Int = data.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainHouseHolder =
MainHouseHolder(ItemOuterRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val house = data[position]
val binding = (holder as MainHouseHolder).binding
binding.innerRecycler.adapter = MainTagAdapter(house.tags)
binding.innerRecycler.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
// process outer recycler view
}
inner class MainHouseHolder(val binding: ItemOuterRecyclerBinding): RecyclerView.ViewHolder(binding.root)
}
and make inner adapter like outer too
class MainTagAdapter(private val data: String) : RecyclerView.Adapter<MainTagAdapter.MainTagHolder>() {
var tagData :MutableList<String> = mutableListOf()
override fun getItemCount(): Int {
tagData = data.split(",") as MutableList<String>
return tagData.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainTagHolder =
MainTagHolder(ItemInnerRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val binding = (holder as MainTagHolder).binding
binding.houseTag.text = tagData[position]
}
inner class MainTagHolder(val binding: ItemInnerRecyclerBinding) : RecyclerView.ViewHolder(binding.root)
}

Oh...the problem was that innerRecycler was set to app:layout_constraintTop_toBottomOf="parent" . I made a stupid mistake.
I'm sorry

Related

RecyclerView Not showing Text

I am new to mobile development with kotlin and I am trying to add a new item to the recyclerview.
The item is added to the recycler view but the text is not visible. I don't get what it's wrong.
I am using Kotlin in Android Studio 4.2
The class AgentAttributes only contains two properties:val Name:String ,val Value:String
**activity_main.xml**
<EditText
android:id="#+id/etSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="No emp"
app:layout_constraintEnd_toStartOf="#+id/btnSearch"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#android:string/search_go"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvAgentAttributes"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etSearch" />
**MainActivity.kt**
private lateinit var agentAttributesAdapter:AgentAttributesAdapter
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
//setContentView(R.layout.activity_main)
//constructor
agentAttributesAdapter = AgentAttributesAdapter(mutableListOf())
//Definition of Recycler view adapter
binding.rvAgentAttributes.adapter = agentAttributesAdapter
binding.rvAgentAttributes.layoutManager = LinearLayoutManager(this)
//THIS IS THE WAY THAT I AM TRYING TO ADD A NEW ITEM
val agentAttr = AgentAttributes("Nombre","JOEL ROMUALDO LOPEZ SALIDO")
agentAttributesAdapter.addAttributes(agentAttr)
**AgentAttributesAdapter**
class AgentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AgentViewHolder {
return AgentViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.agent_details,
parent,
false
)
)
override fun onBindViewHolder(holder: AgentViewHolder, position: Int) {
val layoutInflater = LayoutInflater.from(holder.itemView.context)
binding = AgentDetailsBinding.inflate(layoutInflater)
//val view = binding.root
val currentAgent = agent_attributes[position]
holder.itemView.apply {
binding.tvAttribute.text = currentAgent.Name.toString()
}
}
override fun getItemCount(): Int {
return agent_attributes.size
}
fun addAttributes(attr:AgentAttributes){
agent_attributes.add(attr)
notifyItemInserted(agent_attributes.size - 1)
}
There's no need to inflate your layout in the "binding" step:
override fun onBindViewHolder(viewHolder: ChoicesViewHolder, pos: Int) {
AgentDetailsBinding.bind(viewHolder.itemView).apply {
val currentAgent = agent_attributes[position]
tvAttribute.text = currentAgent.Name.toString()
}
}
PS: variables should be lower case, so currentAgent should have a name, no Name

How to create multiple buttons with recycleview

My app shows multiple ImageButton with recycleview, everything works fine, what i want is when a person clicks a Imagebutton, they will be directed to the activity "monactivitefinal" and keep the content of "article.ifram" so that I use it on this new activity.
all the Imagebutton redirect to the same activity "monactivitefinal" only the variable "article.ifram" that changes
This is my code :
class Article(var id: Int, var nom: String, var lienimg: String, var ifram: String){
}
class ArticleAdapter(var articles: ArrayList<Article>) : RecyclerView.Adapter<ArticleAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
var vue=LayoutInflater.from(parent.context).inflate(
R.layout.listevisitess,
parent,
false
)
return MyViewHolder(vue)
}
override fun getItemCount(): Int {
return articles.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
var article = articles.get(position)
holder.nomvisite.setText(article.nom)
holder.lieimgvisite.setText(article.lienimg)
holder.ifram.setText(article.ifram)
var urldelimg:String = article.lienimg
Glide.with(holder.imagedubloc.context).load(urldelimg).into(holder.imagedubloc)
}
class MyViewHolder(var vue: View):RecyclerView.ViewHolder(vue){
var nomvisite=vue.findViewById<TextView>(R.id.nom_visite)
var lieimgvisite=vue.findViewById<TextView>(R.id.lienimg)
var ifram=vue.findViewById<TextView>(R.id.ifram)
var imagedubloc=vue.findViewById<ImageView>(R.id.imagedubloc)
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/nom_visite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
/>
<TextView
android:id="#+id/lienimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
/>
<ImageButton
android:id="#+id/imagedubloc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:scaleType="fitCenter"
/>
<TextView
android:id="#+id/ifram"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclevirtuel"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
Thank you
You can pass an extra field within your Intent that you are using to navigate to the new activity, you code would be like this:
class ArticleAdapter(var articles: ArrayList<Article>) : RecyclerView.Adapter<ArticleAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
var vue=LayoutInflater.from(parent.context).inflate(
R.layout.listevisitess,
parent,
false
)
return MyViewHolder(vue)
}
override fun getItemCount(): Int {
return articles.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
var article = articles.get(position)
holder.nomvisite.setText(article.nom)
holder.lieimgvisite.setText(article.lienimg)
holder.ifram.setText(article.ifram)
var urldelimg:String = article.lienimg
Glide.with(holder.imagedubloc.context).load(urldelimg).into(holder.imagedubloc)
// here you pass your "ifram" value to the activity you're navigating to
holder.imagedubloc.setOnClickListener {
startActivity(Intent(holder.vue.context,monactivitefinal::class.java).apply {
putExtra("ifram", article.ifram)
})
}
}
class MyViewHolder(var vue: View):RecyclerView.ViewHolder(vue){
var nomvisite=vue.findViewById<TextView>(R.id.nom_visite)
var lieimgvisite=vue.findViewById<TextView>(R.id.lienimg)
var ifram=vue.findViewById<TextView>(R.id.ifram)
var imagedubloc=vue.findViewById<ImageView>(R.id.imagedubloc)
}
}
in your activity you can get "ifram" value as follows:
val ifram = getIntent().getStringExtra("ifram")
You need add listener to handle onClick Event, then the ButtonListActivity needs to implement this interface and init your adapter with it like this.
Listener
interface ImageButtonClickListener {
fun onImageButtonClick(articleIfram: String)
}
Activity with list of buttons
class ButtonListActivity : AppCompactActivity(), ImageButtonClickListener {
private val adapter: ArticleAdapter = ArticleAdapter(ArrayList(), this)
override fun onImageButtonClick(articleIfram: String) {
val intent = Intent(context, Monactivitefinal::class.java)
intent.putExtra("articleIfram", articleIfram)
startActivity(intent)
}
}
Your adapter
class ArticleAdapter(
val onImageButtonClickListener: ImageButtonClickListener,
var articles: ArrayList<Article>
) : RecyclerView.Adapter<ArticleAdapter.MyViewHolder>(){
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
var article = articles.get(position)
imagedubloc.setOnClickListener {
onImageButtonClickListener.onImageButtonClick(article. ifram)
}
}
}
You could use lambda if you don't want to add listener
Activity with list of buttons
class ButtonListActivity : AppCompactActivity(), ImageButtonClickListener {
private val onImageButtonClick: (String) -> Unit = {
val intent = Intent(context, Monactivitefinal::class.java)
intent.putExtra("articleIfram", articleIfram)
startActivity(intent)
}
private val adapter: ArticleAdapter = ArticleAdapter(ArrayList(), onImageButtonClick)
}
Your adapter
class ArticleAdapter(
val onImageButtonClickListener: (String) -> Unit,
var articles: ArrayList<Article>
) : RecyclerView.Adapter<ArticleAdapter.MyViewHolder>(){
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
var article = articles.get(position)
imagedubloc.setOnClickListener {
onImageButtonClickListener(article. ifram)
}
}
}

ViewPager2 not work with RecyclerView.Adapter

Android studio 3.6
In my activity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dataBinding =
DataBindingUtil.setContentView<SelectionActivityBinding>(
this,
R.layout.selection_activity
)
dataBinding.setHandler(this)
setSupportActionBar(dataBinding.toolBarContainer.toolBar)
getSupportActionBar()!!.setDisplayHomeAsUpEnabled(true)
getSupportActionBar()!!.setDisplayShowTitleEnabled(false)
val articlesList = mutableListOf<Article>()
val article1 = Article()
article1.title = "111111"
articlesList.add(article1)
val article2 = Article()
article1.title = "222222"
articlesList.add(article2)
articleAdapter = ArticleAdapter()
articleAdapter.setList(articlesList)
dataBinding.viewPager2.adapter = articleAdapter
}
Here xml layout:
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="handler"
type="com.myproject.ui.activity.SelectionActivity" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/waitressCallMainContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolBarContainer"
layout="#layout/tool_bar"
android:title='#{#string/articles}'
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewPager2"
android:layout_width="0dp"
android:layout_height="300dp"
android:background="#bbccaa"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolBarContainer" />
here custom adapter:
class ArticleAdapter : RecyclerView.Adapter<ArticleAdapter.ArticleViewHolder>() {
var articleList: List<Article> = mutableListOf()
companion object {
private val TAG = ArticleAdapter::class.java.name
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
return ArticleViewHolder(parent)
}
override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
Debug.d(TAG, "onBindViewHolder: position = $position")
holder.bind(articleList[position])
}
fun setList(articleList: List<Article>) {
this.articleList = articleList
notifyDataSetChanged()
}
override fun getItemCount(): Int = articleList.size
class ArticleViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
constructor(parent: ViewGroup) :
this(
LayoutInflater.from(parent.context).inflate(
R.layout.article_item,
parent,
false
)
)
fun bind(article: Article) {
Debug.d(TAG, "bind: article = $article")
itemView.titleTextView.text = article.title
}
}
}
But as result it show empty viewpager2 (green background). No inner item in viewPager2. As result no swiping.

recyclerview showing empty white screen?

I am developing news app using kotlin but it is showing empty white screen and there is no error or exception on the logcat
below my SportNewsAdapter.kt
class SportNewsAdapter(val context: Context) : RecyclerView.Adapter<SportNewsAdapter.MyViewHolder>() {
var articleList : List<Article> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.news_list,parent,false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
return articleList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.tvMovieName.text = articleList.get(position).title
Glide.with(context).load(articleList.get(position).urlToImage)
.apply(RequestOptions().centerCrop())
.into(holder.image)
}
fun setMovieListItems(movieList: List<Article>){
this.articleList = articleList;
notifyDataSetChanged()
}
class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {
val tvMovieName: TextView = itemView!!.findViewById(R.id.title)
val image: ImageView = itemView!!.findViewById(R.id.image)
}
}
below news_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
below MainActivity.kt
class MainActivity : AppCompatActivity() {
lateinit var recyclerView: RecyclerView
lateinit var sportNewsAdapter: SportNewsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView)
sportNewsAdapter = SportNewsAdapter(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = sportNewsAdapter
val apiInterface = SportNewsInterface.create().getNews()
apiInterface.enqueue( object : Callback<List<Article>> {
override fun onResponse(call: Call<List<Article>>?, response: Response<List<Article>>?) {
if(response?.body() != null)
sportNewsAdapter.setMovieListItems(response.body()!!)
}
override fun onFailure(call: Call<List<Article>>?, t: Throwable?) {
}
})
}
}
below activity_main.xml
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" />
below SportNewsInterface.kt
interface SportNewsInterface {
#GET("v2/top-headlines?country=us&apiKey=da331087e3f3462bb534b3b0917cbee9")
fun getNews() : Call <List<Article>>
companion object {
var BASE_URL = "https://newsapi.org/"
fun create() : SportNewsInterface {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build()
return retrofit.create(SportNewsInterface::class.java)
}
} }
below SportNewsResponse.kt where implemented retrofit
data class SportNewsResponse(
val articles: List<Article>,
val status: String,
val totalResults: Int
)
Change recycler view height to wrap content and run again

Unable to update RecyclerView

I'm unable to update my RecyclerView. Tried every solution on stackoverflow but nothing helps. I've tried to add layoutmanager in code, hardcode number of items, made new files, checked if I had duplicate files etc.. I also debugged and confirmed that "onAttachedToRecyclerView" is called, but getItemCount and the others i've listed in the adapter are not called except for the constructor
Adapter:
class BaseAdapter(context: Context, val items: List<Item>) :
RecyclerView.Adapter<LineBoxAdapter.BaseAdapter>() {
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = items[position].text
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.simple_item,
parent,
false
)
)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView = itemView.findViewById<TextView>(R.id.title)
}
}
Function that updates recyclerView:
val listView =
LayoutInflater.from(context).inflate(R.layout.list, viewGroup,
false)
val list = listView.findViewById<RecyclerView>(R.id.
LinearLayoutManager(context)
val adapter = BaseAdapter(context, items)
list.adapter = adapter
adapter.notifyDataSetChanged()
RECYCLERVIEW:
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/items_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:overScrollMode="never"
android:requiresFadingEdge="horizontal"
app:layoutManager="android.support.v7.widget.LinearLayoutManager" />
SIMPLE_ITEM:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:orientation="horizontal">
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="25" />
</LinearLayout>
You should avoid using existing class names from API.
I will post my working code.
simple_item:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_simple_item"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
RecyclerAdapter:
class RecyclerAdapter(context: Context, val items: List<Item>) :
RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>() {
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.textView.text = items[position].itemName
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
MyViewHolder {
return MyViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.simple_item,
parent,
false
)
)
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView = itemView.findViewById<TextView>(R.id.text_simple_item)
}
}
My Activity:
class RecyclerActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler)
val recyler = findViewById<RecyclerView>(R.id.rv_activity_recycler)
val list = mutableListOf(Item("Me"), Item("You"), Item("We"))
val adapter = RecyclerAdapter(this, list)
recyler.layoutManager = LinearLayoutManager(this)
recyler.adapter = adapter
}
}
My Item:
class Item(val itemName: String)

Categories

Resources