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 !
Related
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 🙏
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!
I followed a tutorial to create an application that displays data from a mysql table, if i run the app everything works without error, the application opens with the header but without content, blank page instead of the content list.
activity_main.xml :
package com.example.bingmada
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
class MainActivity : AppCompatActivity() {
var adapter:ArticleAdapter ?=null
var articles:ArrayList<Article> ?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
articles= ArrayList()
getArticlesFromServer()
adapter = ArticleAdapter(articles!!)
var recyclerView = findViewById<RecyclerView>(R.id.recyclevirtuel)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter=adapter
}
fun getArticlesFromServer(){
var url="https://www.exemplesite.com/android/bingmada.php"
var stringRequest=StringRequest(Request.Method.GET,url,Response.Listener { response -> parseData(response) }, Response.ErrorListener { error ->
Toast.makeText(this,"Erreur de connexion ", Toast.LENGTH_SHORT).show()
})
var req=Volley.newRequestQueue(this)
req.add(stringRequest)
}
fun parseData(response:String){
var arrayJson = JSONArray(response)
for(i in 0..arrayJson.length()-1){
var currentObject=arrayJson.getJSONObject(i)
var article = Article(currentObject.getInt("id"),
currentObject.getString("nom"),
currentObject.getString("lienimg"),
currentObject.getString("ifram"))
articles?.add(article)
}
}
}
the page https://www.exemplesite.com/android/bingmada.php show :
[{"id":"1","nom":"tesmon","lienimg":"bingo1","ifram":"car1"},{"id":"2","nom":"testeds","lienimg":"bingo","ifram":"car2"},{"id":"3","nom":"test1","lienimg":"bingo3","ifram":"car3"},{"id":"4","nom":"testr","lienimg":"bingo4","ifram":"car4"},{"id":"5","nom":"test2","lienimg":"bingo5","ifram":"car5"},{"id":"6","nom":"letest","lienimg":"bingo6","ifram":"car6"},{"id":"7","nom":"test3","lienimg":"bingo7","ifram":"car7"},{"id":"8","nom":"testo","lienimg":"bingo8","ifram":"car8"},{"id":"9","nom":"test4","lienimg":"bingo9","ifram":"car9"},{"id":"10","nom":"testad","lienimg":"bingo10","ifram":"car10"},{"id":"11","nom":"test5","lienimg":"bingo11","ifram":"car11"},{"id":"12","nom":"testd","lienimg":"bingo12","ifram":"car12"},{"id":"13","nom":"test6","lienimg":"bingo13","ifram":"car13"},{"id":"14","nom":"testiu","lienimg":"bingo14","ifram":"car14"},{"id":"15","nom":"teste","lienimg":"bingo15","ifram":"car15"}]
in my page listevirtuelles.kt :
package com.example.bingmada
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
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.activity_listevirtuelles, 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.idvirtuelleli.setText(article.id)
holder.nomvisite.setText(article.nom)
holder.lieimgvisite.setText(article.lienimg)
holder.ifram.setText(article.ifram)
}
class MyViewHolder(var vue:View):RecyclerView.ViewHolder(vue){
var idvirtuelleli=vue.findViewById<TextView>(R.id.idvirtuelleli)
var nomvisite=vue.findViewById<TextView>(R.id.nom_virtuelleli)
var lieimgvisite=vue.findViewById<TextView>(R.id.lienimg)
var ifram=vue.findViewById<TextView>(R.id.ifram)
}
}
activity_main.xml 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: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>
a page activity_listevirtuelles.xml :
<?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/idvirtuelleli"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="id"
android:textSize="25dp"
/>
<TextView
android:id="#+id/nom_virtuelleli"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Lenom"
android:textSize="25dp"
/>
<TextView
android:id="#+id/lienimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="lien dimage"
android:textSize="25dp"
/>
<TextView
android:id="#+id/ifram"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="codeifram"
android:textSize="25dp"
/>
</LinearLayout>
can you help me find the problem please?
If you can see the relevant data in the activity. Since it is an asynchronous process, can you apply the structure I added to connect the data with recyclerview?
class MainActivity : AppCompatActivity() {
var adapter:ArticleAdapter ?=null
var articles:ArrayList<Article> ?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
articles= ArrayList()
adapter = ArticleAdapter(articles!!) // 1 line up to changed
getArticlesFromServer()
var recyclerView = findViewById<RecyclerView>(R.id.recyclevirtuel)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter=adapter
}
fun getArticlesFromServer(){
var url="https://www.exemplesite.com/android/bingmada.php"
var stringRequest=StringRequest(Request.Method.GET,url,Response.Listener { response -> parseData(response) }, Response.ErrorListener { error ->
Toast.makeText(this,"Erreur de connexion ", Toast.LENGTH_SHORT).show()
})
var req=Volley.newRequestQueue(this)
req.add(stringRequest)
}
fun parseData(response:String){
var arrayJson = JSONArray(response)
for(i in 0..arrayJson.length()-1){
var currentObject=arrayJson.getJSONObject(i)
var article = Article(currentObject.getInt("id"),
currentObject.getString("nom"),
currentObject.getString("lienimg"),
currentObject.getString("ifram"))
articles?.add(article)
}
adapter.notifydatasetchanged() // added
}
}
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)
I have a plain basic recycler view and its adapter.In the single recycler view row, I got a textView which are floating numbers.The textView width length shall fixed in proportional sizes, i.e. 30 % of the screen.I want to put OnGlobalLayoutListener to auto resize text downward passively whenever the text exceed over the separator lineso that it fits in the textView box prepared.I don't want WRAP the numbers
So I add OnGlobalLayoutListener on each ViewHolder and expect to detect & tracing each row items if the costTextView is Overlapped to the separator line.
However what happened is it does not resize all rows, but part of items that exposed on user screen only. Example 4-7 does not affected, 8-12 is affected, so on.
MainFragment.kt
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.elliot.financetracker.databinding.MainFragmentBinding
class MainFragment : Fragment() {
companion object {
private val TAG = "HomeFragment"
}
private lateinit var thisView: View
private lateinit var binding: MainFragmentBinding
private var cashList: ArrayList<Cash> = ArrayList()
private lateinit var recyclerView: RecyclerView
private lateinit var mAdapter: CashAdapter
init {
cashList = prepareMovieData()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
DataBindingUtil.inflate<MainFragmentBinding>(
inflater,
R.layout.main_fragment, container, false
)
thisView = binding.root
return thisView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = binding.rvCash
mAdapter = CashAdapter(cashList, action)
val mLayoutManager: RecyclerView.LayoutManager = LinearLayoutManager(thisView.context)
recyclerView.layoutManager = mLayoutManager
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.adapter = mAdapter
}
private val action = object : CashAdapter.ClickedListener {
override fun onItemClick(cash: Cash) {
val bundle = bundleOf("cash" to cash)
this#MainFragment.findNavController().navigate(R.id.edit_frag, bundle)
}
}
private val actionAddNewRecord = object : View.OnClickListener {
override fun onClick(v: View?) {
val arg = Bundle()
arg.putInt("sss", 43)
this#MainFragment.findNavController().navigate(R.id.edit_frag, arg)
}
}
private fun prepareMovieData(): ArrayList<Cash> {
for (i in 0..29) {
cashList.add(
Cash(
"-2000000000000000000000000.00",
"Action & Adventure $i"
)
)
}
return cashList
}
}
CashAdapter.kt
import android.graphics.Rect
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.elliot.financetracker.CashAdapter.CashViewHolder
import com.elliot.financetracker.databinding.CashListRowBinding
import com.elliot.financetracker.utils.*
//import com.example.recyclerviewbinding.databinding.MovieListRowBinding;
class CashAdapter(
private val cashList: List<Cash>,
private val clickedAction: ClickedListener
) : RecyclerView.Adapter<CashViewHolder>() {
companion object {
private var TAG = "CashAdapter"
}
inner class CashViewHolder(private val binding: CashListRowBinding) :
RecyclerView.ViewHolder(binding.root) {
var positionss: Int = -1
fun bind(cash: Cash, clickedAction: ClickedListener, positionss: Int) {
this.positionss = positionss
binding.cash = cash
binding.cvCashView.setOnClickListener {
clickedAction.onItemClick(binding.cash!!)
}
// ---------- NOTE HERE I ADD GLOBAL LAYOUT LISTENER ---------------------------------------------
this.binding.cvCashView.viewTreeObserver.addOnGlobalLayoutListener(globalObserver)
binding.executePendingBindings()
}
private val globalObserver = object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val overlapped = isOverlapped(binding.tvItemCost, binding.separatorCost)
if (overlapped) {
Log.d(CashAdapter.TAG, "${CashAdapter.TAG}: isOverlapping : $positionss")
binding.tvItemCost.textSize = resizeTextDown(binding.tvItemCost)
// always assumed values in SP units
} else {
Log.d(CashAdapter.TAG, "${CashAdapter.TAG}: isNotOverlapping : $positionss")
}
}
}
private fun resizeTextDown(target: View): Float {
val t = target as TextView
val z = t.textSize
val a = z.pxToSp()
val b = a - 2.0F
// leave it as SP unit will do**
return b
}
}
interface ClickedListener {
fun onItemClick(cash: Cash)
}
fun isOverlapped(tvItemCost: View, g20: View): Boolean {
val firstPosition = IntArray(2)
val secondPosition = IntArray(2)
tvItemCost.getLocationOnScreen(firstPosition)
g20.getLocationOnScreen(secondPosition)
val rectFirstView = Rect(
firstPosition[0],
firstPosition[1],
firstPosition[0] + tvItemCost.measuredWidth,
firstPosition[1] + tvItemCost.measuredHeight
)
val rectSecondView = Rect(
secondPosition[0],
secondPosition[1],
secondPosition[0] + g20.measuredWidth,
secondPosition[1] + g20.measuredHeight
)
return rectFirstView.intersect(rectSecondView)
}
// plain basic recycler view adapter's methods
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CashViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = CashListRowBinding.inflate(layoutInflater, parent, false)
return CashViewHolder(binding)
}
override fun onBindViewHolder(holder: CashViewHolder, position: Int) {
val cash = cashList[position]
holder.bind(cash, clickedAction, position)
}
override fun getItemCount(): Int {
return cashList.size
}
}
cash_list_row.xml
<?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="cash"
type="com.elliot.financetracker.Cash" />
</data>
<androidx.cardview.widget.CardView
android:id="#+id/cv_cash_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
app:cardBackgroundColor="#color/colorLightGreen"
app:cardElevation="10dp"
app:cardCornerRadius="#dimen/default_card_corner_radius"
app:cardUseCompatPadding="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="#+id/tv_description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="#{cash.description}"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="#id/g_20"
app:layout_constraintTop_toBottomOf="#id/tv_date"
tools:text="Item description Item description Item description Item description" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/g_20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.7"/>
<View
android:id="#+id/separator_cost"
android:layout_width="1dp"
android:layout_height="0dp"
android:padding="20dp"
android:background="#android:color/darker_gray"
app:layout_constraintLeft_toRightOf="#id/g_20"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="#+id/tv_item_cost"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="#{cash.amountString}"
android:gravity="center_vertical"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
tools:text="RM -2000000000.00" />
<!-- removed out ...........-->
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</layout>
This can be perfectly solved by the auto resizing feature of TextView
use something like this
<TextView
android:layout_width="100dp"
android:layout_height="40dp"
android:maxLines="1"
android:text="hello world google"
app:autoSizeTextType="uniform"
app:autoSizeMinTextSize="1sp"
app:autoSizeMaxTextSize="25sp"
android:gravity="center_vertical"
/>