Home > Blockchain >  Loop implementation to XML file in kotlin
Loop implementation to XML file in kotlin

Time:10-29

I'm making an app in AndroidStudio that is generating 20 random pictures, I manage to make it work but my xml file that generate them is looking like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="cardImages">
        <item>https://picsum.photos/200/300?random=1</item>
        <item>https://picsum.photos/200/300?random=2</item>
        <item>https://picsum.photos/200/300?random=3</item>
        <item>https://picsum.photos/200/300?random=4</item>
        <item>https://picsum.photos/200/300?random=5</item>
        <item>https://picsum.photos/200/300?random=6</item>
        <item>https://picsum.photos/200/300?random=7</item>
        <item>https://picsum.photos/200/300?random=8</item>
        <item>https://picsum.photos/200/300?random=9</item>
        <item>https://picsum.photos/200/300?random=10</item>
        <item>https://picsum.photos/200/300?random=11</item>
        <item>https://picsum.photos/200/300?random=12</item>
        <item>https://picsum.photos/200/300?random=13</item>
        <item>https://picsum.photos/200/300?random=14</item>
        <item>https://picsum.photos/200/300?random=15</item>
        <item>https://picsum.photos/200/300?random=16</item>
        <item>https://picsum.photos/200/300?random=17</item>
        <item>https://picsum.photos/200/300?random=18</item>
        <item>https://picsum.photos/200/300?random=19</item>
        <item>https://picsum.photos/200/300?random=20</item>
    </string-array>
</resources>

What I want to know is if there is any way that I can transform this into a for loop in my MainActivity.kt that increments that last number on the URL

CodePudding user response:

val url = "https://picsum.photos/200/300?random=${Random.nextInt(1, 21)}"

or

// you could store this anywhere, if you want to keep URLs organised
const val BASE_URL = "https://picsum.photos/200/300?random="

// a function like this could handle different URLs if you like,
// or min/max values for the random number
fun getRandomImageUrl() = BASE_URL   Random.nextInt(1, 21)

There's no real benefit from having the URL as a string resource, unless you needed to access it from XML too for some reason. It's not something that needs to be translated either. But if you did want to store it in there, you could just store a template string:

// add an argument - in this case a decimal number
<string name="cardImageUrl">https://picsum.photos/200/300\?random=%1$d</string>

// then in your code (where you can call getString on a Context)
val url = getString(R.string.cardImageUrl, Random.nextInt(1, 21))

(Don't forget to escape the ?)


If you really do want to generate all of them instead of random ones:

val urls = (1..20).map { num -> "https://picsum.photos/200/300?random=$num" }
  • Related