Kotlin clickable button in ListView - android

I am making a Kotlin recipe app and I have a list of dishes name with a button to view the dish that will be generated whenever a new dish is added in a list view. The button is supposed to navigate users to a new activity where the recipe of the dish will be shown. However, the button does not work. I have tried a few suggested solutions but still does not work.
xml file of the list:
<?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"
android:background="#android:color/darker_gray"
tools:context=".ViewRecipe">
<ListView
android:id="#+id/recipeList"
android:layout_width="367dp"
android:layout_height="565dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="39dp"
android:text="Recipe List"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
xml for button:
<?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=".Recipes">
<TextView
android:id="#+id/recipeView2"
android:layout_width="228dp"
android:layout_height="28dp"
android:layout_marginStart="23dp"
android:layout_marginTop="47dp"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/recipeDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="33dp"
android:layout_marginEnd="20dp"
android:text="View"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Kotlin file for the list view:
package com.example.recipeapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ListView
import com.google.firebase.database.*
class ViewRecipe : AppCompatActivity() {
lateinit var ref: DatabaseReference
lateinit var recipeList: MutableList<AddRecipeModelClass>
lateinit var listView: ListView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_recipe)
recipeList = mutableListOf()
ref = FirebaseDatabase.getInstance().getReference("addRecipes")
listView = findViewById(R.id.recipeList)
ref.addValueEventListener(object: ValueEventListener {
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
recipeList.clear()
for(h in snapshot.children){
val recipe = h.getValue(AddRecipeModelClass::class.java)
recipeList.add(recipe!!)
}
val adapter = RecipeAdapter(applicationContext, R.layout.activity_recipes, recipeList)
listView.adapter = adapter
}
}
});
}
}
Kotlin file for the button:
package com.example.recipeapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class Recipes : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recipes)
val navView = findViewById<Button>(R.id.recipeDetails)
navView.setOnClickListener{
val intent = Intent(this, RecipeDetails::class.java)
startActivity(intent)
}
}
}
RecipeAdapter.kt
package com.example.recipeapp
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
class RecipeAdapter(val mCtx: Context, val layoutResId: Int, val recipeList: List<AddRecipeModelClass>)
: ArrayAdapter<AddRecipeModelClass>(mCtx, layoutResId, recipeList) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val layoutInflater: LayoutInflater = LayoutInflater.from(mCtx)
val view: View = layoutInflater.inflate(layoutResId, null)
val recipeView = view.findViewById<TextView>(R.id.recipeView2)
val recipe = recipeList[position]
recipeView.text = recipe.dishName
return view
}
}
Edit:
I have found that the issue is occurring because the "view" button is inside a list view. I tried using a "button" placed outside the listview and it works just fine. I am unable to solve it using the solutions found on the internet.
The image shows the 2 types of buttons. View is inside a listview, button is outside listview.
Any help will be greatly appreciated.

