Android Kotlin: Wrong images showing in RecyclerView. How can I fix it? - android

the pictures I show in my recyclerview list are mixed with each other. Let's say that letter A indicates photo X, and letter B indicates photo Y. On my Recyclerview list, A is showing Y photo, and B shows the photo X.When I open the application again, there is no problem. I've been dealing with this problem for a few days, I've tried many solutions but I did not find a true solution until now. How should I solve it? Thanx
If you want to look my adapter and activity code, ı shared the below
My adapter:
class NoteAdapter(private var titleText: ArrayList<String>, private var imageButton: ArrayList<String>, private var noteText: 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])
intent.putExtra("oldNote", noteText[position])
intent.putExtra("oldImage", imageButton[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(imageButton[position]).resize(150,150).into(holder.itemImage)
}
override fun getItemCount(): Int {
return titleText.size
}
}
My Activity
class ListViewActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var db : FirebaseFirestore
var titleTextFromFB : ArrayList<String> = ArrayList()
var noteTextFromFB : ArrayList<String> = ArrayList()
var imageFromFB : ArrayList<String> = ArrayList()
var adapter: NoteAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_view)
auth = FirebaseAuth.getInstance()
db = FirebaseFirestore.getInstance()
getDataFromFirestore()
// recyclerview
var layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB)
recyclerView.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val menuInflater = menuInflater
menuInflater.inflate(R.menu.add_note, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.add_note_click) {
// Take Notes Activity
val intent = Intent(applicationContext, TakeNotesActivity::class.java)
intent.putExtra("info","new")
startActivity(intent)
} else if (item.itemId == R.id.log_out) {
val alert = AlertDialog.Builder(this)
alert.setTitle("Log Out")
alert.setMessage("Are you sure to logout from the app ?")
alert.setPositiveButton("Yes") {dialog, which ->
auth.signOut()
val intent = Intent(applicationContext, MainActivity::class.java)
startActivity(intent)
finish()
}
alert.setNegativeButton("No") {dialog, which ->
}
alert.show()
}
return super.onOptionsItemSelected(item)
}
// get data from firestore
fun getDataFromFirestore() {
db.collection("Notes").orderBy("date", Query.Direction.DESCENDING).addSnapshotListener{ snapshot, exception ->
if (exception != null) {
// If there is a error ,
Toast.makeText(applicationContext, exception.localizedMessage.toString(), Toast.LENGTH_LONG).show()
} else {
if (snapshot != null) {
if (!snapshot.isEmpty) {
titleTextFromFB.clear()
noteTextFromFB.clear()
val documents = snapshot.documents
for (document in documents) {
val userEmail = document.get("userEmail") as String
val noteTitle = document.get("noteTitle") as String
val yourNote = document.get("yourNote") as String
val downloadUrl = document.get("downloadUrl") as String
val timestamp = document.get("date") as Timestamp
val date = timestamp.toDate()
titleTextFromFB.add(noteTitle)
imageFromFB.add(downloadUrl)
noteTextFromFB.add(yourNote)
adapter!!.notifyDataSetChanged()
}
}
}
}
}
}
}

Related

Can't get received messages

