Reputation: 314
very simple, android kotlin. i have a file in the project assest folder with sentence in each line. what i wants, is when i open dialog, it will select random line and put it as the dialog message. i couldn't find any proper solution. dialog's code:
class JokeFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val sentence: String = //random line from the file
// Use the Builder class for convenient dialog construction
val builder = Builder(it)
builder.setMessage(sentence)
.setNegativeButton(R.string.cancel){ _, _->}
// Create the AlertDialog object and return it
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
Upvotes: 0
Views: 254
Reputation: 1295
Based on this answer:
fun readRandomLineFromAsset(context: Context, fileName: String): String =
context
.assets
.open(fileName)
.bufferedReader()
.use(BufferedReader::readText)
.lines()
.shuffled()
.first()
Updated code - shuffled().first() instead of random()
Random picks same line every time fo some reason.
Upvotes: 1