I haven't read your entire code but one problem that I found is this:
navView.setOnClickListener{
val intent = Intent(this, RecipeDetails::class.java)
// ^^^^
startActivity(intent)
}
The this in that scope refers to the View.OnClickListener object passed to setOnclickListener function. Not to the application context.
From kotlin docs :
To access this from an outer scope (a class, or extension function, or
labeled function literal with receiver) we write this#label where
#label is a label on the scope this is meant to be from
So you should be doing this instead:
navView.setOnClickListener{
val intent = Intent(this#Recipes, RecipeDetails::class.java)
// ^^^^ note the label #Recipes
startActivity(intent)
}
Alternatively you can call Intent constructor from outside the object of View.OnClickListener, in the onCreate function:
val intent = Intent(this, RecipeDetails::class.java)
val navView = findViewById<Button>(R.id.recipeDetails)
navView.setOnClickListener{
startActivity(intent)
}

Put this in your activity class and make sure you AddRecipeModelClass is parcelable
private val onItemAction: (AddRecipeModelClass) -> Unit = { it ->
val intent = Intent(this#ViewRecipe , RecipeDetails::class.java)
intent.putExtra("recipe", it)
startActivity(intent)
}
get a recipe from intent in a new activity
Add a click listener to your adapters getView
class RecipeAdapter(val mCtx: Context, val layoutResId: Int,
val recipeList: List<AddRecipeModelClass>,private val onItemSelected: (AddRecipeModelClass) -> Unit?)
: ArrayAdapter<AddRecipeModelClass>(mCtx, layoutResId, recipeList) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val layoutInflater: LayoutInflater = LayoutInflater.from(mCtx)
val view: View = layoutInflater.inflate(layoutResId, null)
val recipeView = view.findViewById<TextView>(R.id.recipeView2)
val btn= findViewById<Button>(R.id.recipeDetails)
val recipe = recipeList[position]
btn.setOnClickListener{
onItemSelected(recipe)
}
recipeView.text = recipe.dishName
return view
}
}
add function to the constructor
val adapter = RecipeAdapter(applicationContext, R.layout.activity_recipes, recipeList,onItemAction)

Related

How use View.OnClickListener with FirestoreRecyclerAdapter

I'm trying to create an application and considering my level it's not easy! I hope you could help me since I didn't succeed with the many links I found on the internet.
I can't add the onClick function of View.OnClickListener, each time the Intent function is not recognized. I tried to implement it in the UserViewHolder and FirestoreRecyclerAdapter class but it doesn't work.
Here is my current code:
---------- kotlin part ---------
package edu.stanford.rkpandey.emojistatus
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.main.activity_main.*
data class User(
val displayName: String? = "",
val emojis: String? = ""
)
class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class MainActivity : AppCompatActivity() {
private val db = Firebase.firestore
private lateinit var auth: FirebaseAuth
// Query the users collection
private val query = db.collection("users")
val options = FirestoreRecyclerOptions.Builder<User>()
.setQuery(query, User::class.java)
.setLifecycleOwner(this).build()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = Firebase.auth
val adapter = object: FirestoreRecyclerAdapter<User, UserViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val view = LayoutInflater.from(this#MainActivity).inflate(R.layout.item_pack, parent, false)
return UserViewHolder(view)
}
override fun onBindViewHolder(
holder: UserViewHolder,
position: Int,
model: User
) {
val tvName: TextView = holder.itemView.findViewById(R.id.title)
val tvEmojis: TextView = holder.itemView.findViewById(R.id.excerpt)
tvName.text = model.displayName
tvEmojis.text = model.emojis
}
}
rvUsers.adapter = adapter
rvUsers.layoutManager = LinearLayoutManager(this)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.miLogout) {
Log.i("MainActivity", "Logout")
auth.signOut()
val logoutIntent = Intent(this, LoginActivity::class.java)
logoutIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(logoutIntent)
}
return super.onOptionsItemSelected(item)
}
}
------- xml part -------
=> activity_main
<?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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvUsers"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
=> item_pack
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="100sp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="12sp"
android:layout_marginTop="12sp"
android:layout_marginEnd="12sp"
android:focusable="true"
android:clickable="true"
app:cardCornerRadius="10dp"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#color/colorPack">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
style="#style/NoteTitleFont"
android:textColor="#color/colorTitle"
tools:text="Note 1" />
<TextView
android:id="#+id/excerpt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12sp"
android:layout_below="#id/title"
android:maxLines="1"
android:ellipsize="end"
android:textStyle="italic"
android:textColor="#color/colorDescribe"
tools:text="test text va se trouver ici, ça va contenir le début de la description du package." />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
This code gives this result :
I would like that when I click on one of the carviews it can go to the activity_pack_detail.
Do you know how to do Intent to PackDetailActivity?
I get this error no matter what I do =>
You're getting that error because you are calling Intent's class constructor with a wrong argument. The first argument should be a Context and not a View. The keyword this is referring in your code to a View and not to a context, hence the error.
To solve this, you have to pass a Context object like this:
val i = Intent(view.getContext(), PackDetailActivity::class.java)
And your error will go away.

