How do I get key in kotlin in RecyclerView to send it to another activity?
I tried using getKey() and position but it doesn't work.
Here is my code:
class RecyclerAdapter (val userlist:ArrayList<RecyClass>,ccc: Context): RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
var mcontext =ccc
val Postdata = java.util.ArrayList<RecyClass>()
lateinit var ref:DatabaseReference
override fun getItemCount(): Int {
return userlist.size
}
override fun onBindViewHolder( holder: ViewHolder?, position: Int) {
val user: RecyClass = userlist[position]
ref = FirebaseDatabase.getInstance().getReference(user.toString())
holder?.txtviewdesc?.text = user.desc
Picasso.with(mcontext).load(user.image).into(holder?.imageviewx)
holder?.setOncustomcilcklistner(object :Custumclicklistner33{
override fun oncustomOnClickListner(view: View, pos: Int) {
}
})
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
this.Postdata
this.mcon
val v = LayoutInflater.from(parent?.context).inflate(R.layout.layoutrcview,parent,false)
return ViewHolder(v,mcon,userlist)
}
class ViewHolder(itemview: View,ccc2:Context,userlist: ArrayList<RecyClass>): RecyclerView.ViewHolder(itemview), View.OnClickListener{
var mCustIemClick5: Custumclicklistner33?=null
var txtviewdesc: TextView
var mcon =ccc2
var userdata =userlist
var imageviewx: ImageView
init {
this.userdata
this.mcon
txtviewdesc = itemview.findViewById<TextView>(R.id.editTextdesc)
imageviewx = itemview.findViewById<ImageView>(R.id.imgvw)
itemview.setOnClickListener(this)
}
fun setOncustomcilcklistner(customclick5: Custumclicklistner33){
this.mCustIemClick5=customclick5
}
override fun onClick(view: View?) {
this.mCustIemClick5!!.oncustomOnClickListner(view!!,adapterPosition)
val pos = adapterPosition
val ref =FirebaseDatabase.getInstance().getReference(pos.toString()).key.toString()
Toast.makeText(mcon,ref,Toast.LENGTH_LONG).show()
var postDetail = this.userdata[pos]
val kkk = Intent(this.mcon,ProfileActivity::class.java)
kkk.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
this.mcon.startActivity(kkk)
}
}
}
fun onclick takes to next activity but it takes post's key. How to get it?
getref and postiton is not working in fun onclick but it works on bindviewholder.
You need to use PostData[position] to get the object that current position and then a key/field from that object that you can reference.
Related
I feel that in this code my layout is not being attached.I verified by toast,log.d but nothing worked.Here this I am using for a recycler view view holder.Code is below
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.posts_layout,parent,false)
return ViewHolder(view)
}
and onBindViewHolder.I user log to check if this method is being used but,its not used
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
firebaseUser = FirebaseAuth.getInstance().currentUser!!
Log.d("binded", true.toString())
val post = mPost[position]
getPublisherInfo(holder.profileImage ,holder.userName , holder.userFullName ,post.getpublisher())
Glide.with(mContext).load(post.getpostId()).placeholder(R.drawable.image).into(holder.postImage)
}
I also checked if my list size id 0 for it to not come.For it use used log and it showed the list size 5 which is correct.This meant that my data is being retrieved from database.So it think that the my layout inflater is not working.The code for it is.
private fun readPosts() {
val postsRef = FirebaseDatabase.getInstance().reference.child("Posts")
postsRef.addValueEventListener(object : ValueEventListener{
#SuppressLint("NotifyDataSetChanged")
override fun onDataChange(snapshot: DataSnapshot) {
postList.clear()
for(snapshot in snapshot.children){
val post = snapshot.getValue(Post::class.java)
for (uid in (followingList as ArrayList<String>)) {
if (post!!.getpublisher().equals(uid)) {
postList.add(post)
}
Log.d("added", postList.size.toString())
Log.d("added", postList.toString())
postAdapter.notifyDataSetChanged()
}
}
}
override fun onCancelled(error: DatabaseError) {}
})
}
My entire adapter code is
package com.u_me_pro.free.Adapters
class PostAdapter(private val mContext: Context,private val mPost: List<Post>) :
RecyclerView.Adapter<PostAdapter.ViewHolder>() {
private lateinit var firebaseUser : FirebaseUser
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.posts_layout,parent,false)
Log.d("attached layout","true")
return ViewHolder(view)
}
class ViewHolder(#NonNull itemView: View) : RecyclerView.ViewHolder(itemView){
var description: TextView = itemView.findViewById(R.id.description)
var userName: TextView = itemView.findViewById(R.id.user_name_post)
var userFullName: TextView = itemView.findViewById(R.id.user_full_name_post)
var commentCount: TextView = itemView.findViewById(R.id.comment_count)
var likeCount: TextView = itemView.findViewById(R.id.love_count)
var profileImage: RoundedImageView = itemView.findViewById(R.id.user_profile_image_post)
var postImage: RoundedImageView = itemView.findViewById(R.id.post_image)
var like: CardView = itemView.findViewById(R.id.post_image_like)
var comment: CardView = itemView.findViewById(R.id.post_image_comment)
var save: CardView = itemView.findViewById(R.id.post_image_save)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
firebaseUser = FirebaseAuth.getInstance().currentUser!!
Log.d("binded", true.toString())
val post = mPost[position]
getPublisherInfo(holder.profileImage ,holder.userName , holder.userFullName ,post.getpublisher())
Glide.with(mContext).load(post.getpostId()).placeholder(R.drawable.image).into(holder.postImage)
}
override fun getItemCount(): Int {
return mPost.size
}
private fun getPublisherInfo(profileImage: RoundedImageView, userName: TextView, userFullName: TextView, publisherId: String) {
val usersRef = FirebaseDatabase.getInstance().reference.child("Users").child(publisherId)
Log.d("publisher id",publisherId)
usersRef.addValueEventListener(object :ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
val user = snapshot.getValue(User::class.java)
userName.text = user!!.getFullname()
userFullName.text = user.getFullname()
Glide.with(mContext).load(user.getImage()).placeholder(R.drawable.profile).into(profileImage)
}
}
override fun onCancelled(error: DatabaseError) {
Log.d(TAG, error.getMessage());
}
})
}
}
Please help me out soon.
Thanks!
You're updating the post list and notifying the adapter of a change but it doesn't appear that you're ever actually passing in the updated list to the adapter.
postAdapter.notifyDataSetChanged()
Won't do anything if the actual data in your adapter hasn't changed.
You should add a way to update your post list in the adapter such as
fun setPostData(posts: List<Post>) {
this.adapterPosts = posts
notifyDataSetChanged() // Either call this here or where you were before
}
This would also require you to create a new variable to hold the passed-in list
private var adapterPosts = mPosts
I have two activity and each activity has recyclerview, I have nested json.I want when user tap first activity recyclerview then they goes to next activity and show the recyclerview.Better understanding please follow the json link and code.
Json Link
: https://run.mocky.io/v3/8c3f6be2-a53f-47da-838c-72e603af844d
CropData.kt
data class CropData(
#SerializedName("cropImage")
val cropImage: String,
#SerializedName("cropName")
val cropName: String,
#SerializedName("cropTime")
val cropTime: String,
#SerializedName("cropDetails")
val cropDetails: String,
#SerializedName("cropProcess")
val cropProcess: String,
#SerializedName("cropType")
val cropType: String,
#SerializedName("cropFertilizer")
val cropFertilizer: List<CropFertilizer>
)
CropFertilizer.kt
data class CropFertilizer(
#SerializedName("fertilizerName")
val fertilizerName: String,
#SerializedName("fertilizerFirst")
val fertilizerFirst: String,
#SerializedName("fertilizerSecond")
val fertilizerSecond: String,
#SerializedName("fertilizerThird")
val fertilizerThird: String
)
CropActivity.kt
class CropActivity : AppCompatActivity(), CropOnItemClickListener {
private lateinit var viewModel: CropActivityViewModel
private val cropAdapter by lazy { CropAdapter(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_crop)
val repository = Repository()
val viewModelFactory = CropActivityViewModelFactory(repository)
viewModel = ViewModelProvider(this, viewModelFactory).get(CropActivityViewModel::class.java)
viewModel.getCropData()
viewModel.cropResponse.observe(this, Observer { response ->
cropAdapter.setData(response)
Log.d("dCrop", response.toString())
})
setUpCrops()
}
private fun setUpCrops() {
crop_recyclerview.layoutManager = LinearLayoutManager(
this,
LinearLayoutManager.VERTICAL, false
)
crop_recyclerview.setHasFixedSize(true)
crop_recyclerview.adapter = cropAdapter
}
override fun onClick(item: CropData, position: Int) {
val intent = Intent(this, CropDetailsActivity::class.java)
intent.putExtra("name", item.cropName)
intent.putExtra("image", item.cropImage)
intent.putExtra("intro", item.cropDetails)
intent.putExtra("process", item.cropProcess)
intent.putExtra("type", item.cropType)
intent.putExtra("time", item.cropTime)
startActivity(intent)
}
}
CropAdapter.kt
class CropAdapter(private val cropOnItemClickListener: CropOnItemClickListener) :
RecyclerView.Adapter<CropAdapter.ViewHolder>() {
private var cropList = emptyList<CropData>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.crop_row,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.crop_name.text = cropList[position].cropName
holder.itemView.crop_details.text = cropList[position].cropDetails
holder.itemView.crop_time.text = cropList[position].cropTime
holder.itemView.setOnClickListener{
cropOnItemClickListener.onClick(cropList[position],position)
}
}
override fun getItemCount(): Int {
return cropList.size
}
fun setData(newList: List<CropData>){
notifyDataSetChanged()
cropList = newList
notifyDataSetChanged()
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView)
}
CropDetailsActivity.kt
class CropDetailsActivity : AppCompatActivity() {
private lateinit var viewModel: CropDetailsActivityViewModel
private val fertlizerAdapter by lazy { FertilizerAdapter() }
private val cropFertilizerAdapter by lazy { FertilizerAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_crop_details)
val bundle:Bundle? = intent.extras
crop_details_name.text = bundle!!.getString("name")
val i: String = bundle!!.getString("intro")
crop_details_intro.text = i
Glide.with(this).load(bundle.getString("image")).into(crop_details_image);
val j: String = bundle!!.getString("process")
crop_details_process.text = j
crop_details_time.text = bundle!!.getString("time")
crop_details_type.text = bundle!!.getString("type")
val repository = Repository()
val viewModelFactory = CropDetailsActivityViewModelFactory(repository)
viewModel = ViewModelProvider(this, viewModelFactory).get(CropDetailsActivityViewModel::class.java)
viewModel.getFertilizer()
viewModel.fResponse.observe(this, Observer {
cropFertilizerAdapter.setData(it)
})
crop_details_recyclerview.layoutManager = LinearLayoutManager(
this,
LinearLayoutManager.VERTICAL, false
)
crop_details_recyclerview.setHasFixedSize(true)
crop_details_recyclerview.adapter = cropFertilizerAdapter
}
}
Better understanding see the image
[1]: https://i.stack.imgur.com/BtPqe.jpg
I want to show CropFertilizer list in CropDetailsActivity.How can i do this?
I just want to say sorry to my English skill
I've studied the Android Studio and Kotlin these days.
but I'd got a problem on RecyclerViewer and Adapter, for Intent method
work flow chart
this image, this is what i want to do
so i coded the three classes
ShoppingAppActivity.kt, MyAdapter.kt, CartActivity.kt
At ShoppingAppActivity, If I click the itemId ( in the Red box texts)
I make it move to other context(CartActivity)
ShoppingAppActivity working
if i clicked the red box then
cartStatus
go to cart Activity
it worked but already I said, I just want to send only send itemID
covert to String (i will use toString())
SO i tried to use Intent method in ShoppingAppActivity.kt
///PROBLEM PART
adapter?.setOnItemClickListener{
val nextIntent = Intent(this, CartActivity::class.java)
//nextIntent.putExtra("itemID", )
startActivity(nextIntent)
}
///PROBLEM PART
like this but the problem is I don't know what am i have to put the parameter in
nextIntent.putExtra("itemID", )
what should i do?
I think, I should fix MyAdaptor.kt or ShopingAppActivity.kt for this problem.
But in my knowledge, this is my limit. :-(
below
Full Codes of ShoppingAppActivity.kt, MyAdapter.kt, CartActivity.kt
ShoppingAppActivity.kt
class ShoppingAppActivity : AppCompatActivity() {
lateinit var binding: ActivityShoppingAppBinding
private var adapter: MyAdapter? = null
private val db : FirebaseFirestore = Firebase.firestore
private val itemsCollectionRef = db.collection("items")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityShoppingAppBinding.inflate(layoutInflater)
setContentView(binding.root)
updateList()
binding.recyclerViewItems.layoutManager = LinearLayoutManager(this)
adapter = MyAdapter(this, emptyList())
binding.recyclerViewItems.adapter = adapter
///PROBLEM PART
adapter?.setOnItemClickListener{
val nextIntent = Intent(this, CartActivity::class.java)
//nextIntent.putExtra("itemID", )
startActivity(nextIntent)
}
///PROBLEM PART
}
private fun updateList() {
itemsCollectionRef.get().addOnSuccessListener {
val items = mutableListOf<Item>()
for (doc in it) {
items.add(Item(doc))
}
adapter?.updateList(items)
}
}
}
MyAdapter.kt
data class Item(val id: String, val name: String, val price: Int, val cart: Boolean) {
constructor(doc: QueryDocumentSnapshot) :
this(doc.id, doc["name"].toString(), doc["price"].toString().toIntOrNull() ?: 0, doc["cart"].toString().toBoolean() ?: false)
constructor(key: String, map: Map<*, *>) :
this(key, map["name"].toString(), map["price"].toString().toIntOrNull() ?: 0, map["cart"].toString().toBoolean() ?: false)
}
class MyViewHolder(val binding: ItemBinding) : RecyclerView.ViewHolder(binding.root)
class MyAdapter(private val context: Context, private var items: List<Item>)
: RecyclerView.Adapter<MyViewHolder>() {
fun interface OnItemClickListener {
fun onItemClick(student_id: String)
}
private var itemClickListener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener) {
itemClickListener = listener
}
fun updateList(newList: List<Item>) {
items = newList
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding: ItemBinding = ItemBinding.inflate(inflater, parent, false)
return MyViewHolder(binding)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = items[position]
val itemID : String
holder.binding.textID.text = item.id
holder.binding.textName.text = item.name
if(item.cart)
{
holder.binding.textCart.text = "in Cart"
}
else
{
holder.binding.textCart.text = ""
}
holder.binding.textID.setOnClickListener {
AlertDialog.Builder(context).setMessage("You clicked ${item.id}.").show()
itemClickListener?.onItemClick(item.id)
}
holder.binding.textName.setOnClickListener {
//AlertDialog.Builder(context).setMessage("You clicked ${student.name}.").show()
itemClickListener?.onItemClick(item.id)
}
//return item.id.toString()
}
override fun getItemCount() = items.size
}
CartActivity.kt
class CartActivity : AppCompatActivity() {
lateinit var binding: ActivityCartBinding
private val db: FirebaseFirestore = Firebase.firestore
private val itemsCollectionRef = db.collection("items")
private var adapter: MyAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCartBinding.inflate(layoutInflater)
setContentView(binding.root)
updateList()
//binding.recyclerViewItems.layoutManager = LinearLayoutManager(this)
//adapter = MyAdapter(this, emptyList())
//binding.recyclerViewItems.adapter = adapter
binding.changeCartStatus.setOnClickListener{
//change the button's text if the itemID is corrected
//if(){
// binding.changeCartStatus.text = ""
//}
}
}
private fun updateList() {
itemsCollectionRef.get().addOnSuccessListener {
val items = mutableListOf<Item>()
for (doc in it) {
items.add(Item(doc))
}
adapter?.updateList(items)
}
}
}
You just need to implement listener to your activity
class ShoppingAppActivity : AppCompatActivity() ,MyAdapter.OnItemClickListener {
In oncreate add below line after adapter
adapter?.setOnItemClickListener(this)
Then override its method
override fun onItemClick(id: String){
val nextIntent = Intent(this, CartActivity::class.java)
nextIntent.putExtra("itemID",id )
startActivity(nextIntent)
}
Hi everyone ı am a new about android kotlin, I just try to pass the image from adapter to the other activity but it does not display. I used the intent code. What should I do ? I shared my adapter and the other activity code so you can see how ı used the intent code,
my adapter;
class NoteAdapter(private var titleText: ArrayList<String>, private var image: ArrayList<String>) : RecyclerView.Adapter<NoteAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemTitle : TextView = itemView.findViewById(R.id.recyclerTitleText)
val itemImage : ImageView = itemView.findViewById(R.id.recyclerImage)
init {
itemView.setOnClickListener { v: View ->
val intent = Intent(itemView.context, PastNotesActivity::class.java)
intent.putExtra("oldTitle", titleText[position])
intent.putExtra("oldImage", image[position] )
itemView.context.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_row, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemTitle.text = titleText[position]
Picasso.get().load(image[position]).resize(150,150).into(holder.itemImage)
}
override fun getItemCount(): Int {
return titleText.size
}
}
The other activity code,
class PastNotesActivity : AppCompatActivity() {
var selectedPicture: Uri? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_past_notes)
val intent = intent
val oldTitleName = intent.getStringExtra("oldTitle")
val oTitle = findViewById<TextView>(R.id.pastTitleText)
oTitle.text = oldTitleName
val oldImageView:Int = intent.getIntExtra("oldImage", 0)
val imageView = findViewById<ImageView>(R.id.pastImage)
imageView.setImageResource(oldImageView)
}
}
Inside your PastNotesActivity you are extracting IntExtra but you sent StringExtra.
Change your code from
val oldImageView:Int = intent.getIntExtra("oldImage", 0)
To
val oldImageView:String = intent.getStringExtra("oldImage", "")
Then load the image using Picasso as you did in your onBindViewHolder.
I am a new about making app. I want to pass the data from adapter to new activity with intent. I want to transfer PastNotesActivity, but it does not working.Because oldTitleName shows me the error: found String, Required editable. How can ı fix it ?
class NoteAdapter(private var titleText: ArrayList<String>, private var image: ArrayList<String>) : RecyclerView.Adapter<NoteAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemTitle : TextView = itemView.findViewById(R.id.recyclerTitleText)
val itemImage : ImageView = itemView.findViewById(R.id.recyclerImage)
init {
itemView.setOnClickListener { v: View ->
// Toast.makeText(itemView.context,"You clicked on item # ${position + 1}", Toast.LENGTH_SHORT).show()
val intent = Intent(itemView.context, PastNotesActivity::class.java)
intent.putExtra("oldTitle", titleText[position])
itemView.context.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_row, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemTitle.text = titleText[position]
Picasso.get().load(image[position]).into(holder.itemImage)
}
override fun getItemCount(): Int {
return titleText.size
}
}
This is PastNotesActivity, oldTitleName shows me the error: found String, Required editable. How can ı fix it ?
class PastNotesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_past_notes)
val intent = intent
val oldTitleName = intent.getStringExtra("oldTitle")
pastTitleText.text = oldTitleName
val navBarTitle = intent.getStringExtra("oldTitle")
supportActionBar?.title = navBarTitle
}
}
Lets say that you are passing the text of an item from your recyclerView to the textView of a desired activity.
Code this...
val intent = Intent(itemView.context, PastNotesActivity::class.java)
intent.putExtra("sampledText", "test123")
And code this in your desired activity...
val textFromIntent = intent.getStringExtra("sampledText")
textView.text = textFromintent