0

I'm trying to add an intem to my arrayList when there new values added on my firebase database using this peace of code THIS IS A SAMPLE CODE ( the error happens when you click on send button ):

ref.addChildEventListener(object : ChildEventListener {

        override fun onCancelled(p0: DatabaseError) {
        }

        override fun onChildMoved(p0: DataSnapshot, p1: String?) {
        }


        override fun onChildChanged(dataSnapshot: DataSnapshot, p1: String?) {
        }

        @SuppressLint("LongLogTag")
        override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) {

            val newMSG: Messages? = dataSnapshot.getValue(Messages::class.java)

            val myrv = findViewById<RecyclerView>(R.id.msgRV)
            name = dataSnapshot.child("name").value.toString()
            muid = dataSnapshot.child("muid").value.toString()
            time = dataSnapshot.child("time").value.toString()
            message = dataSnapshot.child("message").value.toString()
            var contained = false
                messagesArrayList.forEach{ contained =  it.time !=time}
            if (messagesArrayList.isNotEmpty() && contained){
                messagesArrayList.add(Messages(newMSG?.name, newMSG?.mUID, newMSG?.time, newMSG?.message)) // The error is pointing here
                messagesArrayList = messagesArrayList.sortedWith(compareBy { it.time }) as MutableList<Messages>
                val myModulesAdapter = MessageRV(this@MessageActivity, messagesArrayList)
                myrv.layoutManager = GridLayoutManager(this@MessageActivity, 1)
                myrv.adapter = myModulesAdapter
                myrv.scrollToPosition(myModulesAdapter.itemCount - 1)

            }

        }

        override fun onChildRemoved(p0: DataSnapshot) {
        }
    })

But i got this error :

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.medanis.medmax, PID: 3533
    java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:153)
        at java.util.AbstractList.add(AbstractList.java:111)
        at com.medanis.medmax.messages.MessageActivity$onCreate$3.onChildAdded(MessageActivity.kt:148)
        at com.google.firebase.database.core.ChildEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.3.0:79)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.3.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.3.0:55)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)

Can anyone tell me what went wrong? How can I fix it?

NOTE : your database must be structred like this: Messages/MoIfH0sbt2UjJj7yozXRQF72RgK2/w691O35sZ2hvDpkTbAnm6aaTjZj1/ then a value of time in this format yyyyMMddHHmmss the Message Model content

SOLLUTION: Thanks to @Slaw and @AlexMamo, i solved the problem by changing { as MutableList } to { .toMutableList() }

(name, muid, time, message)

itzjackyscode
  • 970
  • 9
  • 27
MEDANIS
  • 107
  • 1
  • 10
  • 4
    Does this answer your question? [Java List.add() UnsupportedOperationException](https://stackoverflow.com/questions/5755477/java-list-add-unsupportedoperationexception) – jsamol May 26 '20 at 10:51
  • no because the add operation is supported by ArrayList and it works fine outside the addChildEventListener – MEDANIS May 26 '20 at 10:58
  • 1
    @MEDANIS Somewhere along the way you're getting an unmodifiable `List`. – Slaw May 26 '20 at 11:00
  • i already used the same ArrayList to collect data from the firebase DB using AddSingleValueListner and it works correctly – MEDANIS May 26 '20 at 11:02
  • At which particular line of code are you getting that error? Please respond with @AlexMamo – Alex Mamo May 26 '20 at 11:03
  • Then I suggest providing a [mre]. (@Alex there's a code comment indicating the line, though you have to scroll to the right) – Slaw May 26 '20 at 11:05
  • You mention collecting data into (supposedly) the same list. What does that look like? – Slaw May 26 '20 at 11:07
  • @Slaw i will make one wait for me please – MEDANIS May 26 '20 at 11:09
  • 2
    How is `messagesArrayList` defined? – Alex Mamo May 26 '20 at 11:10
  • @AlexMamo private var messagesArrayList: MutableList = ArrayList() i'm working to make a sample just u will got the full idea – MEDANIS May 26 '20 at 11:13
  • DONE check now the example don't forget to read the note in the last lines and for the first use just stop the addChildEventListener to pass data to the db then refrech – MEDANIS May 26 '20 at 11:42
  • @Slaw is there anything i can help you with ? – MEDANIS May 26 '20 at 11:55
  • @AlexMamo is there anything i can help you with ? – MEDANIS May 26 '20 at 11:55
  • 2
    I believe your problem is here: `messagesArrayList = messagesArrayList.sortedWith(compareBy { it.time }) as MutableList`. While you may be casting to a mutable list I believe the returned list remains unmodifiable. Perhaps you want https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sort-with.html instead, as that sorts the list in-place. – Slaw May 26 '20 at 12:23
  • @MEDANIS instead of casting it i.e. `as MutableList<..>` just use the extension function `.toMutableList()` it'll actually make the list mutable (by copying out the values). The original list returned from `sortedWith` might be immutable as pointed out by Slaw. – Animesh Sahu May 26 '20 at 12:46
  • Thank you. The answer is correct. It is sufficient to change "as MutableList" by ".toMutableList()"... Please add it as an answer to let the rest know...as Slaw said sortedWith returns immtablelist so the sollution is to turn it to mutableList again as Animesh Suhu said...thank you all – MEDANIS May 26 '20 at 18:39
  • Depending on your use case, you may want to consider using `sortWith` (note _not_ `sortedWith`), which I linked to in my previous comment. It will sort the list in-place rather than copying the elements into a new list. – Slaw May 27 '20 at 01:12
  • Thank you please juste put your answer your solution like an "answer" so i can approved to help others – MEDANIS May 27 '20 at 01:15

1 Answers1

2

SOLLUTION: Thanks to @Slaw and @AlexMamo, i solved the problem by changing { as MutableList } to { .toMutableList() }

MEDANIS
  • 107
  • 1
  • 10