App crash on recyclerview scrolling android kotlin

I'm working on a project dealing with loading data from firebase into recyclerview. recyclerview seems working just fine but when i try to scroll it until the end of the posts it always make the app crash. it's so strange to me if i don't scroll to the end post it won't crash. in logcat it show only an error "fail to acquire dataanalyzer...". i have no clue about it. please kindly help!
Code as below :
package teacher
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.amazontutoringcenter.R
import com.example.amazontutoringcenter.databinding.ActivityTeacherLessonPlanBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.*
import com.google.firebase.firestore.EventListener
import com.squareup.picasso.Picasso
import student.StudentPostData
import kotlin.collections.ArrayList
class TeacherLessonPlan: AppCompatActivity() {
private lateinit var binding : ActivityTeacherLessonPlanBinding
private lateinit var auth: FirebaseAuth
private lateinit var firebaseFirestore: FirebaseFirestore
private lateinit var userRecyclerview: RecyclerView
private lateinit var studentLessonPlanAdapter: LessonPlanAdapter
private lateinit var userArrayList: ArrayList<StudentPostData>
private lateinit var studentName: String
private lateinit var studentProfileUri : String
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
binding = ActivityTeacherLessonPlanBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
auth = FirebaseAuth.getInstance()
// post lesson plan
binding.tvStudentName.setOnClickListener {
intent = Intent(this, TeacherLessonPlanPost::class.java)
intent.putExtra("studentName", studentName)
intent.putExtra("studentProfileUri", studentProfileUri)
startActivity(intent)
}
// get passing data to display profile and name
var b: Bundle = intent.extras!!
studentProfileUri = b.getString("studentProfileUri").toString()
studentName = b.getString("studentName").toString()
Picasso.get().load(studentProfileUri).fit()
.centerCrop().into(binding.imageStudentProfile)
userRecyclerview = findViewById(R.id.recyclerViewStudentLessonPlan)
userRecyclerview.layoutManager = LinearLayoutManager(this)
userArrayList = arrayListOf()
studentLessonPlanAdapter = LessonPlanAdapter(userArrayList)
userRecyclerview.adapter = studentLessonPlanAdapter
getStudentLessonPlanPost()
}
private fun getStudentLessonPlanPost() {
val uid = auth.currentUser!!.uid
firebaseFirestore = FirebaseFirestore.getInstance()
firebaseFirestore.collection("student").document("lesson plan")
.collection("$uid")
.addSnapshotListener(object : EventListener<QuerySnapshot> {
override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {
if(error != null){
Log.d("check error", error.message.toString())
return
}
for(dc : DocumentChange in value?.documentChanges!!){
if(dc.type == DocumentChange.Type.ADDED){
userArrayList.add(dc.document.toObject(StudentPostData::class.java))
userArrayList.sortByDescending {
it.date
}
}
}
studentLessonPlanAdapter.notifyDataSetChanged()
}
})
}
inner class LessonPlanAdapter(private val userList : ArrayList<StudentPostData>) : RecyclerView.Adapter<LessonPlanAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(
R.layout.student_lesson_plan,
parent,false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return userList.size
}
inner class MyViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){
val txLessonPlanDescription : TextView = itemView.findViewById(R.id.txLessonPlanDescription)
val imageStudentLessonPlan : ImageView = itemView.findViewById(R.id.imageStudentLessonPlan)
val imageStudentProfilePost : ImageView = itemView.findViewById(R.id.imageStudentProfilePost)
val tvStudentNamePost : TextView = itemView.findViewById(R.id.tvStudentNamePost)
// date on the post
val textDate : TextView = itemView.findViewById(R.id.txLessonPlanDate)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentitem = userList[position]
holder.txLessonPlanDescription.text = currentitem.description
holder.textDate.text = currentitem.date
Picasso.get().load(currentitem.imageUri)
.into(holder.imageStudentLessonPlan)
holder.tvStudentNamePost.text = studentName
Picasso.get().load(studentProfileUri).fit()
.centerCrop().into(holder.imageStudentProfilePost)
}
}
}
<?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="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<LinearLayout
android:id="#+id/relativeLayout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="70dp"
android:padding="15dp"
android:elevation="10dp"
android:layout_marginBottom="0dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/imageStudentProfile"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginStart="5dp"
android:layout_marginTop="50dp"
android:src="#drawable/ic_profile"
app:shapeAppearanceOverlay="#style/circular"
app:strokeColor="#0AF3D0"
android:layout_gravity="center_horizontal"
app:strokeWidth="1dp" />
<TextView
android:id="#+id/tvStudentName"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:padding="5dp"
android:fontFamily="serif"
android:clickable="true"
android:hint="បង្ហោះកិច្ចតែងការបង្រៀន..."
android:background="#drawable/border_square"
android:textColor="#2196F3"
android:textSize="20dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewStudentLessonPlan"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/student_lesson_plan">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
Since you are using the userArrayList variable globally to serve your adapter the data try to remove the LessonPlanAdapter class parameter and just use the global variable to populate it:
inner class LessonPlanAdapter() : RecyclerView.Adapter<LessonPlanAdapter.MyViewHolder>() {
...
override fun getItemCount(): Int = userArrayList.size
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentitem = userArrayList[position]
...
}
}
I think that the problem may be related to the fact that the class variable containing the data wasn't updated correctly.
That could have caused an index out of bounds exception when reaching the bottom of the list.
Solved ! I'm not sure what the problem was but I could solve it by deleting all of the documents that I have in firestore then trying to add new documents. now it's working fine. thank guys for your help !