Somehow I see in the app messages I sent, but can't see those which should be received from others. Also when I'm sending a message it's sent to all users. Here I'm sending two classes, adapter and main chat activity. I tried using inner classes, different types of getItemViewType functions but nothing works.
MessageAdapter
class MessageAdapter(val context: Context, val messageList: ArrayList<Message>):
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val ITEM_RECIEVE = 1
val ITEM_SENT = 2
class SentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
{
val sentMessage = itemView.findViewById<TextView>(R.id.txt_sent_message)
}
class RecieveViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
{
val recieveMessage = itemView.findViewById<TextView>(R.id.txt_recieve_message)
}
override fun getItemViewType(position: Int): Int {
val currentMessage = messageList[position]
if (FirebaseAuth.getInstance().currentUser?.uid.equals(currentMessage.senderId)) {
return ITEM_SENT
}
else {
return ITEM_RECIEVE
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == 1)
{
val view = LayoutInflater.from(context).inflate(R.layout.recieve, parent, false)
Log.d("tag2", "testrecieveviewholderview11")
return RecieveViewHolder(view)
}
else
{
val view = LayoutInflater.from(context).inflate(R.layout.sent, parent, false)
Log.d("tag", "testsentviewholderview22")
return SentViewHolder(view)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val currentMessage = messageList[position]
if(holder.javaClass == SentViewHolder::class.java)
{
val viewHolder = holder as SentViewHolder
holder.sentMessage.text = currentMessage.message
}
else
{
val viewHolder = holder as RecieveViewHolder
holder.recieveMessage.text = currentMessage.message
}
}
override fun getItemCount(): Int {
return messageList.size
}
}
And ChatActivity
var firebaseUser: FirebaseUser? = null
private lateinit var messageRecyclerView: RecyclerView
private lateinit var messageBox: EditText
private lateinit var sendButton: ImageButton
private lateinit var messageAdapter: MessageAdapter
private lateinit var messageList: ArrayList<Message>
private lateinit var mRef: DatabaseReference
var recieverRoom: String? = null
var senderRoom: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
val intent = Intent()
val name = intent.getStringExtra("name")
val recieverUid = intent.getStringExtra("uid")
val senderUid = FirebaseAuth.getInstance().currentUser?.uid
mRef = FirebaseDatabase.getInstance().reference
senderRoom = recieverUid + senderUid
recieverRoom = senderUid + recieverUid
messageRecyclerView = findViewById(R.id.RecyclerViewChat)
messageBox = findViewById(R.id.messageBox)
sendButton = findViewById(R.id.sendButton)
messageList = ArrayList()
messageAdapter = MessageAdapter(this, messageList)
messageRecyclerView.layoutManager = LinearLayoutManager(this)
messageRecyclerView.scrollToPosition(messageAdapter.itemCount-1)
messageRecyclerView.adapter = messageAdapter
mRef.child("chats").child(senderRoom!!).child("messages")
.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
messageList.clear()
for (postSnapshot in snapshot.children)
{
val message = postSnapshot.getValue(Message::class.java)
messageList.add(message!!)
}
messageAdapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
}
})
sendButton.setOnClickListener {
if (messageBox.text.toString().isEmpty() || messageBox.text.toString().isBlank())
{
messageBox.setText("")
}
else {
val message = messageBox.text.toString()
val messageObject = Message(message, senderUid)
mRef.child("chats").child(senderRoom!!).child("messages").push()
.setValue(messageObject).addOnSuccessListener {
mRef.child("chats").child(recieverRoom!!).child("messages").push()
.setValue(messageObject)
}
messageBox.setText("")
}
}
}
}
The error coming in this code is "Unresolved reference: message" and "Unresolved reference: senderId" in MessageAdapter. MessageAdapter is not able to take variables that are declared in Message class(message and senderId).

firebase data to recyclerview in fragment

