0

Im running android studio 4.1.2 im trying to run this transaction:

QuestionDao.kt

  @Transaction
    suspend fun getRandomRN(num: Int):List<Question>{
     val result = getRandomWrongOrNotAnsweredQuestionsByCount(num)
        val last = getLastQuizNumber()

        val newResult = mutableListOf<Question>()

        result?.forEachIndexed{ index,element ->
            element.status=0
            element.quiz_number = last+1
            newResult[index] = element  // this is line 91
        }

        result?.let { updateQuestions(newResult) }
        return newResult
    }

running app throw error:

com.example.android.myapplication E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-2
    Process: com.example.android.myapplication, PID: 25245
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.set(ArrayList.java:453)
        at com.example.android.webpooyeshelevatorquize.data.QuestionDao$DefaultImpls.getRandomRN(QuestionDao.kt:91)

QuestionDao.kt:91 is newResult[index] = element.
BTW the context is Dispachers.IO

alex
  • 7,551
  • 13
  • 48
  • 80
  • 1
    Well it says there: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0. You are using an instance of ArrayList, so you should use newResult.add(index, element) instead of newResult[index] = element. Just check if its .add(index, element) or .add(element, index). – SlothCoding Jan 29 '21 at 22:01

2 Answers2

2

The newResult list is empty, you cannot use newResult[index] = element to add new elements to it. Use newResult += element or newResult.add(emenent) instead.

Mafor
  • 9,668
  • 2
  • 21
  • 36
0

You are actually trying to access the index of the array while you have not initialized any element to it. Initialize like this newResult.add(i)

Rajat Naik
  • 41
  • 6