RecyclerView only return the last image with Picasso

I'm using Kotlin for an Android app.
But i got a problem I can't resolve. May can you help me.
I'm storing some data in Firebase and I want to return it inside a grid RecyclerView.
Everything works (TextView) but only the last image is showing.
All the other images are white, not empty but just.. White. Every time I add an image in Firebase and return it inside the recyclerview, the previous image is going white and the RecyclerView only return the last one I added.
I think the problem comes from the URL and Picasso but I don't know how to resolve it.
Can you please help me ?
There are the screens, my code, and Firebase :
1 - Screens
2 - Fragment with RecyclerView
3 - Adapter
4 - Dataclass
5 - XML
6 - Firebase
1 - Screens :
Recyclerview (there are 4 images but only we can only see one, the rest are white) :
The screen of the XML (the src isn't a white image) :
2 - Fragment with RecyclerView
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.givenaskv1.R
import com.google.firebase.database.*
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_flux.*
import kotlinx.android.synthetic.main.post_vente.*
private const val TAG = "TAG"
class Flux : Fragment() {
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<ArticleAdapter.ViewHolder>? = null
private lateinit var dbref : DatabaseReference
private lateinit var userRecyclerview : RecyclerView
private lateinit var userArrayList : ArrayList<DataClassArticle>
private lateinit var articleAdapter: ArticleAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
fun getUserData() {
dbref = FirebaseDatabase.getInstance().getReference("Vente")
dbref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (userSnapshot in snapshot.children) {
val user = userSnapshot.getValue(DataClassArticle::class.java)
userArrayList.add(user!!)
userRecyclerview.adapter = ArticleAdapter(userArrayList)
}
// userRecyclerview.adapter = ArticleAdapter(userArrayList)
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
getUserData()
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_flux, container, false)
}
override fun onViewCreated(itemView: View, savedInstanceState: Bundle?) {
super.onViewCreated(itemView, savedInstanceState)
// RvPosts = le recyclerview
btnPublierVente.setOnClickListener {
val bottomSheet = BottomsheetVentes()
bottomSheet.show(fragmentManager!!, "BottomSheet")
}
rvPosts.apply {
userRecyclerview = findViewById(R.id.rvPosts)
// articleAdapter = ArticleAdapter(context.applicationContext)
userRecyclerview.setHasFixedSize(true)
// recyclerView.adapter = articleAdapter
userArrayList = arrayListOf<DataClassArticle>()
// dataList = emptyList<DataClassArticle>()
// set a LinearLayoutManager to handle Android
// RecyclerView behavior
layoutManager = LinearLayoutManager(activity)
// articleAdapter.setDataList(userArrayList)
rvPosts.setLayoutManager(GridLayoutManager(this.context, 2))
}
}
}
3 - Adapter
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.givenaskv1.R
import com.squareup.picasso.Picasso
class ArticleAdapter(private var articleList: ArrayList<DataClassArticle>) : RecyclerView.Adapter<ArticleAdapter.ViewHolder>() {
val TAG = "TAG"
var dataList = emptyList<DataClassArticle>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context)
.inflate(R.layout.post_vente, parent, false)
return ViewHolder(v)
}
internal fun setDataList(dataList : List<DataClassArticle>) {
this.dataList = dataList
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val data = articleList[position]
val targetImageView = holder.articleImage
Picasso.get().load(data.photo).into(targetImageView)
holder.articleTitle.text = data.titrevente
holder.articlePrice.text = data.prixvente
holder.articleLocalisation.text = data.zone
holder.articleId.text = data.venteId
holder.venteUser.text = data.firstname
}
override fun getItemCount() : Int {
return articleList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var articleImage : ImageView
var articleTitle : TextView
var articlePrice : TextView
var articleLocalisation : TextView
var venteUser : TextView
var articleId : TextView
var photoUrl : TextView
init {
articleImage = itemView.findViewById(R.id.articleImage)
articleTitle = itemView.findViewById(R.id.titreArticle)
articlePrice = itemView.findViewById(R.id.prixArticle)
articleLocalisation = itemView.findViewById(R.id.nomVilleArticle)
venteUser = itemView.findViewById(R.id.venteUser)
articleId = itemView.findViewById(R.id.venteId)
photoUrl = itemView.findViewById(R.id.photoUrl)
itemView.setOnClickListener {
val context = itemView.context
val intent = Intent(context, DescriptionVente::class.java).apply {
putExtra("USER_KEY_VENTE", articleId.text)
putExtra("USER_KEY_FIRSTNAME", venteUser.text )
putExtra("USER_KEY_FIRSTNAME", venteUser.text )
}
context.startActivity(intent)
}
}
}
}
4 - Dataclass
data class DataClassArticle(
var titrevente: String? = null,
var prixvente: String? = null,
var zone: String? = null,
var venteId : String? = null,
var firstname : String? = null,
var photo: String? = null,
var photoUrl : String? = null
)
5 - XML
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
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="175dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/articleImage"
android:layout_width="175dp"
android:layout_height="175dp"
android:scaleType="centerCrop"
app:shapeAppearance="#style/RoundedSquare"
android:src="#drawable/profile"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:id="#+id/titreArticle"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:textSize="16dp"
android:textColor="#color/black"
android:fontFamily="#font/baloo"
android:text="Titre de l'article"
/>
<ImageView
android:layout_width="50dp"
android:layout_height="18dp"
android:layout_marginEnd="5dp"
android:layout_marginTop="4dp"
android:src="#drawable/saveicone"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/prixArticle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:textSize="14dp"
android:textColor="#color/black"
android:fontFamily="#font/avenir45"
android:text="20"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:textSize="14dp"
android:textColor="#color/black"
android:fontFamily="#font/avenir45"
android:text="€"
/>
</LinearLayout>
<TextView
android:id="#+id/nomVilleArticle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="Nom de la ville"
/>
<TextView
android:id="#+id/dateAericle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="3 j"
/>
<TextView
android:id="#+id/venteId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<TextView
android:id="#+id/venteUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<TextView
android:id="#+id/photoUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</GridLayout>
6 - Firebase
The photo2, photo3, photo4 are vollontary null because I did'nt upload any image. I dont return photo2, photo3, photo4 inside the code.
Thank you everyone for your help 🙏