This is my first time building an application and I have a problem with making a Recyclerview in a fragment with data from Firebase firestore & storage.
java.lang.NullPointerException: recycle_view must not be null
this is my data class
data class Wallitem (
var title:String,
var image:String,
var ref:String,
var price:String,
var students:String
)
and this is my adapter.kt
class WallAdapter(private var items: ArrayList<Wallitem>, private val context: Context) :
RecyclerView.Adapter<WallAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
Glide.with(context).load(item.image).into(holder.titleImage)
holder.titleTextView.text = item.title
holder.itemView.setOnClickListener {
val i = Intent(context, CoursePage::class.java)
val courseName: String = item.title
val image: String = item.image
val ref: String = item.ref
val price: String = item.price
val students: String = item.students
i.putExtra("courseName", courseName)
i.putExtra("courseImage", image)
i.putExtra("ref", ref)
i.putExtra("coursePrice", price)
i.putExtra("courseStudents", students)
context.startActivity(i)
}
}
override fun getItemCount(): Int {
return items.size
}
class ViewHolder(view: View?) : RecyclerView.ViewHolder(view!!) {
val titleImage:ImageView = view!!.findViewById(R.id.titleImageView)
val titleTextView:TextView = view!!.findViewById(R.id.titleTextView)
}
}
and this is my Fragment.kt (onCreateView part)
private lateinit var adapter: WallAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
val items:ArrayList<Wallitem> = ArrayList()
recycle_view.layoutManager = LinearLayoutManager(view.context, RecyclerView.HORIZONTAL,false)
adapter = WallAdapter(items,view.context)
val db : FirebaseFirestore = FirebaseFirestore.getInstance()
val storage : FirebaseStorage = FirebaseStorage.getInstance()
storage.maxDownloadRetryTimeMillis = 60000
storage.maxOperationRetryTimeMillis = 10000
progressBar.visibility = View.VISIBLE
LoadingTextView.visibility = View.VISIBLE
db.collection("courses").get()
.addOnSuccessListener {documents ->
for(document: QueryDocumentSnapshot in documents){
val wallItem = document.toObject(Wallitem::class.java)
//got title images
val storageRef: StorageReference = storage.reference.child("courses").child("images").child(document.id)
storageRef.list(1).addOnCompleteListener {result ->
val items:List<StorageReference> = result.result!!.items
//got first elements from the list to set title image
items.first().downloadUrl.addOnSuccessListener {
Log.d("storage " ,"$it")
wallItem.image = it.toString()
wallItem.ref = document.id
wallItem.title = document["courseName"].toString()
wallItem.price = document["price"].toString()
wallItem.students = document["students"].toString()
//if you need you may sort
recycle_view.adapter = adapter
}
}
items.add(wallItem)
}
}.addOnFailureListener {
Log.d("fail","Error getting document $it")
}.addOnCompleteListener {
progressBar.visibility = View.GONE
LoadingTextView.visibility = View.GONE
}
return view
}

Android Kotlin: How can I delete the data from Firebase

