Jacob26
Jacob26

Reputation: 31

How to add Items to a recyclerview Kotlin

package com.example.mytodolist

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.QuerySnapshot


class MainActivity : AppCompatActivity() {

    lateinit var storeTextView: EditText
    lateinit var itemTextView: EditText
    lateinit var buttonSave: Button

    lateinit var recyclerView: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val db = FirebaseFirestore.getInstance()

        val shoppingItems = mutableListOf<Item>()

        db.collection("items")
            .addSnapshotListener { snapshot, e ->
                if (snapshot != null) {
                    shoppingItems.clear()
                    for (document in snapshot.documents) {
                        val newItem = document.toObject(Item::class.java)
                        if (newItem != null) {
                            newItem.id = document.id
                            shoppingItems.add(newItem)
                        }
                    }
                    recyclerView.adapter?.notifyDataSetChanged()
                } else {
                    Log.w(
                        "hej",
                        "Error getting documents."
                    )
                }
            }



        recyclerView = findViewById<RecyclerView>(R.id.studentList)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = ItemRecyclerAdapter(this, shoppingItems)

        val fab = findViewById<View>(R.id.floatingActionButton)
        fab.setOnClickListener { view ->
            val intent = Intent(this, ChooseItem::class.java)
            startActivity(intent)

        }

    }

    override fun onResume() {
        super.onResume()
        recyclerView.adapter?.notifyDataSetChanged()
    }


}

Adapter

package com.example.mytodolist

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.firestore.FirebaseFirestore

class ItemRecyclerAdapter(private val context: Context, private val items: List<Item>) :
    RecyclerView.Adapter<ItemRecyclerAdapter.ViewHolder>() {
    private val layoutInflator = LayoutInflater.from(context)


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = layoutInflator.inflate(R.layout.student_list_view, parent, false)
        return ViewHolder(itemView)
    }

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val getItem = items[position]
        holder.itemName.text = getItem.store
        holder.textstoreName.text = getItem.item
        holder.itemPosition = position

    }

    fun removeItem(position: Int) {

        val db = FirebaseFirestore.getInstance()

        val item = items[position]
        val docId = item.id
        if(docId != null){
            db.collection("items").document(docId).delete()
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val itemName = itemView.findViewById<TextView>(R.id.item_name)
        val textstoreName = itemView.findViewById<TextView>(R.id.text_storeName)
        val delete = itemView.findViewById<ImageButton>(R.id.delete)
        var itemPosition = 0

        init {

            // Denna gör så att om du klickar på på en recyclerview field kommer du till en annan.

            itemView.setOnClickListener {
                val intent = Intent(context, ChooseItem::class.java)
                context.startActivity(intent)

            }
            delete.setOnClickListener { view ->
                removeItem(itemPosition)
                Snackbar.make(view, "Item Removed", Snackbar.LENGTH_SHORT).show()
            }

        }
    }
}

data structure

package com.example.mytodolist

data class Item(var store : String? = null,
                var item : String? = null,
                var id : String? = null
)

ChooseItem

package com.example.mytodolist

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.activity_choose_item.*

class ChooseItem : AppCompatActivity() {

    lateinit var  storeTextView : EditText
    lateinit var itemTextView : EditText



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_choose_item)

        storeTextView = findViewById(R.id.edit_store)
        itemTextView = findViewById(R.id.edit_item)

        val saveButton = findViewById<Button>(R.id.save_to_list)

        save_to_list.setOnClickListener { view ->
            addNewItem()
        }

    }
    private fun addNewItem() {

        val db = FirebaseFirestore.getInstance()


        val getStore = storeTextView.text.toString()
        val insertItem = itemTextView.text.toString()

        val item = Item(getStore, insertItem)
        db.collection("items").add(item)
        DataManager.items.add(item)
        finish()
    }

}

xml file

<?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="wrap_content">

    <TextView
        android:id="@+id/item_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/text_storeName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="59dp"
        android:text="TextView"
        app:layout_constraintEnd_toStartOf="@+id/delete"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageButton
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginEnd="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_delete" />
</androidx.constraintlayout.widget.ConstraintLayout>

`````````````````````````````````````````````````````````

/* I have createad a recyclerview useing Kotlin, you can add an item add store and press ADD button and these will be added into recyclerview:n. But I have tried to add more items in the same recyclerview use a clicklistener but I hav’nt found any good solution om internet?

How is it possible to make it work? */

Upvotes: 2

Views: 5928

Answers (1)

Muazzam A.
Muazzam A.

Reputation: 645

In your adapter class write a method:

   public fun updateItems(var newItems: List<Item>){
      this.items.clear()
      this.item.addAll(newItems)
   }

Then in your MainActivity onResume method, get the latest items from the database, and call your adapter class method in order to update items in RecyclerView like this:

recyclerView.adapter?.updateItems(newItems) // Pass the new items fetched from database.

override fun onResume() {
        super.onResume()
        // Fetch newItems from database
        recyclerView.adapter?.updateItems(newItems)
        recyclerView.adapter?.notifyDataSetChanged()
    }

Upvotes: 1

Related Questions