Recyclerview No adapter attached; skipping layout (Kotlin)

i'd like to know what i'm doing wrong over here. I'm building a CRUD app in Kotlin, and i'm using the recyclerview to make the readData page. The problem is, when i'm on the readData page doesn't show me anything, just the text views, so i debugged and when i join in the page, show this message: "Recyclerview No adapter attached; skipping layout".
Here's my code:
(i'm brazilian, so, some words are in portuguese, but you'll get it.)
verDados.kt
package com.nicolas.csrd
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_ver_database.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class verDados : AppCompatActivity() {
private lateinit var database: FirebaseDatabase
private lateinit var reference: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ver_database)
database = FirebaseDatabase.getInstance()
reference = database.getReference("usuarios")
verDados()
btn_voltar.setOnClickListener() {
startActivity(Intent(this#verDados, Dashboard::class.java))
finish()
}
}
private fun verDados() {
reference.addValueEventListener(object: ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
Log.e("cancelar", p0.toString())
}
override fun onDataChange(p0: DataSnapshot) {
//Colocando os usuarios numa lista
var list = ArrayList<DatabaseModelo>()
for (data in p0.children) {
val model = data.getValue(DatabaseModelo::class.java)
list.add(model as DatabaseModelo)
}
if (list.size > 0) {
val ususariosModelo = usuariosModelo(list)
recyclerview.adapter = ususariosModelo
}
}
})
}
}
DatabaseModel
package com.nicolas.csrd
class DatabaseModelo() {
lateinit var email: String
lateinit var senha: String
constructor(email: String, senha: String) : this() {
this.email = email
this.senha = senha
}
}
usuariosModelo.kt (recyclerview adapter)
package com.nicolas.csrd
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.appcompat.view.menu.MenuView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.usuarios_modelo.view.*
class usuariosModelo(val list: ArrayList<DatabaseModelo>): RecyclerView.Adapter<usuariosModelo.ViewHolder>() {
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val email = itemView.campo_email
val senha = itemView.campo_senha
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.usuarios_modelo, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.email.text = list[position].email
holder.senha.text = list[position].senha
}
override fun getItemCount(): Int {
return list.size
}
}
----- XML FILES -----
activity_ver_database.xml (read data page)
<?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:background="#color/dark"
tools:context=".Login">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal" >
<ImageView
android:id="#+id/btn_voltar"
android:layout_width="50dp"
android:layout_height="30dp"
android:layout_gravity="start"
android:layout_marginStart="5dp"
android:layout_marginTop="23dp"
android:src="#drawable/back_arrow" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DADOS"
android:textColor="#7ec1d1"
android:textSize="30sp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:letterSpacing="0.15"
android:fontFamily="#font/montserrat_medium"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Todos os usuários cadastrados"
android:textColor="#7ec1d1"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="0dp"
android:fontFamily="#font/montserrat_thin"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerview"
android:layout_margin="10sp"/>
<TextView
android:id="#+id/btn_cadastrar"
android:layout_width="350dp"
android:layout_height="50dp"
android:layout_marginTop="30dp"
android:backgroundTint="#7ec1d1"
android:gravity="center_horizontal"
android:fontFamily="#font/montserrat_regular"
android:text="Deseja cadastrar alguém? Clique aqui."
android:textColor="#color/white2"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
You are getting this error because you have no defined an adaptor for the RecyclerView that you are using. Somewhere inn your onCreate method, create the adaptor and set it to the RecyclerView. Something like:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ver_database)
recyclerView = findViewById(R.id.recyclerview)
recyclerView.apply {
adapter = usuariosModelo(listOfItems)
}
database = FirebaseDatabase.getInstance()
reference = database.getReference("usuarios")
verDados()
btn_voltar.setOnClickListener() {
startActivity(Intent(this#verDados, Dashboard::class.java))
finish()
}
}
i solve the problem just adding the tag below inside the recyclerview tag in the .xml file:
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
I hope that help y'all!

How to make Android RecyclerView invisible by clicking button inside itself?

Here's the minimal test case what I've managed to make.
It combines with a RecyclerView and TextView, the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/textViewBatteryInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi, I'm watching you!"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
With the MainActivity.kt:
package kot.bignerd.recyclerview101
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val items = arrayListOf<String>()
for (i in 10..50) {
items.add("Here's the $i th")
}
my_rv.layoutManager = LinearLayoutManager(this)
my_rv.adapter = MyListAdapter(items, this)
//my_rv.visibility = View.GONE
}
}
With a very simple adapter(MyListAdapter):
package kot.bignerd.recyclerview101
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class MyListAdapter(val datas: List<String>, val context: Context) : RecyclerView.Adapter<MyListAdapter.InnerHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): MyListAdapter.InnerHolder {
var itemView: View = LayoutInflater.from(context).inflate(R.layout.item_rv, p0, false)
return InnerHolder(itemView)
}
override fun getItemCount(): Int = datas.size
class InnerHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var itemText: TextView = itemView.findViewById(R.id.item_tv)
}
override fun onBindViewHolder(p0: MyListAdapter.InnerHolder, p1: Int) {
p0?.itemText?.text = datas[p1]
}
}
The R.layout.item_rv mentioned in the adapter is (item_rv.xml):
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="#+id/item_cl"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_tv"
android:layout_width="0dp"
android:layout_height="50dp"
android:text="TestRV"
android:textSize="18sp"
android:gravity="center"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent" tools:layout_editor_absoluteY="16dp"
app:layout_constraintHorizontal_bias="0.0"/>
<Button
android:text="Close"
android:layout_width="86dp"
android:layout_height="wrap_content" tools:layout_editor_absoluteY="16dp"
android:id="#+id/button" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"/>
</android.support.constraint.ConstraintLayout>
I was wondering if maybe we could make the RecyclerView disappeared when I click any one of the button inside it? Just like the code my_rv.visibility = View.GONE in the MainActivity.kt:
Your adapter need to receive a Listener as an object in order to react to clicks.
Here's an example:
package kot.bignerd.recyclerview101
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class MyListAdapter(val datas: List<String>, val context: Context, val clickListener: ClickListener) : RecyclerView.Adapter<MyListAdapter.InnerHolder>() {
public interface ClickListener {
fun onItemClicked()
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): MyListAdapter.InnerHolder {
var itemView: View = LayoutInflater.from(context).inflate(R.layout.item_rv, p0, false)
return InnerHolder(itemView)
}
override fun getItemCount(): Int = datas.size
class InnerHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var itemText: TextView = itemView.findViewById(R.id.item_tv)
var button: Button = itemView.findViewById(R.id. button)
fun bindView(text: String, clickListener: ClickListener) {
itemText.text = text
button.setOnClickListner {
clickListner.onItemClicked()
}
}
}
override fun onBindViewHolder(holder: MyListAdapter.InnerHolder, position: Int) {
holder.bindView(datas[position], clickListener)
}
}
Then change the signature of the activity as follow:
class MainActivity : AppCompatActivity(), ClickListener {
and implement the function as follow:
override fun onItemClicked() {
my_rv.visibility = View.GONE
}
Last, but not least, change how you initialise your adapter:
MyListAdapter(items, this, this)

Categories

Resources