I am a new about Android Kotlin. I try to delete the data from Cloud Firebase when I click the button on my app. I did some necessary code on my adapter but How can ı call the database collection on my Activity? ı shared the my adapter and my Activity code below.
class NoteAdapter(val titleText: ArrayList<String>, val rowImage: ArrayList<String>, val noteText: ArrayList<String>, val listener: onClick) : RecyclerView.Adapter<NoteAdapter.NoteHolder>() {
interface onClick {
fun onItemClickListener(v: View, pos: Int, data: Any)
}
class NoteHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemImage : ImageView = itemView.findViewById(R.id.recyclerImage)
val itemDelete: ImageView = itemView.findViewById(R.id.delete)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_row, parent, false)
return NoteHolder(v)
}
override fun onBindViewHolder(holder: NoteHolder, position: Int) {
holder.itemView.recyclerTitleText.text = titleText[position]
Picasso.get().load(rowImage[position]).resize(150,150).into(holder.itemImage)
holder.itemView.setOnClickListener {
val intent = Intent(holder.itemView.context, PastNotesActivity:: class.java)
intent.putExtra("oldTitle", titleText[position])
intent.putExtra("oldNote", noteText[position])
intent.putExtra("oldImage", rowImage[position])
holder.itemView.context.startActivity(intent)
}
holder.itemDelete.setOnClickListener { v: View ->
titleText.removeAt(position)
noteText.removeAt(position)
rowImage.removeAt(position)
notifyItemRemoved(position)
listener.onItemClickListener(v, position, holder.itemView)
}
}
override fun getItemCount(): Int {
return titleText.size
}
override fun getItemId(position: Int):Long {
return position.toLong()
}
override fun getItemViewType(position: Int):Int {
return position
}
}
And This is my Activity code, I create the itemDelete fun in this Activity but How can I define my adapter code in this fun? and I tried to write "{id.data}" in my document but did not work what should I write ?
class ListViewActivity : AppCompatActivity() {
var selectedPicture: Uri? = null
private lateinit var auth: FirebaseAuth
private lateinit var db : FirebaseFirestore
var titleTextFromFB : ArrayList<String> = ArrayList()
var noteTextFromFB : ArrayList<String> = ArrayList()
var imageFromFB : ArrayList<String> = ArrayList()
var adapter: NoteAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_view)
auth = FirebaseAuth.getInstance()
db = FirebaseFirestore.getInstance()
getDataFromFirestore()
// recyclerview
var layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
// adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB)
//recyclerView.adapter = adapter
adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB, object: NoteAdapter.onClick{
override fun onItemClickListener(v: View, pos: Int, data: Any) {
when(v.id){
R.id.delete -> itemDelete(data)
}
}
})
recyclerView.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val menuInflater = menuInflater
menuInflater.inflate(R.menu.add_note, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.add_note_click) {
// Take Notes Activity
val intent = Intent(applicationContext, TakeNotesActivity::class.java)
intent.putExtra("info","new")
startActivity(intent)
} else if (item.itemId == R.id.log_out) {
val alert = AlertDialog.Builder(this)
alert.setTitle("Log Out")
alert.setMessage("Are you sure to logout from the app ?")
alert.setPositiveButton("Yes") {dialog, which ->
auth.signOut()
val intent = Intent(applicationContext, MainActivity::class.java)
startActivity(intent)
finish()
}
alert.setNegativeButton("No") {dialog, which ->
}
alert.show()
}
return super.onOptionsItemSelected(item)
}
// get data from firestore
fun getDataFromFirestore() {
db.collection("Notes").orderBy("date", Query.Direction.DESCENDING).addSnapshotListener{ snapshot, exception ->
if (exception != null) {
// If there is a error ,
Toast.makeText(applicationContext, exception.localizedMessage.toString(), Toast.LENGTH_LONG).show()
} else {
if (snapshot != null) {
if (!snapshot.isEmpty) {
titleTextFromFB.clear()
noteTextFromFB.clear()
imageFromFB.clear()
val documents = snapshot.documents
for (document in documents) {
val userEmail = document.get("userEmail") as String
val noteTitle = document.get("noteTitle") as String
val yourNote = document.get("yourNote") as String
val downloadUrl = document.get("downloadUrl") as String
val timestamp = document.get("date") as Timestamp
val date = timestamp.toDate()
titleTextFromFB.add(noteTitle)
imageFromFB.add(downloadUrl)
noteTextFromFB.add(yourNote)
adapter!!.notifyDataSetChanged()
}
}
}
}
}
}
fun itemDelete(data: Any) {
db.collection("Notes").document().delete().addOnSuccessListener {
}
.addOnFailureListener { exception ->
Toast.makeText(applicationContext, exception.localizedMessage.toString(), Toast.LENGTH_LONG).show()
}
}
}
This code won't work:
db.collection("Notes").document().delete().addOnSuccessListener {
The db.collection("Notes").document() call creates a reference to a new document, which you then delete. So nothing happens.
What you need to do is determine the ID of the document that the user clicked on, and pass that into the document(...) call. That gives you a DocumentReference to the correct document, so that the delete() call will then delete that document.
The key to determining the ID of the document the user clicked on is in this code:
adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB, object: NoteAdapter.onClick{
override fun onItemClickListener(v: View, pos: Int, data: Any) {
when(v.id){
R.id.delete -> itemDelete(data)
}
}
})
You will need to determine the ID from one of these parameters: v, post, or data. I typically do this by keeping a list of document IDs or DocumentSnapshot objects in my adapter or activity, and then looking the clicked item up by its position/index.
So in your getDataFromFirestore function, add the snapshots to a list that you've defined as a field in your activity class:
// in your activity, declare a list;
var mDocuments: List<DocumentSnapshot>? = null
// Then in getDataFromFirestore store that list
...
mDocuments = snapshot.documents;
val documents = snapshot.documents
for (document in documents) {
...
}
...
// And use it when calling itemDelete:
adapter = NoteAdapter(titleTextFromFB, imageFromFB, noteTextFromFB, object: NoteAdapter.onClick{
override fun onItemClickListener(v: View, pos: Int, data: Any) {
when(v.id){
R.id.delete -> itemDelete(mDocuments[pos])
}
}
})
// To then finally delete the document by its ID
fun itemDelete(doc: DocumentSnapshot) {
db.collection("Notes").document(doc.Id).delete()
}

how to filter list data in descending order in kotlin?

From the Android app, I wrote for I want to add, add a button in the toolbar that acts as a toggle. When the toggle is disabled (the default state) all posts should be shown, when it is enabled (after a tap) the list should only show the posts having user_id set to 1 and sorted by descending published_at. Tapping on the button again will return it to its default state.
Note that publishedAt returning date and publishedAt and user_id coming from postList from the server I want to know how can I implement above requirement what kind of steps should I have to follow
below my logic implementation in MainActivity.kt
class MainActivity : AppCompatActivity() {
#Inject
lateinit var restInterface: RestInterface
private fun initializeDagger() = App.appComponent.inject(this)
var context: Context? = null
private var filteredList: List<Post>? = null
private var recyclerView: RecyclerView? = null
private var switch1: Switch? = null
private var restAdapter: RestAdapter? = null
private var postList: List<Post>? = null
private var restList: RestList? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initializeDagger()
recyclerView = findViewById(R.id.recycler_view)
switch1 = findViewById(R.id.switch1)
fetchPosts()
switch1.setOnclickListener {
postList.forEach { postItem: Post ->
if (postItem.userId == 1)
filteredList.add(postItem)
}
recyclerView.post = filteredList
recyclerView.notifyDatasetChanged()
}
// Collections.sort( filteredList.get(4).publishedAt, Collections.reverseOrder());
}
private fun fetchPosts() {
val progress = ProgressDialog(this)
progress.setMessage("Loading... ")
progress.isIndeterminate = true
progress.show()
restInterface?.getPosts?.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableSingleObserver<Response<RestList>>() {
override fun onSuccess(response: Response<RestList>) {
restList = response.body()
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView?.layoutManager = layoutManager
// initialize postList with posts
postList = restList?.posts
restAdapter = postList?.let { RestAdapter(it, restList) }
recyclerView?.adapter = restAdapter
}
override fun onError(e: Throwable) {
progress.dismiss()
Toast.makeText(context, "" + e.message, Toast.LENGTH_SHORT).show()
}
})
}
}
below my RestAdapter.kt
class RestAdapter(val post: List<Post>,val restList: RestList?) : RecyclerView.Adapter<RestAdapter.PostHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.post_list, null)
return PostHolder(itemView)
}
override fun getItemCount(): Int {
return post.size
}
override fun onBindViewHolder(holder: PostHolder, position: Int) {
val posts = post[position]
Picasso
.get() // give it the context
.load(posts.image) // load the image
.into(holder.postImage)
holder.userId.text = posts.userId.toString()
holder.postTitle.text = posts.title
holder.postTime.text = posts.publishedAt
holder.postDescription.text = posts.description
}
class PostHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val postImage: ImageView = itemView.findViewById(R.id.postImage)
val userId: TextView = itemView.findViewById(R.id.userId)
val postTitle: TextView = itemView.findViewById(R.id.postTitle)
val postTime: TextView = itemView.findViewById(R.id.postTime)
val postDescription: TextView = itemView.findViewById(R.id.postDescription)
}
}
You can use method .sortedByDescending or .sortedBy on list :)
[Edit]
I give you a simple solution for that, maybe not the best but should work
1. Change RestAdapter constructor to (var post: List,val restList: RestList?)
Add method to updateData in apadapter:
fun filterData(isChecked: Boolean) {
if (isChecked) {
val filteredList = arrayListOf<Post>()
filteredList.addAll(restList?posts.filter { it.user_id == 1 }.sortedByDescending { it.published_at })
post = filteredList
} else {
post = restList?.posts
}
notifyDatasetChanged()
}
And in your class use this:
switch1.setOnclickListener {
restAdapter?.filterData(switch1.isChecked()//state of your switch i.e isChecked() which return true or false)
}

Listview duplicating itself whenever any event occurs in activity

I have backend firebase which i am using to populate the listview , i was implementing the search functionality suddenly i found a weird behavior in listview ,it is creating duplicates in numbers like 30-40 and above.
Please help me i was batteling for it from 3 days. i am very new to development so any suggestions to code optimizing will also be taken as help!
class Menu : AppCompatActivity(){
private var prevKey : String? = null
var listAdapter : CustomAdapter ? = null
private val listItemArrayList = ArrayList<ListItem>()
var rootRef : FirebaseDatabase? = null
var adminRef : DatabaseReference? = null
var mAuth : FirebaseAuth? = null
var helper : CustomAdapter?=null
private var user : String?=null
var mAuthListener: FirebaseAuth.AuthStateListener? = null
var Items = ArrayList<String>()
var isSectionBoolean = ArrayList<Boolean>()
var ItemCategory= ArrayList<String>()
var ItemCost = ArrayList<Int>()
var listView : ListView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu)
mAuth = FirebaseAuth.getInstance()
mAuthListener = FirebaseAuth.AuthStateListener { }
rootRef = FirebaseDatabase.getInstance()
user =mAuth!!.currentUser!!.phoneNumber as String
adminRef = rootRef!!.getReference("AdminCafe").child(user!!)
listView = findViewById(R.id.admindynamiclist)
listAdapter = CustomAdapter(listItemArrayList,this)
listView!!.adapter = listAdapter
listView!!.isTextFilterEnabled = true
SearchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
listAdapter!!.filter(newText.toString())
return false
}
})
getData()
}
fun addAct(v:View)
{
val intent = Intent(applicationContext,AddActivity::class.java)
startActivity(intent)
}
private fun getData() {
println("getData")
var menucatRef = adminRef!!.child("MenuItem")
menucatRef.addValueEventListener(object : ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
for(Snap in p0.children)
{
println("wtfff")
println("Child"+Snap.childrenCount)
getDataFromKey(Snap.key.toString(),Snap.childrenCount.toInt())
}
}
})
}
private fun getDataFromKey(key: String, child :Int) {
listItemArrayList.clear()
println("called")
var count = 0
var counter = 0
var Category = CategoryHeader()
var menuRef = adminRef!!.child("MenuItem").child(key)
menuRef.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
var catKey = p0.key.toString()
for(snap in p0!!.children)
{
if(count == 0)
{
Category!!.setheader(catKey)
listItemArrayList!!.add(Category)
println("Seperator will be added")
}
else
{
var hashMap = snap.value as HashMap<String,String>
var itemName = snap.key
var isVeg = hashMap["isVeg"]
var itemCost = hashMap["itemCost"]!!.toInt()
var isSig = hashMap["isSig"]
var ItemHelper = Item()
if(itemName!=null)
{
ItemHelper.setItemName(itemName)
}
if(itemCost!=null)
{
ItemHelper.setItemCost(itemCost)
}
listItemArrayList!!.add(ItemHelper)
}
count++
}
listAdapter!!.notifyDataSetChanged()
}
})
}
interface ListItem {
fun isHeader(): Boolean
fun getName(): String
fun getItemCost() : Int
}
fun editAct(v:View)
{
println("Inside edit")
}
}
And Adapter class
class CustomAdapter(private var listItem : ArrayList<Menu.ListItem>, private val context: Activity) : BaseAdapter() {
var orig = ArrayList<Menu.ListItem> ()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
orig.addAll(listItem)
println("List Item is"+listItem)
println("List Item is"+orig)
var holder = ViewHolder()
var customView = convertView
var flag = true
if (convertView == null) {
val layoutInflater = context.layoutInflater
if(listItem.get(position).isHeader()) {
println("position"+position)
customView = layoutInflater.inflate(R.layout.seperator, null)
holder.tvLabel = customView.categoryText
} else {
println("position"+position)
customView = layoutInflater.inflate(R.layout.list_item, null)
holder.tvLabel = customView.itemad
holder.itemCost = customView.cost
flag = false
}
customView.setTag(holder)
}
else
{
customView = convertView
holder = convertView!!.tag as ViewHolder
}
if(flag) {
println("Custoom Flag is"+flag)
holder!!.tvLabel!!.text = listItem.get(position).getName()
}
else {
println("Custoom Flag is"+flag)
holder!!.tvLabel!!.text = listItem.get(position).getName()
holder.itemCost!!.text = listItem.get(position).getItemCost().toString()
}
return customView!!
}
override fun getItem(position: Int): Any {
return listItem.get(position)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return listItem.size
}
private inner class ViewHolder {
var tvLabel: TextView? = null
var itemCost: TextView? = null
}
fun filter(query : String)
{
println("called")
listItem.clear()
var search = query
search = search.toLowerCase(Locale.getDefault())
if(search.isEmpty())
{
listItem.addAll(orig!!)
println("Inside size 0")
}
else
{
var counter = 0
for(result in orig!! )
{
if(result.getName().toLowerCase().contains(search))
{
println("Result is "+result.getName())
println("listItem"+listItem)
}
}
}
}
}

Categories

Resources